blob: 40bbb152690904070aa9e617dec7d383de95f50a [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) {
Douglas Gregora481ec42010-05-23 19:57:01 +0000537 // We don't allow variably-modified types as the type of non-type template
538 // parameters.
539 if (T->isVariablyModifiedType()) {
540 Diag(Loc, diag::err_variably_modified_nontype_template_param)
541 << T;
542 return QualType();
543 }
544
Douglas Gregor2943aed2009-03-03 04:44:36 +0000545 // C++ [temp.param]p4:
546 //
547 // A non-type template-parameter shall have one of the following
548 // (optionally cv-qualified) types:
549 //
550 // -- integral or enumeration type,
551 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000552 // -- pointer to object or pointer to function,
553 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000554 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
555 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000556 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000557 T->isReferenceType() ||
558 // -- pointer to member.
559 T->isMemberPointerType() ||
560 // If T is a dependent type, we can't do the check now, so we
561 // assume that it is well-formed.
562 T->isDependentType())
563 return T;
564 // C++ [temp.param]p8:
565 //
566 // A non-type template-parameter of type "array of T" or
567 // "function returning T" is adjusted to be of type "pointer to
568 // T" or "pointer to function returning T", respectively.
569 else if (T->isArrayType())
570 // FIXME: Keep the type prior to promotion?
571 return Context.getArrayDecayedType(T);
572 else if (T->isFunctionType())
573 // FIXME: Keep the type prior to promotion?
574 return Context.getPointerType(T);
Douglas Gregor0fddb972010-05-22 16:17:30 +0000575
Douglas Gregor2943aed2009-03-03 04:44:36 +0000576 Diag(Loc, diag::err_template_nontype_parm_bad_type)
577 << T;
578
579 return QualType();
580}
581
Douglas Gregor72c3f312008-12-05 18:15:24 +0000582/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
583/// template parameter (e.g., "int Size" in "template<int Size>
584/// class Array") has been parsed. S is the current scope and D is
585/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000586Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump1eb44332009-09-09 15:08:12 +0000587 unsigned Depth,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000588 unsigned Position) {
John McCalla93c9342009-12-07 02:54:59 +0000589 TypeSourceInfo *TInfo = 0;
590 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000591
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000592 assert(S->isTemplateParamScope() &&
593 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000594 bool Invalid = false;
595
596 IdentifierInfo *ParamName = D.getIdentifier();
597 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000598 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000599 LookupOrdinaryName,
600 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000601 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000602 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000603 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000604 }
605
Douglas Gregor2943aed2009-03-03 04:44:36 +0000606 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000607 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000608 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000609 Invalid = true;
610 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000611
Douglas Gregor72c3f312008-12-05 18:15:24 +0000612 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000613 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
614 D.getIdentifierLoc(),
John McCalla93c9342009-12-07 02:54:59 +0000615 Depth, Position, ParamName, T, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000616 if (Invalid)
617 Param->setInvalidDecl();
618
619 if (D.getIdentifier()) {
620 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000621 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000622 IdResolver.AddDecl(Param);
623 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000624 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000625}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000626
Douglas Gregord684b002009-02-10 19:49:53 +0000627/// \brief Adds a default argument to the given non-type template
628/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000629void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000630 SourceLocation EqualLoc,
631 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000632 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000633 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000634 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Douglas Gregord684b002009-02-10 19:49:53 +0000636 // C++ [temp.param]p14:
637 // A template-parameter shall not be used in its own default argument.
638 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000639
Douglas Gregord684b002009-02-10 19:49:53 +0000640 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000641 TemplateArgument Converted;
642 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
643 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000644 TemplateParm->setInvalidDecl();
645 return;
646 }
647
Anders Carlssone9146f22009-05-01 19:49:17 +0000648 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000649}
650
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000651
652/// ActOnTemplateTemplateParameter - Called when a C++ template template
653/// parameter (e.g. T in template <template <typename> class T> class array)
654/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000655Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
656 SourceLocation TmpLoc,
657 TemplateParamsTy *Params,
658 IdentifierInfo *Name,
659 SourceLocation NameLoc,
660 unsigned Depth,
Mike Stump1eb44332009-09-09 15:08:12 +0000661 unsigned Position) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000662 assert(S->isTemplateParamScope() &&
663 "Template template parameter not in template parameter scope!");
664
665 // Construct the parameter object.
666 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000667 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
668 TmpLoc, Depth, Position, Name,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000669 (TemplateParameterList*)Params);
670
671 // Make sure the parameter is valid.
672 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
673 // do anything yet. However, if the template parameter list or (eventual)
674 // default value is ever invalidated, that will propagate here.
675 bool Invalid = false;
676 if (Invalid) {
677 Param->setInvalidDecl();
678 }
679
680 // If the tt-param has a name, then link the identifier into the scope
681 // and lookup mechanisms.
682 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000683 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000684 IdResolver.AddDecl(Param);
685 }
686
Chris Lattnerb28317a2009-03-28 19:18:32 +0000687 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000688}
689
Douglas Gregord684b002009-02-10 19:49:53 +0000690/// \brief Adds a default argument to the given template template
691/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000692void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000693 SourceLocation EqualLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +0000694 const ParsedTemplateArgument &Default) {
Mike Stump1eb44332009-09-09 15:08:12 +0000695 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000696 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor788cd062009-11-11 01:00:40 +0000697
Douglas Gregord684b002009-02-10 19:49:53 +0000698 // C++ [temp.param]p14:
699 // A template-parameter shall not be used in its own default argument.
700 // FIXME: Implement this check! Needs a recursive walk over the types.
701
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000702 // Check only that we have a template template argument. We don't want to
703 // try to check well-formedness now, because our template template parameter
704 // might have dependent types in its template parameters, which we wouldn't
705 // be able to match now.
706 //
707 // If none of the template template parameter's template arguments mention
708 // other template parameters, we could actually perform more checking here.
709 // However, it isn't worth doing.
Douglas Gregor788cd062009-11-11 01:00:40 +0000710 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000711 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
712 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
713 << DefaultArg.getSourceRange();
Douglas Gregord684b002009-02-10 19:49:53 +0000714 return;
715 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000716
Douglas Gregor788cd062009-11-11 01:00:40 +0000717 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregord684b002009-02-10 19:49:53 +0000718}
719
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000720/// ActOnTemplateParameterList - Builds a TemplateParameterList that
721/// contains the template parameters in Params/NumParams.
722Sema::TemplateParamsTy *
723Sema::ActOnTemplateParameterList(unsigned Depth,
724 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000725 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000726 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000727 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000728 SourceLocation RAngleLoc) {
729 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000730 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000731
Douglas Gregorddc29e12009-02-06 22:42:48 +0000732 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000733 (NamedDecl**)Params, NumParams,
734 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000735}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000736
John McCallb6217662010-03-15 10:12:16 +0000737static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
738 if (SS.isSet())
739 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
740 SS.getRange());
741}
742
Douglas Gregor212e81c2009-03-25 00:13:59 +0000743Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000744Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000745 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000746 IdentifierInfo *Name, SourceLocation NameLoc,
747 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000748 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000749 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000750 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000751 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000752 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000753 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000754
755 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000756 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000757 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000758
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000759 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
760 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000761
762 // There is no such thing as an unnamed class template.
763 if (!Name) {
764 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000765 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000766 }
767
768 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000769 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000770 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000771 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000772 if (SS.isNotEmpty() && !SS.isInvalid()) {
773 SemanticContext = computeDeclContext(SS, true);
774 if (!SemanticContext) {
775 // FIXME: Produce a reasonable diagnostic here
776 return true;
777 }
Mike Stump1eb44332009-09-09 15:08:12 +0000778
John McCall77bb1aa2010-05-01 00:40:08 +0000779 if (RequireCompleteDeclContext(SS, SemanticContext))
780 return true;
781
John McCalla24dc2e2009-11-17 02:14:36 +0000782 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000783 } else {
784 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000785 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000786 }
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Douglas Gregor57265e32010-04-12 16:00:01 +0000788 if (Previous.isAmbiguous())
789 return true;
790
Douglas Gregorddc29e12009-02-06 22:42:48 +0000791 NamedDecl *PrevDecl = 0;
792 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000793 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000794
Douglas Gregorddc29e12009-02-06 22:42:48 +0000795 // If there is a previous declaration with the same name, check
796 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000797 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000798 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000799
800 // We may have found the injected-class-name of a class template,
801 // class template partial specialization, or class template specialization.
802 // In these cases, grab the template that is being defined or specialized.
803 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
804 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
805 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
806 PrevClassTemplate
807 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
808 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
809 PrevClassTemplate
810 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
811 ->getSpecializedTemplate();
812 }
813 }
814
John McCall65c49462009-12-18 11:25:59 +0000815 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000816 // C++ [namespace.memdef]p3:
817 // [...] When looking for a prior declaration of a class or a function
818 // declared as a friend, and when the name of the friend class or
819 // function is neither a qualified name nor a template-id, scopes outside
820 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000821 if (!SS.isSet()) {
822 DeclContext *OutermostContext = CurContext;
823 while (!OutermostContext->isFileContext())
824 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000825
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000826 if (PrevDecl &&
827 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
828 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
829 SemanticContext = PrevDecl->getDeclContext();
830 } else {
831 // Declarations in outer scopes don't matter. However, the outermost
832 // context we computed is the semantic context for our new
833 // declaration.
834 PrevDecl = PrevClassTemplate = 0;
835 SemanticContext = OutermostContext;
836 }
John McCalle129d442009-12-17 23:21:11 +0000837 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000838
John McCalle129d442009-12-17 23:21:11 +0000839 if (CurContext->isDependentContext()) {
840 // If this is a dependent context, we don't want to link the friend
841 // class template to the template in scope, because that would perform
842 // checking of the template parameter lists that can't be performed
843 // until the outer context is instantiated.
844 PrevDecl = PrevClassTemplate = 0;
845 }
846 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
847 PrevDecl = PrevClassTemplate = 0;
Douglas Gregor57265e32010-04-12 16:00:01 +0000848
Douglas Gregorddc29e12009-02-06 22:42:48 +0000849 if (PrevClassTemplate) {
850 // Ensure that the template parameter lists are compatible.
851 if (!TemplateParameterListsAreEqual(TemplateParams,
852 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000853 /*Complain=*/true,
854 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000855 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000856
857 // C++ [temp.class]p4:
858 // In a redeclaration, partial specialization, explicit
859 // specialization or explicit instantiation of a class template,
860 // the class-key shall agree in kind with the original class
861 // template declaration (7.1.5.3).
862 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000863 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000864 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000865 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000866 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000867 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000868 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000869 }
870
Douglas Gregorddc29e12009-02-06 22:42:48 +0000871 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000872 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000873 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000874 Diag(NameLoc, diag::err_redefinition) << Name;
875 Diag(Def->getLocation(), diag::note_previous_definition);
876 // FIXME: Would it make sense to try to "forget" the previous
877 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000878 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000879 }
880 }
881 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
882 // Maybe we will complain about the shadowed template parameter.
883 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
884 // Just pretend that we didn't see the previous declaration.
885 PrevDecl = 0;
886 } else if (PrevDecl) {
887 // C++ [temp]p5:
888 // A class template shall not have the same name as any other
889 // template, class, function, object, enumeration, enumerator,
890 // namespace, or type in the same scope (3.3), except as specified
891 // in (14.5.4).
892 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
893 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000894 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000895 }
896
Douglas Gregord684b002009-02-10 19:49:53 +0000897 // Check the template parameter list of this declaration, possibly
898 // merging in the template parameter list from the previous class
899 // template declaration.
900 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000901 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
902 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000903 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Douglas Gregor57265e32010-04-12 16:00:01 +0000905 if (SS.isSet()) {
906 // If the name of the template was qualified, we must be defining the
907 // template out-of-line.
908 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
909 !(TUK == TUK_Friend && CurContext->isDependentContext()))
910 Diag(NameLoc, diag::err_member_def_does_not_match)
911 << Name << SemanticContext << SS.getRange();
912 }
913
Mike Stump1eb44332009-09-09 15:08:12 +0000914 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000915 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000916 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000917 PrevClassTemplate->getTemplatedDecl() : 0,
918 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000919 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000920
921 ClassTemplateDecl *NewTemplate
922 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
923 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000924 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000925 NewClass->setDescribedClassTemplate(NewTemplate);
926
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000927 // Build the type for the class template declaration now.
John McCall3cb0ebd2010-03-10 03:28:59 +0000928 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
929 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000930 assert(T->isDependentType() && "Class template type is not dependent?");
931 (void)T;
932
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000933 // If we are providing an explicit specialization of a member that is a
934 // class template, make a note of that.
935 if (PrevClassTemplate &&
936 PrevClassTemplate->getInstantiatedFromMemberTemplate())
937 PrevClassTemplate->setMemberSpecialization();
938
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000939 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000940 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000941 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Douglas Gregorddc29e12009-02-06 22:42:48 +0000943 // Set the lexical context of these templates
944 NewClass->setLexicalDeclContext(CurContext);
945 NewTemplate->setLexicalDeclContext(CurContext);
946
John McCall0f434ec2009-07-31 02:45:11 +0000947 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000948 NewClass->startDefinition();
949
950 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000951 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000952
John McCall05b23ea2009-09-14 21:59:20 +0000953 if (TUK != TUK_Friend)
954 PushOnScopeChains(NewTemplate, S);
955 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000956 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000957 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000958 NewClass->setAccess(PrevClassTemplate->getAccess());
959 }
John McCall05b23ea2009-09-14 21:59:20 +0000960
Douglas Gregord85bea22009-09-26 06:47:28 +0000961 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
962 PrevClassTemplate != NULL);
963
John McCall05b23ea2009-09-14 21:59:20 +0000964 // Friend templates are visible in fairly strange ways.
965 if (!CurContext->isDependentContext()) {
966 DeclContext *DC = SemanticContext->getLookupContext();
967 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
968 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
969 PushOnScopeChains(NewTemplate, EnclosingScope,
970 /* AddToContext = */ false);
971 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000972
973 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
974 NewClass->getLocation(),
975 NewTemplate,
976 /*FIXME:*/NewClass->getLocation());
977 Friend->setAccess(AS_public);
978 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000979 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000980
Douglas Gregord684b002009-02-10 19:49:53 +0000981 if (Invalid) {
982 NewTemplate->setInvalidDecl();
983 NewClass->setInvalidDecl();
984 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000985 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000986}
987
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000988/// \brief Diagnose the presence of a default template argument on a
989/// template parameter, which is ill-formed in certain contexts.
990///
991/// \returns true if the default template argument should be dropped.
992static bool DiagnoseDefaultTemplateArgument(Sema &S,
993 Sema::TemplateParamListContext TPC,
994 SourceLocation ParamLoc,
995 SourceRange DefArgRange) {
996 switch (TPC) {
997 case Sema::TPC_ClassTemplate:
998 return false;
999
1000 case Sema::TPC_FunctionTemplate:
1001 // C++ [temp.param]p9:
1002 // A default template-argument shall not be specified in a
1003 // function template declaration or a function template
1004 // definition [...]
1005 // (This sentence is not in C++0x, per DR226).
1006 if (!S.getLangOptions().CPlusPlus0x)
1007 S.Diag(ParamLoc,
1008 diag::err_template_parameter_default_in_function_template)
1009 << DefArgRange;
1010 return false;
1011
1012 case Sema::TPC_ClassTemplateMember:
1013 // C++0x [temp.param]p9:
1014 // A default template-argument shall not be specified in the
1015 // template-parameter-lists of the definition of a member of a
1016 // class template that appears outside of the member's class.
1017 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1018 << DefArgRange;
1019 return true;
1020
1021 case Sema::TPC_FriendFunctionTemplate:
1022 // C++ [temp.param]p9:
1023 // A default template-argument shall not be specified in a
1024 // friend template declaration.
1025 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1026 << DefArgRange;
1027 return true;
1028
1029 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1030 // for friend function templates if there is only a single
1031 // declaration (and it is a definition). Strange!
1032 }
1033
1034 return false;
1035}
1036
Douglas Gregord684b002009-02-10 19:49:53 +00001037/// \brief Checks the validity of a template parameter list, possibly
1038/// considering the template parameter list from a previous
1039/// declaration.
1040///
1041/// If an "old" template parameter list is provided, it must be
1042/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1043/// template parameter list.
1044///
1045/// \param NewParams Template parameter list for a new template
1046/// declaration. This template parameter list will be updated with any
1047/// default arguments that are carried through from the previous
1048/// template parameter list.
1049///
1050/// \param OldParams If provided, template parameter list from a
1051/// previous declaration of the same template. Default template
1052/// arguments will be merged from the old template parameter list to
1053/// the new template parameter list.
1054///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001055/// \param TPC Describes the context in which we are checking the given
1056/// template parameter list.
1057///
Douglas Gregord684b002009-02-10 19:49:53 +00001058/// \returns true if an error occurred, false otherwise.
1059bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001060 TemplateParameterList *OldParams,
1061 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001062 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Douglas Gregord684b002009-02-10 19:49:53 +00001064 // C++ [temp.param]p10:
1065 // The set of default template-arguments available for use with a
1066 // template declaration or definition is obtained by merging the
1067 // default arguments from the definition (if in scope) and all
1068 // declarations in scope in the same way default function
1069 // arguments are (8.3.6).
1070 bool SawDefaultArgument = false;
1071 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001072
Anders Carlsson49d25572009-06-12 23:20:15 +00001073 bool SawParameterPack = false;
1074 SourceLocation ParameterPackLoc;
1075
Mike Stump1a35fde2009-02-11 23:03:27 +00001076 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001077 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001078 if (OldParams)
1079 OldParam = OldParams->begin();
1080
1081 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1082 NewParamEnd = NewParams->end();
1083 NewParam != NewParamEnd; ++NewParam) {
1084 // Variables used to diagnose redundant default arguments
1085 bool RedundantDefaultArg = false;
1086 SourceLocation OldDefaultLoc;
1087 SourceLocation NewDefaultLoc;
1088
1089 // Variables used to diagnose missing default arguments
1090 bool MissingDefaultArg = false;
1091
Anders Carlsson49d25572009-06-12 23:20:15 +00001092 // C++0x [temp.param]p11:
1093 // If a template parameter of a class template is a template parameter pack,
1094 // it must be the last template parameter.
1095 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001096 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001097 diag::err_template_param_pack_must_be_last_template_parameter);
1098 Invalid = true;
1099 }
1100
Douglas Gregord684b002009-02-10 19:49:53 +00001101 if (TemplateTypeParmDecl *NewTypeParm
1102 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001103 // Check the presence of a default argument here.
1104 if (NewTypeParm->hasDefaultArgument() &&
1105 DiagnoseDefaultTemplateArgument(*this, TPC,
1106 NewTypeParm->getLocation(),
1107 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001108 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001109 NewTypeParm->removeDefaultArgument();
1110
1111 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001112 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001113 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Anders Carlsson49d25572009-06-12 23:20:15 +00001115 if (NewTypeParm->isParameterPack()) {
1116 assert(!NewTypeParm->hasDefaultArgument() &&
1117 "Parameter packs can't have a default argument!");
1118 SawParameterPack = true;
1119 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001120 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001121 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001122 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1123 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1124 SawDefaultArgument = true;
1125 RedundantDefaultArg = true;
1126 PreviousDefaultArgLoc = NewDefaultLoc;
1127 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1128 // Merge the default argument from the old declaration to the
1129 // new declaration.
1130 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001131 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001132 true);
1133 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1134 } else if (NewTypeParm->hasDefaultArgument()) {
1135 SawDefaultArgument = true;
1136 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1137 } else if (SawDefaultArgument)
1138 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001139 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001140 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001141 // Check the presence of a default argument here.
1142 if (NewNonTypeParm->hasDefaultArgument() &&
1143 DiagnoseDefaultTemplateArgument(*this, TPC,
1144 NewNonTypeParm->getLocation(),
1145 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1146 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1147 NewNonTypeParm->setDefaultArgument(0);
1148 }
1149
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001150 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001151 NonTypeTemplateParmDecl *OldNonTypeParm
1152 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001153 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001154 NewNonTypeParm->hasDefaultArgument()) {
1155 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1156 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1157 SawDefaultArgument = true;
1158 RedundantDefaultArg = true;
1159 PreviousDefaultArgLoc = NewDefaultLoc;
1160 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1161 // Merge the default argument from the old declaration to the
1162 // new declaration.
1163 SawDefaultArgument = true;
1164 // FIXME: We need to create a new kind of "default argument"
1165 // expression that points to a previous template template
1166 // parameter.
1167 NewNonTypeParm->setDefaultArgument(
1168 OldNonTypeParm->getDefaultArgument());
1169 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1170 } else if (NewNonTypeParm->hasDefaultArgument()) {
1171 SawDefaultArgument = true;
1172 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1173 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001174 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001175 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001176 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001177 TemplateTemplateParmDecl *NewTemplateParm
1178 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001179 if (NewTemplateParm->hasDefaultArgument() &&
1180 DiagnoseDefaultTemplateArgument(*this, TPC,
1181 NewTemplateParm->getLocation(),
1182 NewTemplateParm->getDefaultArgument().getSourceRange()))
1183 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1184
1185 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001186 TemplateTemplateParmDecl *OldTemplateParm
1187 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001188 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001189 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001190 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1191 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001192 SawDefaultArgument = true;
1193 RedundantDefaultArg = true;
1194 PreviousDefaultArgLoc = NewDefaultLoc;
1195 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1196 // Merge the default argument from the old declaration to the
1197 // new declaration.
1198 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001199 // FIXME: We need to create a new kind of "default argument" expression
1200 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001201 NewTemplateParm->setDefaultArgument(
1202 OldTemplateParm->getDefaultArgument());
Douglas Gregor788cd062009-11-11 01:00:40 +00001203 PreviousDefaultArgLoc
1204 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001205 } else if (NewTemplateParm->hasDefaultArgument()) {
1206 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001207 PreviousDefaultArgLoc
1208 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001209 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001210 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001211 }
1212
1213 if (RedundantDefaultArg) {
1214 // C++ [temp.param]p12:
1215 // A template-parameter shall not be given default arguments
1216 // by two different declarations in the same scope.
1217 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1218 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1219 Invalid = true;
1220 } else if (MissingDefaultArg) {
1221 // C++ [temp.param]p11:
1222 // If a template-parameter has a default template-argument,
1223 // all subsequent template-parameters shall have a default
1224 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001225 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001226 diag::err_template_param_default_arg_missing);
1227 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1228 Invalid = true;
1229 }
1230
1231 // If we have an old template parameter list that we're merging
1232 // in, move on to the next parameter.
1233 if (OldParams)
1234 ++OldParam;
1235 }
1236
1237 return Invalid;
1238}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001239
Mike Stump1eb44332009-09-09 15:08:12 +00001240/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001241/// specifier, returning the template parameter list that applies to the
1242/// name.
1243///
1244/// \param DeclStartLoc the start of the declaration that has a scope
1245/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001246///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001247/// \param SS the scope specifier that will be matched to the given template
1248/// parameter lists. This scope specifier precedes a qualified name that is
1249/// being declared.
1250///
1251/// \param ParamLists the template parameter lists, from the outermost to the
1252/// innermost template parameter lists.
1253///
1254/// \param NumParamLists the number of template parameter lists in ParamLists.
1255///
John McCall77e8b112010-04-13 20:37:33 +00001256/// \param IsFriend Whether to apply the slightly different rules for
1257/// matching template parameters to scope specifiers in friend
1258/// declarations.
1259///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001260/// \param IsExplicitSpecialization will be set true if the entity being
1261/// declared is an explicit specialization, false otherwise.
1262///
Mike Stump1eb44332009-09-09 15:08:12 +00001263/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001264/// name that is preceded by the scope specifier @p SS. This template
1265/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001266/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001267/// template specialization), or may be NULL (if we were's declaring isn't
1268/// itself a template).
1269TemplateParameterList *
1270Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1271 const CXXScopeSpec &SS,
1272 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001273 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001274 bool IsFriend,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001275 bool &IsExplicitSpecialization) {
1276 IsExplicitSpecialization = false;
1277
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001278 // Find the template-ids that occur within the nested-name-specifier. These
1279 // template-ids will match up with the template parameter lists.
1280 llvm::SmallVector<const TemplateSpecializationType *, 4>
1281 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001282 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1283 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001284 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1285 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001286 const Type *T = NNS->getAsType();
1287 if (!T) break;
1288
1289 // C++0x [temp.expl.spec]p17:
1290 // A member or a member template may be nested within many
1291 // enclosing class templates. In an explicit specialization for
1292 // such a member, the member declaration shall be preceded by a
1293 // template<> for each enclosing class template that is
1294 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001295 //
1296 // Following the existing practice of GNU and EDG, we allow a typedef of a
1297 // template specialization type.
1298 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1299 T = TT->LookThroughTypedefs().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001300
Mike Stump1eb44332009-09-09 15:08:12 +00001301 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001302 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001303 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1304 if (!Template)
1305 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001306
Ted Kremenek6217b802009-07-29 21:53:49 +00001307 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001308 ClassTemplateSpecializationDecl *SpecDecl
1309 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1310 // If the nested name specifier refers to an explicit specialization,
1311 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001312 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1313 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001314 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001315 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001316 }
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001318 TemplateIdsInSpecifier.push_back(SpecType);
1319 }
1320 }
Mike Stump1eb44332009-09-09 15:08:12 +00001321
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001322 // Reverse the list of template-ids in the scope specifier, so that we can
1323 // more easily match up the template-ids and the template parameter lists.
1324 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001326 SourceLocation FirstTemplateLoc = DeclStartLoc;
1327 if (NumParamLists)
1328 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001329
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001330 // Match the template-ids found in the specifier to the template parameter
1331 // lists.
1332 unsigned Idx = 0;
1333 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1334 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001335 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1336 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001337 if (Idx >= NumParamLists) {
1338 // We have a template-id without a corresponding template parameter
1339 // list.
John McCall77e8b112010-04-13 20:37:33 +00001340
1341 // ...which is fine if this is a friend declaration.
1342 if (IsFriend) {
1343 IsExplicitSpecialization = true;
1344 break;
1345 }
1346
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001347 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001348 // FIXME: the location information here isn't great.
1349 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001350 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001351 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001352 << SS.getRange();
1353 } else {
1354 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1355 << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00001356 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001357 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001358 }
1359 return 0;
1360 }
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001362 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001363 if (DependentTemplateId) {
John McCall31f17ec2010-04-27 00:57:59 +00001364 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00001365
John McCall31f17ec2010-04-27 00:57:59 +00001366 // Are there cases in (e.g.) friends where this won't match?
1367 if (const InjectedClassNameType *Injected
1368 = TemplateId->getAs<InjectedClassNameType>()) {
1369 CXXRecordDecl *Record = Injected->getDecl();
1370 if (ClassTemplatePartialSpecializationDecl *Partial =
1371 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1372 ExpectedTemplateParams = Partial->getTemplateParameters();
1373 else
1374 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1375 ->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001376 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001377
John McCall31f17ec2010-04-27 00:57:59 +00001378 if (ExpectedTemplateParams)
1379 TemplateParameterListsAreEqual(ParamLists[Idx],
1380 ExpectedTemplateParams,
1381 true, TPL_TemplateMatch);
1382
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001383 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregorb88e8882009-07-30 17:40:51 +00001384 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001385 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001386 diag::err_template_param_list_matches_nontemplate)
1387 << TemplateId
1388 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001389 else
1390 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001391 }
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001393 // If there were at least as many template-ids as there were template
1394 // parameter lists, then there are no template parameter lists remaining for
1395 // the declaration itself.
1396 if (Idx >= NumParamLists)
1397 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001398
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001399 // If there were too many template parameter lists, complain about that now.
1400 if (Idx != NumParamLists - 1) {
1401 while (Idx < NumParamLists - 1) {
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001402 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001403 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001404 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1405 : diag::err_template_spec_extra_headers)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001406 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1407 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001408
1409 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1410 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1411 diag::note_explicit_template_spec_does_not_need_header)
1412 << ExplicitSpecializationsInSpecifier.back();
1413 ExplicitSpecializationsInSpecifier.pop_back();
1414 }
1415
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001416 ++Idx;
1417 }
1418 }
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001420 // Return the last template parameter list, which corresponds to the
1421 // entity being declared.
1422 return ParamLists[NumParamLists - 1];
1423}
1424
Douglas Gregor7532dc62009-03-30 22:58:21 +00001425QualType Sema::CheckTemplateIdType(TemplateName Name,
1426 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001427 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001428 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001429 if (!Template) {
1430 // The template name does not resolve to a template, so we just
1431 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001432 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001433 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001434
Douglas Gregor40808ce2009-03-09 23:48:35 +00001435 // Check that the template argument list is well-formed for this
1436 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001437 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCalld5532b62009-11-23 01:53:49 +00001438 TemplateArgs.size());
1439 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001440 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001441 return QualType();
1442
Mike Stump1eb44332009-09-09 15:08:12 +00001443 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001444 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001445 "Converted template argument list is too short!");
1446
1447 QualType CanonType;
John McCall31f17ec2010-04-27 00:57:59 +00001448 bool IsCurrentInstantiation = false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001449
Douglas Gregorcaddba02009-11-12 18:38:13 +00001450 if (Name.isDependent() ||
1451 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001452 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001453 // This class template specialization is a dependent
1454 // type. Therefore, its canonical type is another class template
1455 // specialization type that contains all of the converted
1456 // arguments in canonical form. This ensures that, e.g., A<T> and
1457 // A<T, T> have identical types when A is declared as:
1458 //
1459 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001460 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001461 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001462 Converted.getFlatArguments(),
1463 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Douglas Gregor1275ae02009-07-28 23:00:59 +00001465 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001466 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001467 // In the future, we need to teach getTemplateSpecializationType to only
1468 // build the canonical type and return that to us.
1469 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001470
1471 // This might work out to be a current instantiation, in which
1472 // case the canonical type needs to be the InjectedClassNameType.
1473 //
1474 // TODO: in theory this could be a simple hashtable lookup; most
1475 // changes to CurContext don't change the set of current
1476 // instantiations.
1477 if (isa<ClassTemplateDecl>(Template)) {
1478 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1479 // If we get out to a namespace, we're done.
1480 if (Ctx->isFileContext()) break;
1481
1482 // If this isn't a record, keep looking.
1483 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1484 if (!Record) continue;
1485
1486 // Look for one of the two cases with InjectedClassNameTypes
1487 // and check whether it's the same template.
1488 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1489 !Record->getDescribedClassTemplate())
1490 continue;
1491
1492 // Fetch the injected class name type and check whether its
1493 // injected type is equal to the type we just built.
1494 QualType ICNT = Context.getTypeDeclType(Record);
1495 QualType Injected = cast<InjectedClassNameType>(ICNT)
1496 ->getInjectedSpecializationType();
1497
1498 if (CanonType != Injected->getCanonicalTypeInternal())
1499 continue;
1500
1501 // If so, the canonical type of this TST is the injected
1502 // class name type of the record we just found.
1503 assert(ICNT.isCanonical());
1504 CanonType = ICNT;
1505 IsCurrentInstantiation = true;
1506 break;
1507 }
1508 }
Mike Stump1eb44332009-09-09 15:08:12 +00001509 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001510 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001511 // Find the class template specialization declaration that
1512 // corresponds to these arguments.
1513 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001514 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001515 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001516 Converted.flatSize(),
1517 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001518 void *InsertPos = 0;
1519 ClassTemplateSpecializationDecl *Decl
1520 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1521 if (!Decl) {
1522 // This is the first time we have referenced this class template
1523 // specialization. Create the canonical declaration and add it to
1524 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001525 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00001526 ClassTemplate->getTemplatedDecl()->getTagKind(),
1527 ClassTemplate->getDeclContext(),
1528 ClassTemplate->getLocation(),
1529 ClassTemplate,
1530 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001531 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1532 Decl->setLexicalDeclContext(CurContext);
1533 }
1534
1535 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001536 assert(isa<RecordType>(CanonType) &&
1537 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001538 }
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Douglas Gregor40808ce2009-03-09 23:48:35 +00001540 // Build the fully-sugared type for this class template
1541 // specialization, which refers back to the class template
1542 // specialization we created or found.
John McCall31f17ec2010-04-27 00:57:59 +00001543 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType,
1544 IsCurrentInstantiation);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001545}
1546
Douglas Gregorcc636682009-02-17 23:15:12 +00001547Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001548Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001549 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001550 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001551 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001552 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001553
Douglas Gregor40808ce2009-03-09 23:48:35 +00001554 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001555 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001556 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001557
John McCalld5532b62009-11-23 01:53:49 +00001558 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001559 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001560
1561 if (Result.isNull())
1562 return true;
1563
John McCalla93c9342009-12-07 02:54:59 +00001564 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001565 TemplateSpecializationTypeLoc TL
1566 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1567 TL.setTemplateNameLoc(TemplateLoc);
1568 TL.setLAngleLoc(LAngleLoc);
1569 TL.setRAngleLoc(RAngleLoc);
1570 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1571 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1572
1573 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCall6b2becf2009-09-08 17:47:29 +00001574}
John McCallf1bbbb42009-09-04 01:14:41 +00001575
John McCall6b2becf2009-09-08 17:47:29 +00001576Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1577 TagUseKind TUK,
1578 DeclSpec::TST TagSpec,
1579 SourceLocation TagLoc) {
1580 if (TypeResult.isInvalid())
1581 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001582
John McCall833ca992009-10-29 08:12:44 +00001583 // FIXME: preserve source info, ideally without copying the DI.
John McCalla93c9342009-12-07 02:54:59 +00001584 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001585 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001586
John McCall6b2becf2009-09-08 17:47:29 +00001587 // Verify the tag specifier.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001588 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001589
John McCall6b2becf2009-09-08 17:47:29 +00001590 if (const RecordType *RT = Type->getAs<RecordType>()) {
1591 RecordDecl *D = RT->getDecl();
1592
1593 IdentifierInfo *Id = D->getIdentifier();
1594 assert(Id && "templated class must have an identifier");
1595
1596 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1597 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001598 << Type
Douglas Gregor849b2432010-03-31 17:46:05 +00001599 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001600 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001601 }
1602 }
1603
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001604 ElaboratedTypeKeyword Keyword
1605 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1606 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCall6b2becf2009-09-08 17:47:29 +00001607
1608 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001609}
1610
John McCallf7a1a742009-11-24 19:00:30 +00001611Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1612 LookupResult &R,
1613 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001614 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001615 // FIXME: Can we do any checking at this point? I guess we could check the
1616 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001617 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001618 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001619
1620 // These should be filtered out by our callers.
1621 assert(!R.empty() && "empty lookup results when building templateid");
1622 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1623
1624 NestedNameSpecifier *Qualifier = 0;
1625 SourceRange QualifierRange;
1626 if (SS.isSet()) {
1627 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1628 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001629 }
John McCallc373d482010-01-27 01:50:18 +00001630
1631 // We don't want lookup warnings at this point.
1632 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001633
John McCallf7a1a742009-11-24 19:00:30 +00001634 bool Dependent
1635 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1636 &TemplateArgs);
1637 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001638 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001639 Qualifier, QualifierRange,
1640 R.getLookupName(), R.getNameLoc(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00001641 RequiresADL, TemplateArgs,
1642 R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001643
1644 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001645}
1646
John McCallf7a1a742009-11-24 19:00:30 +00001647// We actually only call this from template instantiation.
1648Sema::OwningExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001649Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001650 DeclarationName Name,
1651 SourceLocation NameLoc,
1652 const TemplateArgumentListInfo &TemplateArgs) {
1653 DeclContext *DC;
1654 if (!(DC = computeDeclContext(SS, false)) ||
1655 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00001656 RequireCompleteDeclContext(SS, DC))
John McCallf7a1a742009-11-24 19:00:30 +00001657 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001659 bool MemberOfUnknownSpecialization;
John McCallf7a1a742009-11-24 19:00:30 +00001660 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001661 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1662 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00001663
John McCallf7a1a742009-11-24 19:00:30 +00001664 if (R.isAmbiguous())
1665 return ExprError();
1666
1667 if (R.empty()) {
1668 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1669 << Name << SS.getRange();
1670 return ExprError();
1671 }
1672
1673 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1674 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1675 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1676 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1677 return ExprError();
1678 }
1679
1680 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001681}
1682
Douglas Gregorc45c2322009-03-31 00:43:58 +00001683/// \brief Form a dependent template name.
1684///
1685/// This action forms a dependent template name given the template
1686/// name and its (presumably dependent) scope specifier. For
1687/// example, given "MetaFun::template apply", the scope specifier \p
1688/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1689/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump1eb44332009-09-09 15:08:12 +00001690Sema::TemplateTy
Douglas Gregorc45c2322009-03-31 00:43:58 +00001691Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001692 CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +00001693 UnqualifiedId &Name,
Douglas Gregora481edb2009-11-20 23:39:24 +00001694 TypeTy *ObjectType,
1695 bool EnteringContext) {
Douglas Gregor0707bc52010-01-19 16:01:07 +00001696 DeclContext *LookupCtx = 0;
1697 if (SS.isSet())
1698 LookupCtx = computeDeclContext(SS, EnteringContext);
1699 if (!LookupCtx && ObjectType)
1700 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1701 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001702 // C++0x [temp.names]p5:
1703 // If a name prefixed by the keyword template is not the name of
1704 // a template, the program is ill-formed. [Note: the keyword
1705 // template may not be applied to non-template members of class
1706 // templates. -end note ] [ Note: as is the case with the
1707 // typename prefix, the template prefix is allowed in cases
1708 // where it is not strictly necessary; i.e., when the
1709 // nested-name-specifier or the expression on the left of the ->
1710 // or . is not dependent on a template-parameter, or the use
1711 // does not appear in the scope of a template. -end note]
1712 //
1713 // Note: C++03 was more strict here, because it banned the use of
1714 // the "template" keyword prior to a template-name that was not a
1715 // dependent name. C++ DR468 relaxed this requirement (the
1716 // "template" keyword is now permitted). We follow the C++0x
1717 // rules, even in C++03 mode, retroactively applying the DR.
1718 TemplateTy Template;
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001719 bool MemberOfUnknownSpecialization;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001720 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001721 EnteringContext, Template,
1722 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001723 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1724 isa<CXXRecordDecl>(LookupCtx) &&
1725 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001726 // This is a dependent template.
1727 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001728 Diag(Name.getSourceRange().getBegin(),
1729 diag::err_template_kw_refers_to_non_template)
1730 << GetNameFromUnqualifiedId(Name)
Douglas Gregor0278e122010-05-05 05:58:24 +00001731 << Name.getSourceRange()
1732 << TemplateKWLoc;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001733 return TemplateTy();
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001734 } else {
1735 // We found something; return it.
1736 return Template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001737 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001738 }
1739
Mike Stump1eb44332009-09-09 15:08:12 +00001740 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001741 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001742
1743 switch (Name.getKind()) {
1744 case UnqualifiedId::IK_Identifier:
1745 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1746 Name.Identifier));
1747
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001748 case UnqualifiedId::IK_OperatorFunctionId:
1749 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1750 Name.OperatorFunctionId.Operator));
Sean Hunte6252d12009-11-28 08:58:14 +00001751
1752 case UnqualifiedId::IK_LiteralOperatorId:
1753 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1754
Douglas Gregor014e88d2009-11-03 23:16:33 +00001755 default:
1756 break;
1757 }
1758
1759 Diag(Name.getSourceRange().getBegin(),
1760 diag::err_template_kw_refers_to_non_template)
1761 << GetNameFromUnqualifiedId(Name)
Douglas Gregor0278e122010-05-05 05:58:24 +00001762 << Name.getSourceRange()
1763 << TemplateKWLoc;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001764 return TemplateTy();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001765}
1766
Mike Stump1eb44332009-09-09 15:08:12 +00001767bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001768 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001769 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001770 const TemplateArgument &Arg = AL.getArgument();
1771
Anders Carlsson436b1562009-06-13 00:33:33 +00001772 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001773 switch(Arg.getKind()) {
1774 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00001775 // C++ [temp.arg.type]p1:
1776 // A template-argument for a template-parameter which is a
1777 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001778 break;
1779 case TemplateArgument::Template: {
1780 // We have a template type parameter but the template argument
1781 // is a template without any arguments.
1782 SourceRange SR = AL.getSourceRange();
1783 TemplateName Name = Arg.getAsTemplate();
1784 Diag(SR.getBegin(), diag::err_template_missing_args)
1785 << Name << SR;
1786 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1787 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00001788
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001789 return true;
1790 }
1791 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00001792 // We have a template type parameter but the template argument
1793 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001794 SourceRange SR = AL.getSourceRange();
1795 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001796 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001797
Anders Carlsson436b1562009-06-13 00:33:33 +00001798 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001799 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001800 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001801
John McCalla93c9342009-12-07 02:54:59 +00001802 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001803 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001804
Anders Carlsson436b1562009-06-13 00:33:33 +00001805 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001806 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001807 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001808 return false;
1809}
1810
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001811/// \brief Substitute template arguments into the default template argument for
1812/// the given template type parameter.
1813///
1814/// \param SemaRef the semantic analysis object for which we are performing
1815/// the substitution.
1816///
1817/// \param Template the template that we are synthesizing template arguments
1818/// for.
1819///
1820/// \param TemplateLoc the location of the template name that started the
1821/// template-id we are checking.
1822///
1823/// \param RAngleLoc the location of the right angle bracket ('>') that
1824/// terminates the template-id.
1825///
1826/// \param Param the template template parameter whose default we are
1827/// substituting into.
1828///
1829/// \param Converted the list of template arguments provided for template
1830/// parameters that precede \p Param in the template parameter list.
1831///
1832/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001833static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001834SubstDefaultTemplateArgument(Sema &SemaRef,
1835 TemplateDecl *Template,
1836 SourceLocation TemplateLoc,
1837 SourceLocation RAngleLoc,
1838 TemplateTypeParmDecl *Param,
1839 TemplateArgumentListBuilder &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001840 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001841
1842 // If the argument type is dependent, instantiate it now based
1843 // on the previously-computed template arguments.
1844 if (ArgType->getType()->isDependentType()) {
1845 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1846 /*TakeArgs=*/false);
1847
1848 MultiLevelTemplateArgumentList AllTemplateArgs
1849 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1850
1851 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1852 Template, Converted.getFlatArguments(),
1853 Converted.flatSize(),
1854 SourceRange(TemplateLoc, RAngleLoc));
1855
1856 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1857 Param->getDefaultArgumentLoc(),
1858 Param->getDeclName());
1859 }
1860
1861 return ArgType;
1862}
1863
1864/// \brief Substitute template arguments into the default template argument for
1865/// the given non-type template parameter.
1866///
1867/// \param SemaRef the semantic analysis object for which we are performing
1868/// the substitution.
1869///
1870/// \param Template the template that we are synthesizing template arguments
1871/// for.
1872///
1873/// \param TemplateLoc the location of the template name that started the
1874/// template-id we are checking.
1875///
1876/// \param RAngleLoc the location of the right angle bracket ('>') that
1877/// terminates the template-id.
1878///
Douglas Gregor788cd062009-11-11 01:00:40 +00001879/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001880/// substituting into.
1881///
1882/// \param Converted the list of template arguments provided for template
1883/// parameters that precede \p Param in the template parameter list.
1884///
1885/// \returns the substituted template argument, or NULL if an error occurred.
1886static Sema::OwningExprResult
1887SubstDefaultTemplateArgument(Sema &SemaRef,
1888 TemplateDecl *Template,
1889 SourceLocation TemplateLoc,
1890 SourceLocation RAngleLoc,
1891 NonTypeTemplateParmDecl *Param,
1892 TemplateArgumentListBuilder &Converted) {
1893 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1894 /*TakeArgs=*/false);
1895
1896 MultiLevelTemplateArgumentList AllTemplateArgs
1897 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1898
1899 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1900 Template, Converted.getFlatArguments(),
1901 Converted.flatSize(),
1902 SourceRange(TemplateLoc, RAngleLoc));
1903
1904 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1905}
1906
Douglas Gregor788cd062009-11-11 01:00:40 +00001907/// \brief Substitute template arguments into the default template argument for
1908/// the given template template parameter.
1909///
1910/// \param SemaRef the semantic analysis object for which we are performing
1911/// the substitution.
1912///
1913/// \param Template the template that we are synthesizing template arguments
1914/// for.
1915///
1916/// \param TemplateLoc the location of the template name that started the
1917/// template-id we are checking.
1918///
1919/// \param RAngleLoc the location of the right angle bracket ('>') that
1920/// terminates the template-id.
1921///
1922/// \param Param the template template parameter whose default we are
1923/// substituting into.
1924///
1925/// \param Converted the list of template arguments provided for template
1926/// parameters that precede \p Param in the template parameter list.
1927///
1928/// \returns the substituted template argument, or NULL if an error occurred.
1929static TemplateName
1930SubstDefaultTemplateArgument(Sema &SemaRef,
1931 TemplateDecl *Template,
1932 SourceLocation TemplateLoc,
1933 SourceLocation RAngleLoc,
1934 TemplateTemplateParmDecl *Param,
1935 TemplateArgumentListBuilder &Converted) {
1936 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1937 /*TakeArgs=*/false);
1938
1939 MultiLevelTemplateArgumentList AllTemplateArgs
1940 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1941
1942 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1943 Template, Converted.getFlatArguments(),
1944 Converted.flatSize(),
1945 SourceRange(TemplateLoc, RAngleLoc));
1946
1947 return SemaRef.SubstTemplateName(
1948 Param->getDefaultArgument().getArgument().getAsTemplate(),
1949 Param->getDefaultArgument().getTemplateNameLoc(),
1950 AllTemplateArgs);
1951}
1952
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001953/// \brief If the given template parameter has a default template
1954/// argument, substitute into that default template argument and
1955/// return the corresponding template argument.
1956TemplateArgumentLoc
1957Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1958 SourceLocation TemplateLoc,
1959 SourceLocation RAngleLoc,
1960 Decl *Param,
1961 TemplateArgumentListBuilder &Converted) {
1962 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1963 if (!TypeParm->hasDefaultArgument())
1964 return TemplateArgumentLoc();
1965
John McCalla93c9342009-12-07 02:54:59 +00001966 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001967 TemplateLoc,
1968 RAngleLoc,
1969 TypeParm,
1970 Converted);
1971 if (DI)
1972 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1973
1974 return TemplateArgumentLoc();
1975 }
1976
1977 if (NonTypeTemplateParmDecl *NonTypeParm
1978 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1979 if (!NonTypeParm->hasDefaultArgument())
1980 return TemplateArgumentLoc();
1981
1982 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1983 TemplateLoc,
1984 RAngleLoc,
1985 NonTypeParm,
1986 Converted);
1987 if (Arg.isInvalid())
1988 return TemplateArgumentLoc();
1989
1990 Expr *ArgE = Arg.takeAs<Expr>();
1991 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1992 }
1993
1994 TemplateTemplateParmDecl *TempTempParm
1995 = cast<TemplateTemplateParmDecl>(Param);
1996 if (!TempTempParm->hasDefaultArgument())
1997 return TemplateArgumentLoc();
1998
1999 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2000 TemplateLoc,
2001 RAngleLoc,
2002 TempTempParm,
2003 Converted);
2004 if (TName.isNull())
2005 return TemplateArgumentLoc();
2006
2007 return TemplateArgumentLoc(TemplateArgument(TName),
2008 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2009 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2010}
2011
Douglas Gregore7526412009-11-11 19:31:23 +00002012/// \brief Check that the given template argument corresponds to the given
2013/// template parameter.
2014bool Sema::CheckTemplateArgument(NamedDecl *Param,
2015 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00002016 TemplateDecl *Template,
2017 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002018 SourceLocation RAngleLoc,
Douglas Gregor02024a92010-03-28 02:42:43 +00002019 TemplateArgumentListBuilder &Converted,
2020 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002021 // Check template type parameters.
2022 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002023 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00002024
Douglas Gregord9e15302009-11-11 19:41:09 +00002025 // Check non-type template parameters.
2026 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002027 // Do substitution on the type of the non-type template parameter
2028 // with the template arguments we've seen thus far.
2029 QualType NTTPType = NTTP->getType();
2030 if (NTTPType->isDependentType()) {
2031 // Do substitution on the type of the non-type template parameter.
2032 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2033 NTTP, Converted.getFlatArguments(),
2034 Converted.flatSize(),
2035 SourceRange(TemplateLoc, RAngleLoc));
2036
2037 TemplateArgumentList TemplateArgs(Context, Converted,
2038 /*TakeArgs=*/false);
2039 NTTPType = SubstType(NTTPType,
2040 MultiLevelTemplateArgumentList(TemplateArgs),
2041 NTTP->getLocation(),
2042 NTTP->getDeclName());
2043 // If that worked, check the non-type template parameter type
2044 // for validity.
2045 if (!NTTPType.isNull())
2046 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2047 NTTP->getLocation());
2048 if (NTTPType.isNull())
2049 return true;
2050 }
2051
2052 switch (Arg.getArgument().getKind()) {
2053 case TemplateArgument::Null:
2054 assert(false && "Should never see a NULL template argument here");
2055 return true;
2056
2057 case TemplateArgument::Expression: {
2058 Expr *E = Arg.getArgument().getAsExpr();
2059 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002060 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00002061 return true;
2062
2063 Converted.Append(Result);
2064 break;
2065 }
2066
2067 case TemplateArgument::Declaration:
2068 case TemplateArgument::Integral:
2069 // We've already checked this template argument, so just copy
2070 // it to the list of converted arguments.
2071 Converted.Append(Arg.getArgument());
2072 break;
2073
2074 case TemplateArgument::Template:
2075 // We were given a template template argument. It may not be ill-formed;
2076 // see below.
2077 if (DependentTemplateName *DTN
2078 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2079 // We have a template argument such as \c T::template X, which we
2080 // parsed as a template template argument. However, since we now
2081 // know that we need a non-type template argument, convert this
2082 // template name into an expression.
John McCallf7a1a742009-11-24 19:00:30 +00002083 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2084 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002085 Arg.getTemplateQualifierRange(),
John McCallf7a1a742009-11-24 19:00:30 +00002086 DTN->getIdentifier(),
2087 Arg.getTemplateNameLoc());
Douglas Gregore7526412009-11-11 19:31:23 +00002088
2089 TemplateArgument Result;
2090 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2091 return true;
2092
2093 Converted.Append(Result);
2094 break;
2095 }
2096
2097 // We have a template argument that actually does refer to a class
2098 // template, template alias, or template template parameter, and
2099 // therefore cannot be a non-type template argument.
2100 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2101 << Arg.getSourceRange();
2102
2103 Diag(Param->getLocation(), diag::note_template_param_here);
2104 return true;
2105
2106 case TemplateArgument::Type: {
2107 // We have a non-type template parameter but the template
2108 // argument is a type.
2109
2110 // C++ [temp.arg]p2:
2111 // In a template-argument, an ambiguity between a type-id and
2112 // an expression is resolved to a type-id, regardless of the
2113 // form of the corresponding template-parameter.
2114 //
2115 // We warn specifically about this case, since it can be rather
2116 // confusing for users.
2117 QualType T = Arg.getArgument().getAsType();
2118 SourceRange SR = Arg.getSourceRange();
2119 if (T->isFunctionType())
2120 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2121 else
2122 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2123 Diag(Param->getLocation(), diag::note_template_param_here);
2124 return true;
2125 }
2126
2127 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002128 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002129 break;
2130 }
2131
2132 return false;
2133 }
2134
2135
2136 // Check template template parameters.
2137 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2138
2139 // Substitute into the template parameter list of the template
2140 // template parameter, since previously-supplied template arguments
2141 // may appear within the template template parameter.
2142 {
2143 // Set up a template instantiation context.
2144 LocalInstantiationScope Scope(*this);
2145 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2146 TempParm, Converted.getFlatArguments(),
2147 Converted.flatSize(),
2148 SourceRange(TemplateLoc, RAngleLoc));
2149
2150 TemplateArgumentList TemplateArgs(Context, Converted,
2151 /*TakeArgs=*/false);
2152 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2153 SubstDecl(TempParm, CurContext,
2154 MultiLevelTemplateArgumentList(TemplateArgs)));
2155 if (!TempParm)
2156 return true;
2157
2158 // FIXME: TempParam is leaked.
2159 }
2160
2161 switch (Arg.getArgument().getKind()) {
2162 case TemplateArgument::Null:
2163 assert(false && "Should never see a NULL template argument here");
2164 return true;
2165
2166 case TemplateArgument::Template:
2167 if (CheckTemplateArgument(TempParm, Arg))
2168 return true;
2169
2170 Converted.Append(Arg.getArgument());
2171 break;
2172
2173 case TemplateArgument::Expression:
2174 case TemplateArgument::Type:
2175 // We have a template template parameter but the template
2176 // argument does not refer to a template.
2177 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2178 return true;
2179
2180 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002181 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002182 "Declaration argument with template template parameter");
2183 break;
2184 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002185 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002186 "Integral argument with template template parameter");
2187 break;
2188
2189 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002190 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002191 break;
2192 }
2193
2194 return false;
2195}
2196
Douglas Gregorc15cb382009-02-09 23:23:08 +00002197/// \brief Check that the given template argument list is well-formed
2198/// for specializing the given template.
2199bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2200 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002201 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002202 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002203 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002204 TemplateParameterList *Params = Template->getTemplateParameters();
2205 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002206 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002207 bool Invalid = false;
2208
John McCalld5532b62009-11-23 01:53:49 +00002209 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2210
Mike Stump1eb44332009-09-09 15:08:12 +00002211 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002212 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002213
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002214 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002215 (NumArgs < Params->getMinRequiredArguments() &&
2216 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002217 // FIXME: point at either the first arg beyond what we can handle,
2218 // or the '>', depending on whether we have too many or too few
2219 // arguments.
2220 SourceRange Range;
2221 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002222 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002223 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2224 << (NumArgs > NumParams)
2225 << (isa<ClassTemplateDecl>(Template)? 0 :
2226 isa<FunctionTemplateDecl>(Template)? 1 :
2227 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2228 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002229 Diag(Template->getLocation(), diag::note_template_decl_here)
2230 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002231 Invalid = true;
2232 }
Mike Stump1eb44332009-09-09 15:08:12 +00002233
2234 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002235 // [...] The type and form of each template-argument specified in
2236 // a template-id shall match the type and form specified for the
2237 // corresponding parameter declared by the template in its
2238 // template-parameter-list.
2239 unsigned ArgIdx = 0;
2240 for (TemplateParameterList::iterator Param = Params->begin(),
2241 ParamEnd = Params->end();
2242 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002243 if (ArgIdx > NumArgs && PartialTemplateArgs)
2244 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Douglas Gregord9e15302009-11-11 19:41:09 +00002246 // If we have a template parameter pack, check every remaining template
2247 // argument against that template parameter pack.
2248 if ((*Param)->isTemplateParameterPack()) {
2249 Converted.BeginPack();
2250 for (; ArgIdx < NumArgs; ++ArgIdx) {
2251 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2252 TemplateLoc, RAngleLoc, Converted)) {
2253 Invalid = true;
2254 break;
2255 }
2256 }
2257 Converted.EndPack();
2258 continue;
2259 }
2260
Douglas Gregorf35f8282009-11-11 21:54:23 +00002261 if (ArgIdx < NumArgs) {
2262 // Check the template argument we were given.
2263 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2264 TemplateLoc, RAngleLoc, Converted))
2265 return true;
2266
2267 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002268 }
Douglas Gregore7526412009-11-11 19:31:23 +00002269
Douglas Gregorf35f8282009-11-11 21:54:23 +00002270 // We have a default template argument that we will use.
2271 TemplateArgumentLoc Arg;
2272
2273 // Retrieve the default template argument from the template
2274 // parameter. For each kind of template parameter, we substitute the
2275 // template arguments provided thus far and any "outer" template arguments
2276 // (when the template parameter was part of a nested template) into
2277 // the default argument.
2278 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2279 if (!TTP->hasDefaultArgument()) {
2280 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2281 break;
2282 }
2283
John McCalla93c9342009-12-07 02:54:59 +00002284 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002285 Template,
2286 TemplateLoc,
2287 RAngleLoc,
2288 TTP,
2289 Converted);
2290 if (!ArgType)
2291 return true;
2292
2293 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2294 ArgType);
2295 } else if (NonTypeTemplateParmDecl *NTTP
2296 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2297 if (!NTTP->hasDefaultArgument()) {
2298 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2299 break;
2300 }
2301
2302 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2303 TemplateLoc,
2304 RAngleLoc,
2305 NTTP,
2306 Converted);
2307 if (E.isInvalid())
2308 return true;
2309
2310 Expr *Ex = E.takeAs<Expr>();
2311 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2312 } else {
2313 TemplateTemplateParmDecl *TempParm
2314 = cast<TemplateTemplateParmDecl>(*Param);
2315
2316 if (!TempParm->hasDefaultArgument()) {
2317 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2318 break;
2319 }
2320
2321 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2322 TemplateLoc,
2323 RAngleLoc,
2324 TempParm,
2325 Converted);
2326 if (Name.isNull())
2327 return true;
2328
2329 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2330 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2331 TempParm->getDefaultArgument().getTemplateNameLoc());
2332 }
2333
2334 // Introduce an instantiation record that describes where we are using
2335 // the default template argument.
2336 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2337 Converted.getFlatArguments(),
2338 Converted.flatSize(),
2339 SourceRange(TemplateLoc, RAngleLoc));
2340
2341 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002342 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002343 RAngleLoc, Converted))
2344 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002345 }
2346
2347 return Invalid;
2348}
2349
2350/// \brief Check a template argument against its corresponding
2351/// template type parameter.
2352///
2353/// This routine implements the semantics of C++ [temp.arg.type]. It
2354/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002355bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002356 TypeSourceInfo *ArgInfo) {
2357 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002358 QualType Arg = ArgInfo->getType();
2359
Douglas Gregorc15cb382009-02-09 23:23:08 +00002360 // C++ [temp.arg.type]p2:
2361 // A local type, a type with no linkage, an unnamed type or a type
2362 // compounded from any of these types shall not be used as a
2363 // template-argument for a template type-parameter.
2364 //
Douglas Gregor0fddb972010-05-22 16:17:30 +00002365 // FIXME: Perform the unnamed type check.
2366 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002367 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00002368 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002369 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00002370 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002371 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00002372 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002373 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall833ca992009-10-29 08:12:44 +00002374 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2375 << QualType(Tag, 0) << SR;
2376 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00002377 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall833ca992009-10-29 08:12:44 +00002378 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002379 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2380 return true;
Douglas Gregor0fddb972010-05-22 16:17:30 +00002381 } else if (Arg->isVariablyModifiedType()) {
2382 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2383 << Arg;
2384 return true;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002385 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00002386 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002387 }
2388
2389 return false;
2390}
2391
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002392/// \brief Checks whether the given template argument is the address
2393/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002394static bool
2395CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2396 NonTypeTemplateParmDecl *Param,
2397 QualType ParamType,
2398 Expr *ArgIn,
2399 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002400 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002401 Expr *Arg = ArgIn;
2402 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002403
2404 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002405 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002406 Arg = Cast->getSubExpr();
2407
2408 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002409 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002410 // A template-argument for a non-type, non-template
2411 // template-parameter shall be one of: [...]
2412 //
2413 // -- the address of an object or function with external
2414 // linkage, including function templates and function
2415 // template-ids but excluding non-static class members,
2416 // expressed as & id-expression where the & is optional if
2417 // the name refers to a function or array, or if the
2418 // corresponding template-parameter is a reference; or
2419 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002420
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002421 // Ignore (and complain about) any excess parentheses.
2422 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2423 if (!Invalid) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002424 S.Diag(Arg->getSourceRange().getBegin(),
2425 diag::err_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002426 << Arg->getSourceRange();
2427 Invalid = true;
2428 }
2429
2430 Arg = Parens->getSubExpr();
2431 }
2432
Douglas Gregorb7a09262010-04-01 18:32:35 +00002433 bool AddressTaken = false;
2434 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002435 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002436 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002437 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb7a09262010-04-01 18:32:35 +00002438 AddressTaken = true;
2439 AddrOpLoc = UnOp->getOperatorLoc();
2440 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002441 } else
2442 DRE = dyn_cast<DeclRefExpr>(Arg);
2443
Douglas Gregorb7a09262010-04-01 18:32:35 +00002444 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002445 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2446 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002447 S.Diag(Param->getLocation(), diag::note_template_param_here);
2448 return true;
2449 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002450
2451 // Stop checking the precise nature of the argument if it is value dependent,
2452 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002453 if (Arg->isValueDependent()) {
2454 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth038cc392010-01-31 10:01:20 +00002455 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002456 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002457
Douglas Gregorb7a09262010-04-01 18:32:35 +00002458 if (!isa<ValueDecl>(DRE->getDecl())) {
2459 S.Diag(Arg->getSourceRange().getBegin(),
2460 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002461 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002462 S.Diag(Param->getLocation(), diag::note_template_param_here);
2463 return true;
2464 }
2465
2466 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002467
2468 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00002469 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2470 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002471 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002472 S.Diag(Param->getLocation(), diag::note_template_param_here);
2473 return true;
2474 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002475
2476 // Cannot refer to non-static member functions
2477 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00002478 if (!Method->isStatic()) {
2479 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002480 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002481 S.Diag(Param->getLocation(), diag::note_template_param_here);
2482 return true;
2483 }
Mike Stump1eb44332009-09-09 15:08:12 +00002484
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002485 // Functions must have external linkage.
2486 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002487 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002488 S.Diag(Arg->getSourceRange().getBegin(),
2489 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002490 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002491 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002492 << true;
2493 return true;
2494 }
2495
2496 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002497 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002498
Douglas Gregorb7a09262010-04-01 18:32:35 +00002499 // If the template parameter has pointer type, the function decays.
2500 if (ParamType->isPointerType() && !AddressTaken)
2501 ArgType = S.Context.getPointerType(Func->getType());
2502 else if (AddressTaken && ParamType->isReferenceType()) {
2503 // If we originally had an address-of operator, but the
2504 // parameter has reference type, complain and (if things look
2505 // like they will work) drop the address-of operator.
2506 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2507 ParamType.getNonReferenceType())) {
2508 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2509 << ParamType;
2510 S.Diag(Param->getLocation(), diag::note_template_param_here);
2511 return true;
2512 }
2513
2514 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2515 << ParamType
2516 << FixItHint::CreateRemoval(AddrOpLoc);
2517 S.Diag(Param->getLocation(), diag::note_template_param_here);
2518
2519 ArgType = Func->getType();
2520 }
2521 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002522 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002523 S.Diag(Arg->getSourceRange().getBegin(),
2524 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002525 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002526 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002527 << true;
2528 return true;
2529 }
2530
Douglas Gregorb7a09262010-04-01 18:32:35 +00002531 // A value of reference type is not an object.
2532 if (Var->getType()->isReferenceType()) {
2533 S.Diag(Arg->getSourceRange().getBegin(),
2534 diag::err_template_arg_reference_var)
2535 << Var->getType() << Arg->getSourceRange();
2536 S.Diag(Param->getLocation(), diag::note_template_param_here);
2537 return true;
2538 }
2539
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002540 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002541 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002542
2543 // If the template parameter has pointer type, we must have taken
2544 // the address of this object.
2545 if (ParamType->isReferenceType()) {
2546 if (AddressTaken) {
2547 // If we originally had an address-of operator, but the
2548 // parameter has reference type, complain and (if things look
2549 // like they will work) drop the address-of operator.
2550 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2551 ParamType.getNonReferenceType())) {
2552 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2553 << ParamType;
2554 S.Diag(Param->getLocation(), diag::note_template_param_here);
2555 return true;
2556 }
2557
2558 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2559 << ParamType
2560 << FixItHint::CreateRemoval(AddrOpLoc);
2561 S.Diag(Param->getLocation(), diag::note_template_param_here);
2562
2563 ArgType = Var->getType();
2564 }
2565 } else if (!AddressTaken && ParamType->isPointerType()) {
2566 if (Var->getType()->isArrayType()) {
2567 // Array-to-pointer decay.
2568 ArgType = S.Context.getArrayDecayedType(Var->getType());
2569 } else {
2570 // If the template parameter has pointer type but the address of
2571 // this object was not taken, complain and (possibly) recover by
2572 // taking the address of the entity.
2573 ArgType = S.Context.getPointerType(Var->getType());
2574 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2575 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2576 << ParamType;
2577 S.Diag(Param->getLocation(), diag::note_template_param_here);
2578 return true;
2579 }
2580
2581 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2582 << ParamType
2583 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2584
2585 S.Diag(Param->getLocation(), diag::note_template_param_here);
2586 }
2587 }
2588 } else {
2589 // We found something else, but we don't know specifically what it is.
2590 S.Diag(Arg->getSourceRange().getBegin(),
2591 diag::err_template_arg_not_object_or_func)
2592 << Arg->getSourceRange();
2593 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2594 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002595 }
Mike Stump1eb44332009-09-09 15:08:12 +00002596
Douglas Gregorb7a09262010-04-01 18:32:35 +00002597 if (ParamType->isPointerType() &&
2598 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2599 S.IsQualificationConversion(ArgType, ParamType)) {
2600 // For pointer-to-object types, qualification conversions are
2601 // permitted.
2602 } else {
2603 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2604 if (!ParamRef->getPointeeType()->isFunctionType()) {
2605 // C++ [temp.arg.nontype]p5b3:
2606 // For a non-type template-parameter of type reference to
2607 // object, no conversions apply. The type referred to by the
2608 // reference may be more cv-qualified than the (otherwise
2609 // identical) type of the template- argument. The
2610 // template-parameter is bound directly to the
2611 // template-argument, which shall be an lvalue.
2612
2613 // FIXME: Other qualifiers?
2614 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2615 unsigned ArgQuals = ArgType.getCVRQualifiers();
2616
2617 if ((ParamQuals | ArgQuals) != ParamQuals) {
2618 S.Diag(Arg->getSourceRange().getBegin(),
2619 diag::err_template_arg_ref_bind_ignores_quals)
2620 << ParamType << Arg->getType()
2621 << Arg->getSourceRange();
2622 S.Diag(Param->getLocation(), diag::note_template_param_here);
2623 return true;
2624 }
2625 }
2626 }
2627
2628 // At this point, the template argument refers to an object or
2629 // function with external linkage. We now need to check whether the
2630 // argument and parameter types are compatible.
2631 if (!S.Context.hasSameUnqualifiedType(ArgType,
2632 ParamType.getNonReferenceType())) {
2633 // We can't perform this conversion or binding.
2634 if (ParamType->isReferenceType())
2635 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2636 << ParamType << Arg->getType() << Arg->getSourceRange();
2637 else
2638 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2639 << Arg->getType() << ParamType << Arg->getSourceRange();
2640 S.Diag(Param->getLocation(), diag::note_template_param_here);
2641 return true;
2642 }
2643 }
2644
2645 // Create the template argument.
2646 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor77c13e02010-04-24 18:20:53 +00002647 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00002648 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002649}
2650
2651/// \brief Checks whether the given template argument is a pointer to
2652/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002653bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2654 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002655 bool Invalid = false;
2656
2657 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002658 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002659 Arg = Cast->getSubExpr();
2660
2661 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002662 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002663 // A template-argument for a non-type, non-template
2664 // template-parameter shall be one of: [...]
2665 //
2666 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002667 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002668
2669 // Ignore (and complain about) any excess parentheses.
2670 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2671 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002672 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002673 diag::err_template_arg_extra_parens)
2674 << Arg->getSourceRange();
2675 Invalid = true;
2676 }
2677
2678 Arg = Parens->getSubExpr();
2679 }
2680
Douglas Gregorcaddba02009-11-12 18:38:13 +00002681 // A pointer-to-member constant written &Class::member.
2682 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002683 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2684 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2685 if (DRE && !DRE->getQualifier())
2686 DRE = 0;
2687 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002688 }
2689 // A constant of pointer-to-member type.
2690 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2691 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2692 if (VD->getType()->isMemberPointerType()) {
2693 if (isa<NonTypeTemplateParmDecl>(VD) ||
2694 (isa<VarDecl>(VD) &&
2695 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2696 if (Arg->isTypeDependent() || Arg->isValueDependent())
2697 Converted = TemplateArgument(Arg->Retain());
2698 else
2699 Converted = TemplateArgument(VD->getCanonicalDecl());
2700 return Invalid;
2701 }
2702 }
2703 }
2704
2705 DRE = 0;
2706 }
2707
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002708 if (!DRE)
2709 return Diag(Arg->getSourceRange().getBegin(),
2710 diag::err_template_arg_not_pointer_to_member_form)
2711 << Arg->getSourceRange();
2712
2713 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2714 assert((isa<FieldDecl>(DRE->getDecl()) ||
2715 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2716 "Only non-static member pointers can make it here");
2717
2718 // Okay: this is the address of a non-static member, and therefore
2719 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002720 if (Arg->isTypeDependent() || Arg->isValueDependent())
2721 Converted = TemplateArgument(Arg->Retain());
2722 else
2723 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002724 return Invalid;
2725 }
2726
2727 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002728 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002729 diag::err_template_arg_not_pointer_to_member_form)
2730 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002731 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002732 diag::note_template_arg_refers_here);
2733 return true;
2734}
2735
Douglas Gregorc15cb382009-02-09 23:23:08 +00002736/// \brief Check a template argument against its corresponding
2737/// non-type template parameter.
2738///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002739/// This routine implements the semantics of C++ [temp.arg.nontype].
2740/// It returns true if an error occurred, and false otherwise. \p
2741/// InstantiatedParamType is the type of the non-type template
2742/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002743///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002744/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002745bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002746 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00002747 TemplateArgument &Converted,
2748 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002749 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2750
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002751 // If either the parameter has a dependent type or the argument is
2752 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00002753 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2754 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002755 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002756 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002757 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002758
2759 // C++ [temp.arg.nontype]p5:
2760 // The following conversions are performed on each expression used
2761 // as a non-type template-argument. If a non-type
2762 // template-argument cannot be converted to the type of the
2763 // corresponding template-parameter then the program is
2764 // ill-formed.
2765 //
2766 // -- for a non-type template-parameter of integral or
2767 // enumeration type, integral promotions (4.5) and integral
2768 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002769 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002770 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002771 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002772 // C++ [temp.arg.nontype]p1:
2773 // A template-argument for a non-type, non-template
2774 // template-parameter shall be one of:
2775 //
2776 // -- an integral constant-expression of integral or enumeration
2777 // type; or
2778 // -- the name of a non-type template-parameter; or
2779 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002780 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002781 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002782 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002783 diag::err_template_arg_not_integral_or_enumeral)
2784 << ArgType << Arg->getSourceRange();
2785 Diag(Param->getLocation(), diag::note_template_param_here);
2786 return true;
2787 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002788 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002789 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2790 << ArgType << Arg->getSourceRange();
2791 return true;
2792 }
2793
Douglas Gregor02024a92010-03-28 02:42:43 +00002794 // From here on out, all we care about are the unqualified forms
2795 // of the parameter and argument types.
2796 ParamType = ParamType.getUnqualifiedType();
2797 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002798
2799 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002800 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002801 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00002802 } else if (CTAK == CTAK_Deduced) {
2803 // C++ [temp.deduct.type]p17:
2804 // If, in the declaration of a function template with a non-type
2805 // template-parameter, the non-type template- parameter is used
2806 // in an expression in the function parameter-list and, if the
2807 // corresponding template-argument is deduced, the
2808 // template-argument type shall match the type of the
2809 // template-parameter exactly, except that a template-argument
2810 // deduced from an array bound may be of any integral type.
2811 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2812 << ArgType << ParamType;
2813 Diag(Param->getLocation(), diag::note_template_param_here);
2814 return true;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002815 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2816 !ParamType->isEnumeralType()) {
2817 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002818 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002819 } else {
2820 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002821 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002822 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002823 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002824 Diag(Param->getLocation(), diag::note_template_param_here);
2825 return true;
2826 }
2827
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002828 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002829 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002830 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002831
2832 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002833 llvm::APSInt OldValue = Value;
2834
2835 // Coerce the template argument's value to the value it will have
2836 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002837 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002838 if (Value.getBitWidth() != AllowedBits)
2839 Value.extOrTrunc(AllowedBits);
2840 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002841
2842 // Complain if an unsigned parameter received a negative value.
2843 if (IntegerType->isUnsignedIntegerType()
2844 && (OldValue.isSigned() && OldValue.isNegative())) {
2845 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2846 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2847 << Arg->getSourceRange();
2848 Diag(Param->getLocation(), diag::note_template_param_here);
2849 }
2850
2851 // Complain if we overflowed the template parameter's type.
2852 unsigned RequiredBits;
2853 if (IntegerType->isUnsignedIntegerType())
2854 RequiredBits = OldValue.getActiveBits();
2855 else if (OldValue.isUnsigned())
2856 RequiredBits = OldValue.getActiveBits() + 1;
2857 else
2858 RequiredBits = OldValue.getMinSignedBits();
2859 if (RequiredBits > AllowedBits) {
2860 Diag(Arg->getSourceRange().getBegin(),
2861 diag::warn_template_arg_too_large)
2862 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2863 << Arg->getSourceRange();
2864 Diag(Param->getLocation(), diag::note_template_param_here);
2865 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002866 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002867
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002868 // Add the value of this argument to the list of converted
2869 // arguments. We use the bitwidth and signedness of the template
2870 // parameter.
2871 if (Arg->isValueDependent()) {
2872 // The argument is value-dependent. Create a new
2873 // TemplateArgument with the converted expression.
2874 Converted = TemplateArgument(Arg);
2875 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002876 }
2877
John McCall833ca992009-10-29 08:12:44 +00002878 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002879 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002880 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002881 return false;
2882 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002883
John McCall6bb80172010-03-30 21:47:33 +00002884 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2885
Douglas Gregorb7a09262010-04-01 18:32:35 +00002886 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2887 // from a template argument of type std::nullptr_t to a non-type
2888 // template parameter of type pointer to object, pointer to
2889 // function, or pointer-to-member, respectively.
2890 if (ArgType->isNullPtrType() &&
2891 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2892 Converted = TemplateArgument((NamedDecl *)0);
2893 return false;
2894 }
2895
Douglas Gregorb86b0572009-02-11 01:18:59 +00002896 // Handle pointer-to-function, reference-to-function, and
2897 // pointer-to-member-function all in (roughly) the same way.
2898 if (// -- For a non-type template-parameter of type pointer to
2899 // function, only the function-to-pointer conversion (4.3) is
2900 // applied. If the template-argument represents a set of
2901 // overloaded functions (or a pointer to such), the matching
2902 // function is selected from the set (13.4).
2903 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002904 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002905 // -- For a non-type template-parameter of type reference to
2906 // function, no conversions apply. If the template-argument
2907 // represents a set of overloaded functions, the matching
2908 // function is selected from the set (13.4).
2909 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002910 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002911 // -- For a non-type template-parameter of type pointer to
2912 // member function, no conversions apply. If the
2913 // template-argument represents a set of overloaded member
2914 // functions, the matching member function is selected from
2915 // the set (13.4).
2916 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002917 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002918 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002919
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002920 if (Arg->getType() == Context.OverloadTy) {
2921 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2922 true,
2923 FoundResult)) {
2924 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2925 return true;
2926
2927 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2928 ArgType = Arg->getType();
2929 } else
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002930 return true;
Douglas Gregora35284b2009-02-11 00:19:33 +00002931 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002932
Douglas Gregorb7a09262010-04-01 18:32:35 +00002933 if (!ParamType->isMemberPointerType())
2934 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2935 ParamType,
2936 Arg, Converted);
2937
2938 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
2939 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2940 Arg->isLvalue(Context) == Expr::LV_Valid);
2941 } else if (!Context.hasSameUnqualifiedType(ArgType,
2942 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002943 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002944 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002945 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002946 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002947 Diag(Param->getLocation(), diag::note_template_param_here);
2948 return true;
2949 }
Mike Stump1eb44332009-09-09 15:08:12 +00002950
Douglas Gregorb7a09262010-04-01 18:32:35 +00002951 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregora35284b2009-02-11 00:19:33 +00002952 }
2953
Chris Lattnerfe90de72009-02-20 21:37:53 +00002954 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002955 // -- for a non-type template-parameter of type pointer to
2956 // object, qualification conversions (4.4) and the
2957 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002958 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002959 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002960 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002961
Douglas Gregorb7a09262010-04-01 18:32:35 +00002962 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2963 ParamType,
2964 Arg, Converted);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002965 }
Mike Stump1eb44332009-09-09 15:08:12 +00002966
Ted Kremenek6217b802009-07-29 21:53:49 +00002967 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002968 // -- For a non-type template-parameter of type reference to
2969 // object, no conversions apply. The type referred to by the
2970 // reference may be more cv-qualified than the (otherwise
2971 // identical) type of the template-argument. The
2972 // template-parameter is bound directly to the
2973 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002974 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002975 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002976
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002977 if (Arg->getType() == Context.OverloadTy) {
2978 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2979 ParamRefType->getPointeeType(),
2980 true,
2981 FoundResult)) {
2982 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2983 return true;
2984
2985 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2986 ArgType = Arg->getType();
2987 } else
Douglas Gregorb7a09262010-04-01 18:32:35 +00002988 return true;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002989 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002990
Douglas Gregorb7a09262010-04-01 18:32:35 +00002991 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2992 ParamType,
2993 Arg, Converted);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002994 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002995
2996 // -- For a non-type template-parameter of type pointer to data
2997 // member, qualification conversions (4.4) are applied.
2998 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2999
Douglas Gregor8e6563b2009-02-11 18:22:40 +00003000 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00003001 // Types match exactly: nothing more to do here.
3002 } else if (IsQualificationConversion(ArgType, ParamType)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003003 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
3004 Arg->isLvalue(Context) == Expr::LV_Valid);
Douglas Gregor658bbb52009-02-11 16:16:59 +00003005 } else {
3006 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003007 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00003008 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003009 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00003010 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00003011 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00003012 }
3013
Douglas Gregorcaddba02009-11-12 18:38:13 +00003014 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00003015}
3016
3017/// \brief Check a template argument against its corresponding
3018/// template template parameter.
3019///
3020/// This routine implements the semantics of C++ [temp.arg.template].
3021/// It returns true if an error occurred, and false otherwise.
3022bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00003023 const TemplateArgumentLoc &Arg) {
3024 TemplateName Name = Arg.getArgument().getAsTemplate();
3025 TemplateDecl *Template = Name.getAsTemplateDecl();
3026 if (!Template) {
3027 // Any dependent template name is fine.
3028 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3029 return false;
3030 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003031
3032 // C++ [temp.arg.template]p1:
3033 // A template-argument for a template template-parameter shall be
3034 // the name of a class template, expressed as id-expression. Only
3035 // primary class templates are considered when matching the
3036 // template template argument with the corresponding parameter;
3037 // partial specializations are not considered even if their
3038 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003039 //
3040 // Note that we also allow template template parameters here, which
3041 // will happen when we are dealing with, e.g., class template
3042 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00003043 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003044 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003045 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00003046 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00003047 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00003048 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003049 << Template;
3050 }
3051
3052 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3053 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00003054 true,
3055 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00003056 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00003057}
3058
Douglas Gregor02024a92010-03-28 02:42:43 +00003059/// \brief Given a non-type template argument that refers to a
3060/// declaration and the type of its corresponding non-type template
3061/// parameter, produce an expression that properly refers to that
3062/// declaration.
3063Sema::OwningExprResult
3064Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3065 QualType ParamType,
3066 SourceLocation Loc) {
3067 assert(Arg.getKind() == TemplateArgument::Declaration &&
3068 "Only declaration template arguments permitted here");
3069 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3070
3071 if (VD->getDeclContext()->isRecord() &&
3072 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3073 // If the value is a class member, we might have a pointer-to-member.
3074 // Determine whether the non-type template template parameter is of
3075 // pointer-to-member type. If so, we need to build an appropriate
3076 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3077 // would refer to the member itself.
3078 if (ParamType->isMemberPointerType()) {
3079 QualType ClassType
3080 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3081 NestedNameSpecifier *Qualifier
3082 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
3083 CXXScopeSpec SS;
3084 SS.setScopeRep(Qualifier);
3085 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
3086 VD->getType().getNonReferenceType(),
3087 Loc,
3088 &SS);
3089 if (RefExpr.isInvalid())
3090 return ExprError();
3091
3092 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregorc0c83002010-04-30 21:46:38 +00003093
3094 // We might need to perform a trailing qualification conversion, since
3095 // the element type on the parameter could be more qualified than the
3096 // element type in the expression we constructed.
3097 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3098 ParamType.getUnqualifiedType())) {
3099 Expr *RefE = RefExpr.takeAs<Expr>();
3100 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(),
3101 CastExpr::CK_NoOp);
3102 RefExpr = Owned(RefE);
3103 }
3104
Douglas Gregor02024a92010-03-28 02:42:43 +00003105 assert(!RefExpr.isInvalid() &&
3106 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00003107 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00003108 return move(RefExpr);
3109 }
3110 }
3111
3112 QualType T = VD->getType().getNonReferenceType();
3113 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003114 // When the non-type template parameter is a pointer, take the
3115 // address of the declaration.
Douglas Gregor02024a92010-03-28 02:42:43 +00003116 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3117 if (RefExpr.isInvalid())
3118 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003119
3120 if (T->isFunctionType() || T->isArrayType()) {
3121 // Decay functions and arrays.
3122 Expr *RefE = (Expr *)RefExpr.get();
3123 DefaultFunctionArrayConversion(RefE);
3124 if (RefE != RefExpr.get()) {
3125 RefExpr.release();
3126 RefExpr = Owned(RefE);
3127 }
3128
3129 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00003130 }
3131
Douglas Gregorb7a09262010-04-01 18:32:35 +00003132 // Take the address of everything else
3133 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregor02024a92010-03-28 02:42:43 +00003134 }
3135
3136 // If the non-type template parameter has reference type, qualify the
3137 // resulting declaration reference with the extra qualifiers on the
3138 // type that the reference refers to.
3139 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3140 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3141
3142 return BuildDeclRefExpr(VD, T, Loc);
3143}
3144
3145/// \brief Construct a new expression that refers to the given
3146/// integral template argument with the given source-location
3147/// information.
3148///
3149/// This routine takes care of the mapping from an integral template
3150/// argument (which may have any integral type) to the appropriate
3151/// literal value.
3152Sema::OwningExprResult
3153Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3154 SourceLocation Loc) {
3155 assert(Arg.getKind() == TemplateArgument::Integral &&
3156 "Operation is only value for integral template arguments");
3157 QualType T = Arg.getIntegralType();
3158 if (T->isCharType() || T->isWideCharType())
3159 return Owned(new (Context) CharacterLiteral(
3160 Arg.getAsIntegral()->getZExtValue(),
3161 T->isWideCharType(),
3162 T,
3163 Loc));
3164 if (T->isBooleanType())
3165 return Owned(new (Context) CXXBoolLiteralExpr(
3166 Arg.getAsIntegral()->getBoolValue(),
3167 T,
3168 Loc));
3169
3170 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3171}
3172
3173
Douglas Gregorddc29e12009-02-06 22:42:48 +00003174/// \brief Determine whether the given template parameter lists are
3175/// equivalent.
3176///
Mike Stump1eb44332009-09-09 15:08:12 +00003177/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00003178/// source code as part of a new template declaration.
3179///
3180/// \param Old The old template parameter list, typically found via
3181/// name lookup of the template declared with this template parameter
3182/// list.
3183///
3184/// \param Complain If true, this routine will produce a diagnostic if
3185/// the template parameter lists are not equivalent.
3186///
Douglas Gregorfb898e12009-11-12 16:20:59 +00003187/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00003188///
3189/// \param TemplateArgLoc If this source location is valid, then we
3190/// are actually checking the template parameter list of a template
3191/// argument (New) against the template parameter list of its
3192/// corresponding template template parameter (Old). We produce
3193/// slightly different diagnostics in this scenario.
3194///
Douglas Gregorddc29e12009-02-06 22:42:48 +00003195/// \returns True if the template parameter lists are equal, false
3196/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003197bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00003198Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3199 TemplateParameterList *Old,
3200 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003201 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003202 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003203 if (Old->size() != New->size()) {
3204 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003205 unsigned NextDiag = diag::err_template_param_list_different_arity;
3206 if (TemplateArgLoc.isValid()) {
3207 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3208 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00003209 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003210 Diag(New->getTemplateLoc(), NextDiag)
3211 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00003212 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003213 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00003214 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003215 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003216 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3217 }
3218
3219 return false;
3220 }
3221
3222 for (TemplateParameterList::iterator OldParm = Old->begin(),
3223 OldParmEnd = Old->end(), NewParm = New->begin();
3224 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3225 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003226 if (Complain) {
3227 unsigned NextDiag = diag::err_template_param_different_kind;
3228 if (TemplateArgLoc.isValid()) {
3229 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3230 NextDiag = diag::note_template_param_different_kind;
3231 }
3232 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003233 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003234 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003235 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00003236 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003237 return false;
3238 }
3239
3240 if (isa<TemplateTypeParmDecl>(*OldParm)) {
3241 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00003242 // know we're at the same index).
Mike Stump1eb44332009-09-09 15:08:12 +00003243 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003244 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3245 // The types of non-type template parameters must agree.
3246 NonTypeTemplateParmDecl *NewNTTP
3247 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00003248
3249 // If we are matching a template template argument to a template
3250 // template parameter and one of the non-type template parameter types
3251 // is dependent, then we must wait until template instantiation time
3252 // to actually compare the arguments.
3253 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3254 (OldNTTP->getType()->isDependentType() ||
3255 NewNTTP->getType()->isDependentType()))
3256 continue;
3257
Douglas Gregorddc29e12009-02-06 22:42:48 +00003258 if (Context.getCanonicalType(OldNTTP->getType()) !=
3259 Context.getCanonicalType(NewNTTP->getType())) {
3260 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003261 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3262 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003263 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003264 diag::err_template_arg_template_params_mismatch);
3265 NextDiag = diag::note_template_nontype_parm_different_type;
3266 }
3267 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003268 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00003269 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00003270 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00003271 diag::note_template_nontype_parm_prev_declaration)
3272 << OldNTTP->getType();
3273 }
3274 return false;
3275 }
3276 } else {
3277 // The template parameter lists of template template
3278 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00003279 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00003280 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00003281 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003282 = cast<TemplateTemplateParmDecl>(*OldParm);
3283 TemplateTemplateParmDecl *NewTTP
3284 = cast<TemplateTemplateParmDecl>(*NewParm);
3285 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3286 OldTTP->getTemplateParameters(),
3287 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003288 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00003289 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003290 return false;
3291 }
3292 }
3293
3294 return true;
3295}
3296
3297/// \brief Check whether a template can be declared within this scope.
3298///
3299/// If the template declaration is valid in this scope, returns
3300/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003301bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003302Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003303 // Find the nearest enclosing declaration scope.
3304 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3305 (S->getFlags() & Scope::TemplateParamScope) != 0)
3306 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003307
Douglas Gregorddc29e12009-02-06 22:42:48 +00003308 // C++ [temp]p2:
3309 // A template-declaration can appear only as a namespace scope or
3310 // class scope declaration.
3311 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003312 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3313 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003314 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003315 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003316
Eli Friedman1503f772009-07-31 01:43:05 +00003317 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003318 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003319
3320 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3321 return false;
3322
Mike Stump1eb44332009-09-09 15:08:12 +00003323 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003324 diag::err_template_outside_namespace_or_class_scope)
3325 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003326}
Douglas Gregorcc636682009-02-17 23:15:12 +00003327
Douglas Gregord5cb8762009-10-07 00:13:32 +00003328/// \brief Determine what kind of template specialization the given declaration
3329/// is.
3330static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3331 if (!D)
3332 return TSK_Undeclared;
3333
Douglas Gregorf6b11852009-10-08 15:14:33 +00003334 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3335 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003336 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3337 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003338 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3339 return Var->getTemplateSpecializationKind();
3340
Douglas Gregord5cb8762009-10-07 00:13:32 +00003341 return TSK_Undeclared;
3342}
3343
Douglas Gregor9302da62009-10-14 23:50:59 +00003344/// \brief Check whether a specialization is well-formed in the current
3345/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003346///
Douglas Gregor9302da62009-10-14 23:50:59 +00003347/// This routine determines whether a template specialization can be declared
3348/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003349///
3350/// \param S the semantic analysis object for which this check is being
3351/// performed.
3352///
3353/// \param Specialized the entity being specialized or instantiated, which
3354/// may be a kind of template (class template, function template, etc.) or
3355/// a member of a class template (member function, static data member,
3356/// member class).
3357///
3358/// \param PrevDecl the previous declaration of this entity, if any.
3359///
3360/// \param Loc the location of the explicit specialization or instantiation of
3361/// this entity.
3362///
3363/// \param IsPartialSpecialization whether this is a partial specialization of
3364/// a class template.
3365///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003366/// \returns true if there was an error that we cannot recover from, false
3367/// otherwise.
3368static bool CheckTemplateSpecializationScope(Sema &S,
3369 NamedDecl *Specialized,
3370 NamedDecl *PrevDecl,
3371 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003372 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003373 // Keep these "kind" numbers in sync with the %select statements in the
3374 // various diagnostics emitted by this routine.
3375 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003376 bool isTemplateSpecialization = false;
3377 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003378 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003379 isTemplateSpecialization = true;
3380 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003381 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003382 isTemplateSpecialization = true;
3383 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003384 EntityKind = 3;
3385 else if (isa<VarDecl>(Specialized))
3386 EntityKind = 4;
3387 else if (isa<RecordDecl>(Specialized))
3388 EntityKind = 5;
3389 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003390 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3391 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003392 return true;
3393 }
3394
Douglas Gregor88b70942009-02-25 22:02:03 +00003395 // C++ [temp.expl.spec]p2:
3396 // An explicit specialization shall be declared in the namespace
3397 // of which the template is a member, or, for member templates, in
3398 // the namespace of which the enclosing class or enclosing class
3399 // template is a member. An explicit specialization of a member
3400 // function, member class or static data member of a class
3401 // template shall be declared in the namespace of which the class
3402 // template is a member. Such a declaration may also be a
3403 // definition. If the declaration is not a definition, the
3404 // specialization may be defined later in the name- space in which
3405 // the explicit specialization was declared, or in a namespace
3406 // that encloses the one in which the explicit specialization was
3407 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003408 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3409 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003410 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003411 return true;
3412 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003413
Douglas Gregor0a407472009-10-07 17:30:37 +00003414 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3415 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003416 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003417 return true;
3418 }
3419
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003420 // C++ [temp.class.spec]p6:
3421 // A class template partial specialization may be declared or redeclared
3422 // in any namespace scope in which its definition may be defined (14.5.1
3423 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003424 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003425 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003426 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003427 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003428 if ((!PrevDecl ||
3429 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3430 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3431 // There is no prior declaration of this entity, so this
3432 // specialization must be in the same context as the template
3433 // itself.
3434 if (!DC->Equals(SpecializedContext)) {
3435 if (isa<TranslationUnitDecl>(SpecializedContext))
3436 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3437 << EntityKind << Specialized;
3438 else if (isa<NamespaceDecl>(SpecializedContext))
3439 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3440 << EntityKind << Specialized
3441 << cast<NamedDecl>(SpecializedContext);
3442
3443 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3444 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003445 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003446 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003447
3448 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003449 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003450 // Note that HandleDeclarator() performs this check for explicit
3451 // specializations of function templates, static data members, and member
3452 // functions, so we skip the check here for those kinds of entities.
3453 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003454 // Should we refactor that check, so that it occurs later?
3455 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003456 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3457 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003458 if (isa<TranslationUnitDecl>(SpecializedContext))
3459 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3460 << EntityKind << Specialized;
3461 else if (isa<NamespaceDecl>(SpecializedContext))
3462 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3463 << EntityKind << Specialized
3464 << cast<NamedDecl>(SpecializedContext);
3465
Douglas Gregor9302da62009-10-14 23:50:59 +00003466 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003467 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003468
3469 // FIXME: check for specialization-after-instantiation errors and such.
3470
Douglas Gregor88b70942009-02-25 22:02:03 +00003471 return false;
3472}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003473
Douglas Gregore94866f2009-06-12 21:21:02 +00003474/// \brief Check the non-type template arguments of a class template
3475/// partial specialization according to C++ [temp.class.spec]p9.
3476///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003477/// \param TemplateParams the template parameters of the primary class
3478/// template.
3479///
3480/// \param TemplateArg the template arguments of the class template
3481/// partial specialization.
3482///
3483/// \param MirrorsPrimaryTemplate will be set true if the class
3484/// template partial specialization arguments are identical to the
3485/// implicit template arguments of the primary template. This is not
3486/// necessarily an error (C++0x), and it is left to the caller to diagnose
3487/// this condition when it is an error.
3488///
Douglas Gregore94866f2009-06-12 21:21:02 +00003489/// \returns true if there was an error, false otherwise.
3490bool Sema::CheckClassTemplatePartialSpecializationArgs(
3491 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00003492 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003493 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003494 // FIXME: the interface to this function will have to change to
3495 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003496 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003497
Anders Carlssonfb250522009-06-23 01:26:57 +00003498 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00003499
Douglas Gregore94866f2009-06-12 21:21:02 +00003500 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003501 // Determine whether the template argument list of the partial
3502 // specialization is identical to the implicit argument list of
3503 // the primary template. The caller may need to diagnostic this as
3504 // an error per C++ [temp.class.spec]p9b3.
3505 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003506 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003507 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3508 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003509 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003510 MirrorsPrimaryTemplate = false;
3511 } else if (TemplateTemplateParmDecl *TTP
3512 = dyn_cast<TemplateTemplateParmDecl>(
3513 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003514 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003515 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003516 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003517 if (!ArgDecl ||
3518 ArgDecl->getIndex() != TTP->getIndex() ||
3519 ArgDecl->getDepth() != TTP->getDepth())
3520 MirrorsPrimaryTemplate = false;
3521 }
3522 }
3523
Mike Stump1eb44332009-09-09 15:08:12 +00003524 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003525 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003526 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003527 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003528 }
3529
Anders Carlsson6360be72009-06-13 18:20:51 +00003530 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003531 if (!ArgExpr) {
3532 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003533 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003534 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003535
3536 // C++ [temp.class.spec]p8:
3537 // A non-type argument is non-specialized if it is the name of a
3538 // non-type parameter. All other non-type arguments are
3539 // specialized.
3540 //
3541 // Below, we check the two conditions that only apply to
3542 // specialized non-type arguments, so skip any non-specialized
3543 // arguments.
3544 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003545 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003546 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003547 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003548 (Param->getIndex() != NTTP->getIndex() ||
3549 Param->getDepth() != NTTP->getDepth()))
3550 MirrorsPrimaryTemplate = false;
3551
Douglas Gregore94866f2009-06-12 21:21:02 +00003552 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003553 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003554
3555 // C++ [temp.class.spec]p9:
3556 // Within the argument list of a class template partial
3557 // specialization, the following restrictions apply:
3558 // -- A partially specialized non-type argument expression
3559 // shall not involve a template parameter of the partial
3560 // specialization except when the argument expression is a
3561 // simple identifier.
3562 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003563 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003564 diag::err_dependent_non_type_arg_in_partial_spec)
3565 << ArgExpr->getSourceRange();
3566 return true;
3567 }
3568
3569 // -- The type of a template parameter corresponding to a
3570 // specialized non-type argument shall not be dependent on a
3571 // parameter of the specialization.
3572 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003573 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003574 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3575 << Param->getType()
3576 << ArgExpr->getSourceRange();
3577 Diag(Param->getLocation(), diag::note_template_param_here);
3578 return true;
3579 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003580
3581 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003582 }
3583
3584 return false;
3585}
3586
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003587/// \brief Retrieve the previous declaration of the given declaration.
3588static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3589 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3590 return VD->getPreviousDeclaration();
3591 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3592 return FD->getPreviousDeclaration();
3593 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3594 return TD->getPreviousDeclaration();
3595 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3596 return TD->getPreviousDeclaration();
3597 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3598 return FTD->getPreviousDeclaration();
3599 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3600 return CTD->getPreviousDeclaration();
3601 return 0;
3602}
3603
Douglas Gregor212e81c2009-03-25 00:13:59 +00003604Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003605Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3606 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00003607 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003608 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003609 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00003610 SourceLocation TemplateNameLoc,
3611 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00003612 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00003613 SourceLocation RAngleLoc,
3614 AttributeList *Attr,
3615 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003616 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00003617
Douglas Gregorcc636682009-02-17 23:15:12 +00003618 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00003619 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003620 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00003621 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3622
3623 if (!ClassTemplate) {
3624 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3625 << (Name.getAsTemplateDecl() &&
3626 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3627 return true;
3628 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003629
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003630 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003631 bool isPartialSpecialization = false;
3632
Douglas Gregor88b70942009-02-25 22:02:03 +00003633 // Check the validity of the template headers that introduce this
3634 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003635 // FIXME: We probably shouldn't complain about these headers for
3636 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00003637 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00003638 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3639 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003640 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00003641 TUK == TUK_Friend,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003642 isExplicitSpecialization);
Douglas Gregor05396e22009-08-25 17:23:04 +00003643 if (TemplateParams && TemplateParams->size() > 0) {
3644 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003645
Douglas Gregor05396e22009-08-25 17:23:04 +00003646 // C++ [temp.class.spec]p10:
3647 // The template parameter list of a specialization shall not
3648 // contain default template argument values.
3649 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3650 Decl *Param = TemplateParams->getParam(I);
3651 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3652 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003653 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003654 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00003655 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003656 }
3657 } else if (NonTypeTemplateParmDecl *NTTP
3658 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3659 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003660 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003661 diag::err_default_arg_in_partial_spec)
3662 << DefArg->getSourceRange();
3663 NTTP->setDefaultArgument(0);
3664 DefArg->Destroy(Context);
3665 }
3666 } else {
3667 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003668 if (TTP->hasDefaultArgument()) {
3669 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003670 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003671 << TTP->getDefaultArgument().getSourceRange();
3672 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003673 }
3674 }
3675 }
Douglas Gregora735b202009-10-13 14:39:41 +00003676 } else if (TemplateParams) {
3677 if (TUK == TUK_Friend)
3678 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00003679 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00003680 SourceRange(TemplateParams->getTemplateLoc(),
3681 TemplateParams->getRAngleLoc()))
3682 << SourceRange(LAngleLoc, RAngleLoc);
3683 else
3684 isExplicitSpecialization = true;
3685 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003686 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00003687 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003688 isExplicitSpecialization = true;
3689 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003690
Douglas Gregorcc636682009-02-17 23:15:12 +00003691 // Check that the specialization uses the same tag kind as the
3692 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003693 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3694 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003695 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003696 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003697 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003698 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003699 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00003700 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003701 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003702 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003703 diag::note_previous_use);
3704 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3705 }
3706
Douglas Gregor40808ce2009-03-09 23:48:35 +00003707 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00003708 TemplateArgumentListInfo TemplateArgs;
3709 TemplateArgs.setLAngleLoc(LAngleLoc);
3710 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00003711 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003712
Douglas Gregorcc636682009-02-17 23:15:12 +00003713 // Check that the template argument list is well-formed for this
3714 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003715 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3716 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00003717 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3718 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003719 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003720
Mike Stump1eb44332009-09-09 15:08:12 +00003721 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003722 ClassTemplate->getTemplateParameters()->size()) &&
3723 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003724
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003725 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003726 // corresponds to these arguments.
3727 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003728 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003729 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003730 if (CheckClassTemplatePartialSpecializationArgs(
3731 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003732 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003733 return true;
3734
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003735 if (MirrorsPrimaryTemplate) {
3736 // C++ [temp.class.spec]p9b3:
3737 //
Mike Stump1eb44332009-09-09 15:08:12 +00003738 // -- The argument list of the specialization shall not be identical
3739 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003740 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003741 << (TUK == TUK_Definition)
Douglas Gregor849b2432010-03-31 17:46:05 +00003742 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003743 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003744 ClassTemplate->getIdentifier(),
3745 TemplateNameLoc,
3746 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003747 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003748 AS_none);
3749 }
3750
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003751 // FIXME: Diagnose friend partial specializations
3752
Douglas Gregorde090962010-02-09 00:37:32 +00003753 if (!Name.isDependent() &&
3754 !TemplateSpecializationType::anyDependentTemplateArguments(
3755 TemplateArgs.getArgumentArray(),
3756 TemplateArgs.size())) {
3757 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3758 << ClassTemplate->getDeclName();
3759 isPartialSpecialization = false;
3760 } else {
3761 // FIXME: Template parameter list matters, too
3762 ClassTemplatePartialSpecializationDecl::Profile(ID,
3763 Converted.getFlatArguments(),
3764 Converted.flatSize(),
3765 Context);
3766 }
3767 }
3768
3769 if (!isPartialSpecialization)
Anders Carlsson1c5976e2009-06-05 03:43:12 +00003770 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003771 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003772 Converted.flatSize(),
3773 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00003774 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003775 ClassTemplateSpecializationDecl *PrevDecl = 0;
3776
3777 if (isPartialSpecialization)
3778 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00003779 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003780 InsertPos);
3781 else
3782 PrevDecl
3783 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003784
3785 ClassTemplateSpecializationDecl *Specialization = 0;
3786
Douglas Gregor88b70942009-02-25 22:02:03 +00003787 // Check whether we can declare a class template specialization in
3788 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003789 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003790 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003791 TemplateNameLoc,
3792 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003793 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003794
Douglas Gregorb88e8882009-07-30 17:40:51 +00003795 // The canonical type
3796 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003797 if (PrevDecl &&
3798 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00003799 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003800 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003801 // arguments was referenced but not declared, or we're only
3802 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003803 // declaration node as our own, updating its source location to
3804 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003805 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003806 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003807 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003808 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003809 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003810 // Build the canonical type that describes the converted template
3811 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00003812 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3813 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb88e8882009-07-30 17:40:51 +00003814 Converted.getFlatArguments(),
3815 Converted.flatSize());
3816
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003817 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003818 ClassTemplatePartialSpecializationDecl *PrevPartial
3819 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00003820 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
3821 : ClassTemplate->getPartialSpecializations().size();
Mike Stump1eb44332009-09-09 15:08:12 +00003822 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00003823 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003824 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003825 TemplateNameLoc,
3826 TemplateParams,
3827 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003828 Converted,
John McCalld5532b62009-11-23 01:53:49 +00003829 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00003830 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00003831 PrevPartial,
3832 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00003833 SetNestedNameSpecifier(Partial, SS);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003834
3835 if (PrevPartial) {
3836 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3837 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3838 } else {
3839 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3840 }
3841 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003842
Douglas Gregored9c0f92009-10-29 00:04:11 +00003843 // If we are providing an explicit specialization of a member class
3844 // template specialization, make a note of that.
3845 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3846 PrevPartial->setMemberSpecialization();
3847
Douglas Gregor031a5882009-06-13 00:26:55 +00003848 // Check that all of the template parameters of the class template
3849 // partial specialization are deducible from the template
3850 // arguments. If not, this class template partial specialization
3851 // will never be used.
3852 llvm::SmallVector<bool, 8> DeducibleParams;
3853 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003854 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003855 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003856 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003857 unsigned NumNonDeducible = 0;
3858 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3859 if (!DeducibleParams[I])
3860 ++NumNonDeducible;
3861
3862 if (NumNonDeducible) {
3863 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3864 << (NumNonDeducible > 1)
3865 << SourceRange(TemplateNameLoc, RAngleLoc);
3866 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3867 if (!DeducibleParams[I]) {
3868 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3869 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003870 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003871 diag::note_partial_spec_unused_parameter)
3872 << Param->getDeclName();
3873 else
Mike Stump1eb44332009-09-09 15:08:12 +00003874 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003875 diag::note_partial_spec_unused_parameter)
3876 << std::string("<anonymous>");
3877 }
3878 }
3879 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003880 } else {
3881 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003882 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003883 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00003884 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00003885 ClassTemplate->getDeclContext(),
3886 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003887 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003888 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003889 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00003890 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregorcc636682009-02-17 23:15:12 +00003891
3892 if (PrevDecl) {
3893 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3894 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3895 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003896 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00003897 InsertPos);
3898 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00003899
3900 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003901 }
3902
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003903 // C++ [temp.expl.spec]p6:
3904 // If a template, a member template or the member of a class template is
3905 // explicitly specialized then that specialization shall be declared
3906 // before the first use of that specialization that would cause an implicit
3907 // instantiation to take place, in every translation unit in which such a
3908 // use occurs; no diagnostic is required.
3909 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003910 bool Okay = false;
3911 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3912 // Is there any previous explicit specialization declaration?
3913 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3914 Okay = true;
3915 break;
3916 }
3917 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003918
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003919 if (!Okay) {
3920 SourceRange Range(TemplateNameLoc, RAngleLoc);
3921 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3922 << Context.getTypeDeclType(Specialization) << Range;
3923
3924 Diag(PrevDecl->getPointOfInstantiation(),
3925 diag::note_instantiation_required_here)
3926 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003927 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003928 return true;
3929 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003930 }
3931
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003932 // If this is not a friend, note that this is an explicit specialization.
3933 if (TUK != TUK_Friend)
3934 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003935
3936 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003937 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00003938 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003939 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003940 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003941 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003942 Diag(Def->getLocation(), diag::note_previous_definition);
3943 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003944 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003945 }
3946 }
3947
Douglas Gregorfc705b82009-02-26 22:19:44 +00003948 // Build the fully-sugared type for this class template
3949 // specialization as the user wrote in the specialization
3950 // itself. This means that we'll pretty-print the type retrieved
3951 // from the specialization's declaration the way that the user
3952 // actually wrote the specialization, rather than formatting the
3953 // name based on the "canonical" representation used to store the
3954 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00003955 TypeSourceInfo *WrittenTy
3956 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3957 TemplateArgs, CanonType);
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003958 if (TUK != TUK_Friend)
3959 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003960 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00003961
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003962 // C++ [temp.expl.spec]p9:
3963 // A template explicit specialization is in the scope of the
3964 // namespace in which the template was defined.
3965 //
3966 // We actually implement this paragraph where we set the semantic
3967 // context (in the creation of the ClassTemplateSpecializationDecl),
3968 // but we also maintain the lexical context where the actual
3969 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00003970 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003971
Douglas Gregorcc636682009-02-17 23:15:12 +00003972 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003973 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00003974 Specialization->startDefinition();
3975
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003976 if (TUK == TUK_Friend) {
3977 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3978 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00003979 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003980 /*FIXME:*/KWLoc);
3981 Friend->setAccess(AS_public);
3982 CurContext->addDecl(Friend);
3983 } else {
3984 // Add the specialization into its lexical context, so that it can
3985 // be seen when iterating through the list of declarations in that
3986 // context. However, specializations are not found by name lookup.
3987 CurContext->addDecl(Specialization);
3988 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003989 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003990}
Douglas Gregord57959a2009-03-27 23:10:48 +00003991
Mike Stump1eb44332009-09-09 15:08:12 +00003992Sema::DeclPtrTy
3993Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00003994 MultiTemplateParamsArg TemplateParameterLists,
3995 Declarator &D) {
3996 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3997}
3998
Mike Stump1eb44332009-09-09 15:08:12 +00003999Sema::DeclPtrTy
4000Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00004001 MultiTemplateParamsArg TemplateParameterLists,
4002 Declarator &D) {
4003 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4004 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4005 "Not a function declarator!");
4006 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00004007
Douglas Gregor52591bf2009-06-24 00:54:41 +00004008 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00004009 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00004010 }
Mike Stump1eb44332009-09-09 15:08:12 +00004011
Douglas Gregor52591bf2009-06-24 00:54:41 +00004012 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004013
4014 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00004015 move(TemplateParameterLists),
4016 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004017 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00004018 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00004019 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00004020 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00004021 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
4022 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00004023 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00004024}
4025
John McCall75042392010-02-11 01:33:53 +00004026/// \brief Strips various properties off an implicit instantiation
4027/// that has just been explicitly specialized.
4028static void StripImplicitInstantiation(NamedDecl *D) {
4029 D->invalidateAttrs();
4030
4031 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4032 FD->setInlineSpecified(false);
4033 }
4034}
4035
Douglas Gregor454885e2009-10-15 15:54:05 +00004036/// \brief Diagnose cases where we have an explicit template specialization
4037/// before/after an explicit template instantiation, producing diagnostics
4038/// for those cases where they are required and determining whether the
4039/// new specialization/instantiation will have any effect.
4040///
Douglas Gregor454885e2009-10-15 15:54:05 +00004041/// \param NewLoc the location of the new explicit specialization or
4042/// instantiation.
4043///
4044/// \param NewTSK the kind of the new explicit specialization or instantiation.
4045///
4046/// \param PrevDecl the previous declaration of the entity.
4047///
4048/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4049///
4050/// \param PrevPointOfInstantiation if valid, indicates where the previus
4051/// declaration was instantiated (either implicitly or explicitly).
4052///
4053/// \param SuppressNew will be set to true to indicate that the new
4054/// specialization or instantiation has no effect and should be ignored.
4055///
4056/// \returns true if there was an error that should prevent the introduction of
4057/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00004058bool
4059Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4060 TemplateSpecializationKind NewTSK,
4061 NamedDecl *PrevDecl,
4062 TemplateSpecializationKind PrevTSK,
4063 SourceLocation PrevPointOfInstantiation,
4064 bool &SuppressNew) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004065 SuppressNew = false;
4066
4067 switch (NewTSK) {
4068 case TSK_Undeclared:
4069 case TSK_ImplicitInstantiation:
4070 assert(false && "Don't check implicit instantiations here");
4071 return false;
4072
4073 case TSK_ExplicitSpecialization:
4074 switch (PrevTSK) {
4075 case TSK_Undeclared:
4076 case TSK_ExplicitSpecialization:
4077 // Okay, we're just specializing something that is either already
4078 // explicitly specialized or has merely been mentioned without any
4079 // instantiation.
4080 return false;
4081
4082 case TSK_ImplicitInstantiation:
4083 if (PrevPointOfInstantiation.isInvalid()) {
4084 // The declaration itself has not actually been instantiated, so it is
4085 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00004086 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00004087 return false;
4088 }
4089 // Fall through
4090
4091 case TSK_ExplicitInstantiationDeclaration:
4092 case TSK_ExplicitInstantiationDefinition:
4093 assert((PrevTSK == TSK_ImplicitInstantiation ||
4094 PrevPointOfInstantiation.isValid()) &&
4095 "Explicit instantiation without point of instantiation?");
4096
4097 // C++ [temp.expl.spec]p6:
4098 // If a template, a member template or the member of a class template
4099 // is explicitly specialized then that specialization shall be declared
4100 // before the first use of that specialization that would cause an
4101 // implicit instantiation to take place, in every translation unit in
4102 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004103 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4104 // Is there any previous explicit specialization declaration?
4105 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4106 return false;
4107 }
4108
Douglas Gregor0d035142009-10-27 18:42:08 +00004109 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00004110 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004111 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00004112 << (PrevTSK != TSK_ImplicitInstantiation);
4113
4114 return true;
4115 }
4116 break;
4117
4118 case TSK_ExplicitInstantiationDeclaration:
4119 switch (PrevTSK) {
4120 case TSK_ExplicitInstantiationDeclaration:
4121 // This explicit instantiation declaration is redundant (that's okay).
4122 SuppressNew = true;
4123 return false;
4124
4125 case TSK_Undeclared:
4126 case TSK_ImplicitInstantiation:
4127 // We're explicitly instantiating something that may have already been
4128 // implicitly instantiated; that's fine.
4129 return false;
4130
4131 case TSK_ExplicitSpecialization:
4132 // C++0x [temp.explicit]p4:
4133 // For a given set of template parameters, if an explicit instantiation
4134 // of a template appears after a declaration of an explicit
4135 // specialization for that template, the explicit instantiation has no
4136 // effect.
John McCalle97c32f2010-03-02 23:09:38 +00004137 SuppressNew = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004138 return false;
4139
4140 case TSK_ExplicitInstantiationDefinition:
4141 // C++0x [temp.explicit]p10:
4142 // If an entity is the subject of both an explicit instantiation
4143 // declaration and an explicit instantiation definition in the same
4144 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00004145 Diag(NewLoc,
4146 diag::err_explicit_instantiation_declaration_after_definition);
4147 Diag(PrevPointOfInstantiation,
4148 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00004149 assert(PrevPointOfInstantiation.isValid() &&
4150 "Explicit instantiation without point of instantiation?");
4151 SuppressNew = true;
4152 return false;
4153 }
4154 break;
4155
4156 case TSK_ExplicitInstantiationDefinition:
4157 switch (PrevTSK) {
4158 case TSK_Undeclared:
4159 case TSK_ImplicitInstantiation:
4160 // We're explicitly instantiating something that may have already been
4161 // implicitly instantiated; that's fine.
4162 return false;
4163
4164 case TSK_ExplicitSpecialization:
4165 // C++ DR 259, C++0x [temp.explicit]p4:
4166 // For a given set of template parameters, if an explicit
4167 // instantiation of a template appears after a declaration of
4168 // an explicit specialization for that template, the explicit
4169 // instantiation has no effect.
4170 //
4171 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00004172 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00004173 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00004174 if (!getLangOptions().CPlusPlus0x) {
4175 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00004176 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004177 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00004178 diag::note_previous_template_specialization);
4179 }
4180 SuppressNew = true;
4181 return false;
4182
4183 case TSK_ExplicitInstantiationDeclaration:
4184 // We're explicity instantiating a definition for something for which we
4185 // were previously asked to suppress instantiations. That's fine.
4186 return false;
4187
4188 case TSK_ExplicitInstantiationDefinition:
4189 // C++0x [temp.spec]p5:
4190 // For a given template and a given set of template-arguments,
4191 // - an explicit instantiation definition shall appear at most once
4192 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00004193 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00004194 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004195 Diag(PrevPointOfInstantiation,
4196 diag::note_previous_explicit_instantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00004197 SuppressNew = true;
4198 return false;
4199 }
4200 break;
4201 }
4202
4203 assert(false && "Missing specialization/instantiation case?");
4204
4205 return false;
4206}
4207
John McCallaf2094e2010-04-08 09:05:18 +00004208/// \brief Perform semantic analysis for the given dependent function
4209/// template specialization. The only possible way to get a dependent
4210/// function template specialization is with a friend declaration,
4211/// like so:
4212///
4213/// template <class T> void foo(T);
4214/// template <class T> class A {
4215/// friend void foo<>(T);
4216/// };
4217///
4218/// There really isn't any useful analysis we can do here, so we
4219/// just store the information.
4220bool
4221Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4222 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4223 LookupResult &Previous) {
4224 // Remove anything from Previous that isn't a function template in
4225 // the correct context.
4226 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4227 LookupResult::Filter F = Previous.makeFilter();
4228 while (F.hasNext()) {
4229 NamedDecl *D = F.next()->getUnderlyingDecl();
4230 if (!isa<FunctionTemplateDecl>(D) ||
4231 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4232 F.erase();
4233 }
4234 F.done();
4235
4236 // Should this be diagnosed here?
4237 if (Previous.empty()) return true;
4238
4239 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4240 ExplicitTemplateArgs);
4241 return false;
4242}
4243
Abramo Bagnarae03db982010-05-20 15:32:11 +00004244/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004245/// specialization.
4246///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004247/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004248/// explicit function template specialization. On successful completion,
4249/// the function declaration \p FD will become a function template
4250/// specialization.
4251///
4252/// \param FD the function declaration, which will be updated to become a
4253/// function template specialization.
4254///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004255/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4256/// if any. Note that this may be valid info even when 0 arguments are
4257/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4258/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004259///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004260/// \param PrevDecl the set of declarations that may be specialized by
4261/// this function specialization.
4262bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004263Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004264 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004265 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004266 // The set of function template specializations that could match this
4267 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004268 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004269
4270 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall68263142009-11-18 22:49:29 +00004271 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4272 I != E; ++I) {
4273 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4274 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004275 // Only consider templates found within the same semantic lookup scope as
4276 // FD.
4277 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4278 continue;
4279
4280 // C++ [temp.expl.spec]p11:
4281 // A trailing template-argument can be left unspecified in the
4282 // template-id naming an explicit function template specialization
4283 // provided it can be deduced from the function argument type.
4284 // Perform template argument deduction to determine whether we may be
4285 // specializing this template.
4286 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004287 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004288 FunctionDecl *Specialization = 0;
4289 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004290 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004291 FD->getType(),
4292 Specialization,
4293 Info)) {
4294 // FIXME: Template argument deduction failed; record why it failed, so
4295 // that we can provide nifty diagnostics.
4296 (void)TDK;
4297 continue;
4298 }
4299
4300 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004301 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004302 }
4303 }
4304
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004305 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004306 UnresolvedSetIterator Result
4307 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4308 TPOC_Other, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004309 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004310 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004311 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004312 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004313 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004314 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004315 return true;
John McCallc373d482010-01-27 01:50:18 +00004316
4317 // Ignore access information; it doesn't figure into redeclaration checking.
4318 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorc42b6522010-04-09 21:02:29 +00004319 Specialization->setLocation(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004320
4321 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004322 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004323
4324 // If this is a friend declaration, then we're not really declaring
4325 // an explicit specialization.
4326 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004327
Douglas Gregord5cb8762009-10-07 00:13:32 +00004328 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004329 if (!isFriend &&
4330 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004331 Specialization->getPrimaryTemplate(),
4332 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004333 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004334 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004335
4336 // C++ [temp.expl.spec]p6:
4337 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004338 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004339 // before the first use of that specialization that would cause an implicit
4340 // instantiation to take place, in every translation unit in which such a
4341 // use occurs; no diagnostic is required.
4342 FunctionTemplateSpecializationInfo *SpecInfo
4343 = Specialization->getTemplateSpecializationInfo();
4344 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004345
4346 bool SuppressNew = false;
John McCall7ad650f2010-03-24 07:46:06 +00004347 if (!isFriend &&
4348 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004349 TSK_ExplicitSpecialization,
4350 Specialization,
4351 SpecInfo->getTemplateSpecializationKind(),
4352 SpecInfo->getPointOfInstantiation(),
4353 SuppressNew))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004354 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004355
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004356 // Mark the prior declaration as an explicit specialization, so that later
4357 // clients know that this is an explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004358 if (!isFriend)
4359 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004360
4361 // Turn the given function declaration into a function template
4362 // specialization, with the template arguments from the previous
4363 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00004364 // Take copies of (semantic and syntactic) template argument lists.
4365 const TemplateArgumentList* TemplArgs = new (Context)
4366 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4367 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4368 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregor838db382010-02-11 01:19:42 +00004369 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00004370 TemplArgs, /*InsertPos=*/0,
4371 SpecInfo->getTemplateSpecializationKind(),
4372 TemplArgsAsWritten);
4373
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004374 // The "previous declaration" for this function template specialization is
4375 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004376 Previous.clear();
4377 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004378 return false;
4379}
4380
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004381/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004382/// specialization.
4383///
4384/// This routine performs all of the semantic analysis required for an
4385/// explicit member function specialization. On successful completion,
4386/// the function declaration \p FD will become a member function
4387/// specialization.
4388///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004389/// \param Member the member declaration, which will be updated to become a
4390/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004391///
John McCall68263142009-11-18 22:49:29 +00004392/// \param Previous the set of declarations, one of which may be specialized
4393/// by this function specialization; the set will be modified to contain the
4394/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004395bool
John McCall68263142009-11-18 22:49:29 +00004396Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004397 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00004398
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004399 // Try to find the member we are instantiating.
4400 NamedDecl *Instantiation = 0;
4401 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004402 MemberSpecializationInfo *MSInfo = 0;
4403
John McCall68263142009-11-18 22:49:29 +00004404 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004405 // Nowhere to look anyway.
4406 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004407 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4408 I != E; ++I) {
4409 NamedDecl *D = (*I)->getUnderlyingDecl();
4410 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004411 if (Context.hasSameType(Function->getType(), Method->getType())) {
4412 Instantiation = Method;
4413 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004414 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004415 break;
4416 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004417 }
4418 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004419 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004420 VarDecl *PrevVar;
4421 if (Previous.isSingleResult() &&
4422 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004423 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004424 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004425 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004426 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004427 }
4428 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004429 CXXRecordDecl *PrevRecord;
4430 if (Previous.isSingleResult() &&
4431 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4432 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004433 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004434 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004435 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004436 }
4437
4438 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004439 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004440 // specializations are always out-of-line, the caller will complain about
4441 // this mismatch later.
4442 return false;
4443 }
John McCall77e8b112010-04-13 20:37:33 +00004444
4445 // If this is a friend, just bail out here before we start turning
4446 // things into explicit specializations.
4447 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4448 // Preserve instantiation information.
4449 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4450 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4451 cast<CXXMethodDecl>(InstantiatedFrom),
4452 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4453 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4454 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4455 cast<CXXRecordDecl>(InstantiatedFrom),
4456 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4457 }
4458
4459 Previous.clear();
4460 Previous.addDecl(Instantiation);
4461 return false;
4462 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004463
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004464 // Make sure that this is a specialization of a member.
4465 if (!InstantiatedFrom) {
4466 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4467 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004468 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4469 return true;
4470 }
4471
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004472 // C++ [temp.expl.spec]p6:
4473 // If a template, a member template or the member of a class template is
4474 // explicitly specialized then that spe- cialization shall be declared
4475 // before the first use of that specialization that would cause an implicit
4476 // instantiation to take place, in every translation unit in which such a
4477 // use occurs; no diagnostic is required.
4478 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004479
4480 bool SuppressNew = false;
4481 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4482 TSK_ExplicitSpecialization,
4483 Instantiation,
4484 MSInfo->getTemplateSpecializationKind(),
4485 MSInfo->getPointOfInstantiation(),
4486 SuppressNew))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004487 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004488
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004489 // Check the scope of this explicit specialization.
4490 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004491 InstantiatedFrom,
4492 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004493 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004494 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004495
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004496 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004497 // the original declaration to note that it is an explicit specialization
4498 // (if it was previously an implicit instantiation). This latter step
4499 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004500 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004501 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4502 if (InstantiationFunction->getTemplateSpecializationKind() ==
4503 TSK_ImplicitInstantiation) {
4504 InstantiationFunction->setTemplateSpecializationKind(
4505 TSK_ExplicitSpecialization);
4506 InstantiationFunction->setLocation(Member->getLocation());
4507 }
4508
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004509 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4510 cast<CXXMethodDecl>(InstantiatedFrom),
4511 TSK_ExplicitSpecialization);
4512 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004513 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4514 if (InstantiationVar->getTemplateSpecializationKind() ==
4515 TSK_ImplicitInstantiation) {
4516 InstantiationVar->setTemplateSpecializationKind(
4517 TSK_ExplicitSpecialization);
4518 InstantiationVar->setLocation(Member->getLocation());
4519 }
4520
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004521 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4522 cast<VarDecl>(InstantiatedFrom),
4523 TSK_ExplicitSpecialization);
4524 } else {
4525 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004526 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4527 if (InstantiationClass->getTemplateSpecializationKind() ==
4528 TSK_ImplicitInstantiation) {
4529 InstantiationClass->setTemplateSpecializationKind(
4530 TSK_ExplicitSpecialization);
4531 InstantiationClass->setLocation(Member->getLocation());
4532 }
4533
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004534 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004535 cast<CXXRecordDecl>(InstantiatedFrom),
4536 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004537 }
4538
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004539 // Save the caller the trouble of having to figure out which declaration
4540 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004541 Previous.clear();
4542 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004543 return false;
4544}
4545
Douglas Gregor558c0322009-10-14 23:41:34 +00004546/// \brief Check the scope of an explicit instantiation.
4547static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4548 SourceLocation InstLoc,
4549 bool WasQualifiedName) {
4550 DeclContext *ExpectedContext
4551 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4552 DeclContext *CurContext = S.CurContext->getLookupContext();
4553
4554 // C++0x [temp.explicit]p2:
4555 // An explicit instantiation shall appear in an enclosing namespace of its
4556 // template.
4557 //
4558 // This is DR275, which we do not retroactively apply to C++98/03.
4559 if (S.getLangOptions().CPlusPlus0x &&
4560 !CurContext->Encloses(ExpectedContext)) {
4561 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregor2166beb2010-05-11 17:39:34 +00004562 S.Diag(InstLoc,
4563 S.getLangOptions().CPlusPlus0x?
4564 diag::err_explicit_instantiation_out_of_scope
4565 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004566 << D << NS;
4567 else
Douglas Gregor2166beb2010-05-11 17:39:34 +00004568 S.Diag(InstLoc,
4569 S.getLangOptions().CPlusPlus0x?
4570 diag::err_explicit_instantiation_must_be_global
4571 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004572 << D;
4573 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4574 return;
4575 }
4576
4577 // C++0x [temp.explicit]p2:
4578 // If the name declared in the explicit instantiation is an unqualified
4579 // name, the explicit instantiation shall appear in the namespace where
4580 // its template is declared or, if that namespace is inline (7.3.1), any
4581 // namespace from its enclosing namespace set.
4582 if (WasQualifiedName)
4583 return;
4584
4585 if (CurContext->Equals(ExpectedContext))
4586 return;
4587
Douglas Gregor2166beb2010-05-11 17:39:34 +00004588 S.Diag(InstLoc,
4589 S.getLangOptions().CPlusPlus0x?
4590 diag::err_explicit_instantiation_unqualified_wrong_namespace
4591 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004592 << D << ExpectedContext;
4593 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4594}
4595
4596/// \brief Determine whether the given scope specifier has a template-id in it.
4597static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4598 if (!SS.isSet())
4599 return false;
4600
4601 // C++0x [temp.explicit]p2:
4602 // If the explicit instantiation is for a member function, a member class
4603 // or a static data member of a class template specialization, the name of
4604 // the class template specialization in the qualified-id for the member
4605 // name shall be a simple-template-id.
4606 //
4607 // C++98 has the same restriction, just worded differently.
4608 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4609 NNS; NNS = NNS->getPrefix())
4610 if (Type *T = NNS->getAsType())
4611 if (isa<TemplateSpecializationType>(T))
4612 return true;
4613
4614 return false;
4615}
4616
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004617// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004618Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004619Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004620 SourceLocation ExternLoc,
4621 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004622 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004623 SourceLocation KWLoc,
4624 const CXXScopeSpec &SS,
4625 TemplateTy TemplateD,
4626 SourceLocation TemplateNameLoc,
4627 SourceLocation LAngleLoc,
4628 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004629 SourceLocation RAngleLoc,
4630 AttributeList *Attr) {
4631 // Find the class template we're specializing
4632 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004633 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004634 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4635
4636 // Check that the specialization uses the same tag kind as the
4637 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004638 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4639 assert(Kind != TTK_Enum &&
4640 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004641 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004642 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004643 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004644 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004645 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004646 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004647 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004648 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004649 diag::note_previous_use);
4650 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4651 }
4652
Douglas Gregor558c0322009-10-14 23:41:34 +00004653 // C++0x [temp.explicit]p2:
4654 // There are two forms of explicit instantiation: an explicit instantiation
4655 // definition and an explicit instantiation declaration. An explicit
4656 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00004657 TemplateSpecializationKind TSK
4658 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4659 : TSK_ExplicitInstantiationDeclaration;
4660
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004661 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004662 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004663 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004664
4665 // Check that the template argument list is well-formed for this
4666 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00004667 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4668 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00004669 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4670 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004671 return true;
4672
Mike Stump1eb44332009-09-09 15:08:12 +00004673 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004674 ClassTemplate->getTemplateParameters()->size()) &&
4675 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004676
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004677 // Find the class template specialization declaration that
4678 // corresponds to these arguments.
4679 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00004680 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00004681 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00004682 Converted.flatSize(),
4683 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004684 void *InsertPos = 0;
4685 ClassTemplateSpecializationDecl *PrevDecl
4686 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4687
Douglas Gregord5cb8762009-10-07 00:13:32 +00004688 // C++0x [temp.explicit]p2:
4689 // [...] An explicit instantiation shall appear in an enclosing
4690 // namespace of its template. [...]
4691 //
4692 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004693 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4694 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00004695
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004696 ClassTemplateSpecializationDecl *Specialization = 0;
4697
Douglas Gregord78f5982009-11-25 06:01:46 +00004698 bool ReusedDecl = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004699 if (PrevDecl) {
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004700 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004701 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004702 PrevDecl,
4703 PrevDecl->getSpecializationKind(),
4704 PrevDecl->getPointOfInstantiation(),
4705 SuppressNew))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004706 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004707
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004708 if (SuppressNew)
Douglas Gregor52604ab2009-09-11 21:19:12 +00004709 return DeclPtrTy::make(PrevDecl);
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004710
Douglas Gregor52604ab2009-09-11 21:19:12 +00004711 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4712 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4713 // Since the only prior class template specialization with these
4714 // arguments was referenced but not declared, reuse that
4715 // declaration node as our own, updating its source location to
4716 // reflect our new declaration.
4717 Specialization = PrevDecl;
4718 Specialization->setLocation(TemplateNameLoc);
4719 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00004720 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00004721 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004722 }
Douglas Gregor52604ab2009-09-11 21:19:12 +00004723
4724 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004725 // Create a new class template specialization declaration node for
4726 // this explicit specialization.
4727 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00004728 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004729 ClassTemplate->getDeclContext(),
4730 TemplateNameLoc,
4731 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00004732 Converted, PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004733 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004734
Douglas Gregor52604ab2009-09-11 21:19:12 +00004735 if (PrevDecl) {
4736 // Remove the previous declaration from the folding set, since we want
4737 // to introduce a new declaration.
4738 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4739 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4740 }
4741
4742 // Insert the new specialization.
4743 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004744 }
4745
4746 // Build the fully-sugared type for this explicit instantiation as
4747 // the user wrote in the explicit instantiation itself. This means
4748 // that we'll pretty-print the type retrieved from the
4749 // specialization's declaration the way that the user actually wrote
4750 // the explicit instantiation, rather than formatting the name based
4751 // on the "canonical" representation used to store the template
4752 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004753 TypeSourceInfo *WrittenTy
4754 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4755 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004756 Context.getTypeDeclType(Specialization));
4757 Specialization->setTypeAsWritten(WrittenTy);
4758 TemplateArgsIn.release();
4759
Douglas Gregord78f5982009-11-25 06:01:46 +00004760 if (!ReusedDecl) {
4761 // Add the explicit instantiation into its lexical context. However,
4762 // since explicit instantiations are never found by name lookup, we
4763 // just put it into the declaration context directly.
4764 Specialization->setLexicalDeclContext(CurContext);
4765 CurContext->addDecl(Specialization);
4766 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004767
4768 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004769 // A definition of a class template or class member template
4770 // shall be in scope at the point of the explicit instantiation of
4771 // the class template or class member template.
4772 //
4773 // This check comes when we actually try to perform the
4774 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004775 ClassTemplateSpecializationDecl *Def
4776 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004777 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004778 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004779 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004780 else if (TSK == TSK_ExplicitInstantiationDefinition)
4781 MarkVTableUsed(TemplateNameLoc, Specialization, true);
4782
Douglas Gregor0d035142009-10-27 18:42:08 +00004783 // Instantiate the members of this class template specialization.
4784 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004785 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004786 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00004787 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4788
4789 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4790 // TSK_ExplicitInstantiationDefinition
4791 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4792 TSK == TSK_ExplicitInstantiationDefinition)
4793 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004794
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004795 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004796 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004797
4798 return DeclPtrTy::make(Specialization);
4799}
4800
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004801// Explicit instantiation of a member class of a class template.
4802Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004803Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004804 SourceLocation ExternLoc,
4805 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004806 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004807 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004808 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004809 IdentifierInfo *Name,
4810 SourceLocation NameLoc,
4811 AttributeList *Attr) {
4812
Douglas Gregor402abb52009-05-28 23:31:59 +00004813 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004814 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00004815 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004816 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00004817 MultiTemplateParamsArg(*this, 0, 0),
4818 Owned, IsDependent);
4819 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4820
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004821 if (!TagD)
4822 return true;
4823
4824 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4825 if (Tag->isEnum()) {
4826 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4827 << Context.getTypeDeclType(Tag);
4828 return true;
4829 }
4830
Douglas Gregord0c87372009-05-27 17:30:49 +00004831 if (Tag->isInvalidDecl())
4832 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004833
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004834 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4835 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4836 if (!Pattern) {
4837 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4838 << Context.getTypeDeclType(Record);
4839 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4840 return true;
4841 }
4842
Douglas Gregor558c0322009-10-14 23:41:34 +00004843 // C++0x [temp.explicit]p2:
4844 // If the explicit instantiation is for a class or member class, the
4845 // elaborated-type-specifier in the declaration shall include a
4846 // simple-template-id.
4847 //
4848 // C++98 has the same restriction, just worded differently.
4849 if (!ScopeSpecifierHasTemplateId(SS))
4850 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4851 << Record << SS.getRange();
4852
4853 // C++0x [temp.explicit]p2:
4854 // There are two forms of explicit instantiation: an explicit instantiation
4855 // definition and an explicit instantiation declaration. An explicit
4856 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004857 TemplateSpecializationKind TSK
4858 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4859 : TSK_ExplicitInstantiationDeclaration;
4860
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004861 // C++0x [temp.explicit]p2:
4862 // [...] An explicit instantiation shall appear in an enclosing
4863 // namespace of its template. [...]
4864 //
4865 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004866 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004867
4868 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004869 CXXRecordDecl *PrevDecl
4870 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00004871 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00004872 PrevDecl = Record;
4873 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004874 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4875 bool SuppressNew = false;
4876 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004877 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004878 PrevDecl,
4879 MSInfo->getTemplateSpecializationKind(),
4880 MSInfo->getPointOfInstantiation(),
4881 SuppressNew))
4882 return true;
4883 if (SuppressNew)
4884 return TagD;
4885 }
4886
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004887 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00004888 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004889 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004890 // C++ [temp.explicit]p3:
4891 // A definition of a member class of a class template shall be in scope
4892 // at the point of an explicit instantiation of the member class.
4893 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00004894 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004895 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004896 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4897 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004898 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4899 << Pattern;
4900 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004901 } else {
4902 if (InstantiateClass(NameLoc, Record, Def,
4903 getTemplateInstantiationArgs(Record),
4904 TSK))
4905 return true;
4906
Douglas Gregor952b0172010-02-11 01:04:33 +00004907 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00004908 if (!RecordDef)
4909 return true;
4910 }
4911 }
4912
4913 // Instantiate all of the members of the class.
4914 InstantiateClassMembers(NameLoc, RecordDef,
4915 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004916
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004917 if (TSK == TSK_ExplicitInstantiationDefinition)
4918 MarkVTableUsed(NameLoc, RecordDef, true);
4919
Mike Stump390b4cc2009-05-16 07:39:55 +00004920 // FIXME: We don't have any representation for explicit instantiations of
4921 // member classes. Such a representation is not needed for compilation, but it
4922 // should be available for clients that want to see all of the declarations in
4923 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004924 return TagD;
4925}
4926
Douglas Gregord5a423b2009-09-25 18:43:00 +00004927Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4928 SourceLocation ExternLoc,
4929 SourceLocation TemplateLoc,
4930 Declarator &D) {
4931 // Explicit instantiations always require a name.
4932 DeclarationName Name = GetNameForDeclarator(D);
4933 if (!Name) {
4934 if (!D.isInvalidType())
4935 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4936 diag::err_explicit_instantiation_requires_name)
4937 << D.getDeclSpec().getSourceRange()
4938 << D.getSourceRange();
4939
4940 return true;
4941 }
4942
4943 // The scope passed in may not be a decl scope. Zip up the scope tree until
4944 // we find one that is.
4945 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4946 (S->getFlags() & Scope::TemplateParamScope) != 0)
4947 S = S->getParent();
4948
4949 // Determine the type of the declaration.
4950 QualType R = GetTypeForDeclarator(D, S, 0);
4951 if (R.isNull())
4952 return true;
4953
4954 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4955 // Cannot explicitly instantiate a typedef.
4956 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4957 << Name;
4958 return true;
4959 }
4960
Douglas Gregor663b5a02009-10-14 20:14:33 +00004961 // C++0x [temp.explicit]p1:
4962 // [...] An explicit instantiation of a function template shall not use the
4963 // inline or constexpr specifiers.
4964 // Presumably, this also applies to member functions of class templates as
4965 // well.
4966 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4967 Diag(D.getDeclSpec().getInlineSpecLoc(),
4968 diag::err_explicit_instantiation_inline)
Douglas Gregor849b2432010-03-31 17:46:05 +00004969 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00004970
4971 // FIXME: check for constexpr specifier.
4972
Douglas Gregor558c0322009-10-14 23:41:34 +00004973 // C++0x [temp.explicit]p2:
4974 // There are two forms of explicit instantiation: an explicit instantiation
4975 // definition and an explicit instantiation declaration. An explicit
4976 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00004977 TemplateSpecializationKind TSK
4978 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4979 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00004980
John McCalla24dc2e2009-11-17 02:14:36 +00004981 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4982 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004983
4984 if (!R->isFunctionType()) {
4985 // C++ [temp.explicit]p1:
4986 // A [...] static data member of a class template can be explicitly
4987 // instantiated from the member definition associated with its class
4988 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00004989 if (Previous.isAmbiguous())
4990 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004991
John McCall1bcee0a2009-12-02 08:25:40 +00004992 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004993 if (!Prev || !Prev->isStaticDataMember()) {
4994 // We expect to see a data data member here.
4995 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4996 << Name;
4997 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4998 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00004999 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005000 return true;
5001 }
5002
5003 if (!Prev->getInstantiatedFromStaticDataMember()) {
5004 // FIXME: Check for explicit specialization?
5005 Diag(D.getIdentifierLoc(),
5006 diag::err_explicit_instantiation_data_member_not_instantiated)
5007 << Prev;
5008 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5009 // FIXME: Can we provide a note showing where this was declared?
5010 return true;
5011 }
5012
Douglas Gregor558c0322009-10-14 23:41:34 +00005013 // C++0x [temp.explicit]p2:
5014 // If the explicit instantiation is for a member function, a member class
5015 // or a static data member of a class template specialization, the name of
5016 // the class template specialization in the qualified-id for the member
5017 // name shall be a simple-template-id.
5018 //
5019 // C++98 has the same restriction, just worded differently.
5020 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5021 Diag(D.getIdentifierLoc(),
5022 diag::err_explicit_instantiation_without_qualified_id)
5023 << Prev << D.getCXXScopeSpec().getRange();
5024
5025 // Check the scope of this explicit instantiation.
5026 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5027
Douglas Gregor454885e2009-10-15 15:54:05 +00005028 // Verify that it is okay to explicitly instantiate here.
5029 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5030 assert(MSInfo && "Missing static data member specialization info?");
5031 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005032 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00005033 MSInfo->getTemplateSpecializationKind(),
5034 MSInfo->getPointOfInstantiation(),
5035 SuppressNew))
5036 return true;
5037 if (SuppressNew)
5038 return DeclPtrTy();
5039
Douglas Gregord5a423b2009-09-25 18:43:00 +00005040 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005041 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005042 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00005043 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
5044 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005045
5046 // FIXME: Create an ExplicitInstantiation node?
5047 return DeclPtrTy();
5048 }
5049
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005050 // If the declarator is a template-id, translate the parser's template
5051 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00005052 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00005053 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005054 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5055 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00005056 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5057 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00005058 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5059 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00005060 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00005061 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00005062 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00005063 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00005064 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005065
Douglas Gregord5a423b2009-09-25 18:43:00 +00005066 // C++ [temp.explicit]p1:
5067 // A [...] function [...] can be explicitly instantiated from its template.
5068 // A member function [...] of a class template can be explicitly
5069 // instantiated from the member definition associated with its class
5070 // template.
John McCallc373d482010-01-27 01:50:18 +00005071 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005072 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5073 P != PEnd; ++P) {
5074 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00005075 if (!HasExplicitTemplateArgs) {
5076 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5077 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5078 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00005079
John McCallc373d482010-01-27 01:50:18 +00005080 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00005081 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5082 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00005083 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00005084 }
5085 }
5086
5087 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5088 if (!FunTmpl)
5089 continue;
5090
John McCall5769d612010-02-08 23:07:23 +00005091 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005092 FunctionDecl *Specialization = 0;
5093 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00005094 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00005095 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00005096 R, Specialization, Info)) {
5097 // FIXME: Keep track of almost-matches?
5098 (void)TDK;
5099 continue;
5100 }
5101
John McCallc373d482010-01-27 01:50:18 +00005102 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005103 }
5104
5105 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005106 UnresolvedSetIterator Result
5107 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregord5a423b2009-09-25 18:43:00 +00005108 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005109 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5110 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5111 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00005112
John McCallc373d482010-01-27 01:50:18 +00005113 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00005114 return true;
John McCallc373d482010-01-27 01:50:18 +00005115
5116 // Ignore access control bits, we don't need them for redeclaration checking.
5117 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005118
Douglas Gregor0a897e32009-10-15 17:21:20 +00005119 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005120 Diag(D.getIdentifierLoc(),
5121 diag::err_explicit_instantiation_member_function_not_instantiated)
5122 << Specialization
5123 << (Specialization->getTemplateSpecializationKind() ==
5124 TSK_ExplicitSpecialization);
5125 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5126 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005127 }
Douglas Gregor558c0322009-10-14 23:41:34 +00005128
Douglas Gregor0a897e32009-10-15 17:21:20 +00005129 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00005130 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5131 PrevDecl = Specialization;
5132
Douglas Gregor0a897e32009-10-15 17:21:20 +00005133 if (PrevDecl) {
5134 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005135 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00005136 PrevDecl,
5137 PrevDecl->getTemplateSpecializationKind(),
5138 PrevDecl->getPointOfInstantiation(),
5139 SuppressNew))
5140 return true;
5141
5142 // FIXME: We may still want to build some representation of this
5143 // explicit specialization.
5144 if (SuppressNew)
5145 return DeclPtrTy();
5146 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00005147
5148 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00005149
5150 if (TSK == TSK_ExplicitInstantiationDefinition)
5151 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5152 false, /*DefinitionRequired=*/true);
Douglas Gregor0a897e32009-10-15 17:21:20 +00005153
Douglas Gregor558c0322009-10-14 23:41:34 +00005154 // C++0x [temp.explicit]p2:
5155 // If the explicit instantiation is for a member function, a member class
5156 // or a static data member of a class template specialization, the name of
5157 // the class template specialization in the qualified-id for the member
5158 // name shall be a simple-template-id.
5159 //
5160 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005161 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005162 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00005163 D.getCXXScopeSpec().isSet() &&
5164 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5165 Diag(D.getIdentifierLoc(),
5166 diag::err_explicit_instantiation_without_qualified_id)
5167 << Specialization << D.getCXXScopeSpec().getRange();
5168
5169 CheckExplicitInstantiationScope(*this,
5170 FunTmpl? (NamedDecl *)FunTmpl
5171 : Specialization->getInstantiatedFromMemberFunction(),
5172 D.getIdentifierLoc(),
5173 D.getCXXScopeSpec().isSet());
5174
Douglas Gregord5a423b2009-09-25 18:43:00 +00005175 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5176 return DeclPtrTy();
5177}
5178
Douglas Gregord57959a2009-03-27 23:10:48 +00005179Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00005180Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5181 const CXXScopeSpec &SS, IdentifierInfo *Name,
5182 SourceLocation TagLoc, SourceLocation NameLoc) {
5183 // This has to hold, because SS is expected to be defined.
5184 assert(Name && "Expected a name in a dependent tag");
5185
5186 NestedNameSpecifier *NNS
5187 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5188 if (!NNS)
5189 return true;
5190
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005191 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005192
Douglas Gregor48c89f42010-04-24 16:38:41 +00005193 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5194 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005195 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00005196 return true;
5197 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005198
5199 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5200 return Context.getDependentNameType(Kwd, NNS, Name).getAsOpaquePtr();
John McCallc4e70192009-09-11 04:59:25 +00005201}
5202
5203Sema::TypeResult
Douglas Gregord57959a2009-03-27 23:10:48 +00005204Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5205 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005206 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00005207 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5208 if (!NNS)
5209 return true;
5210
Douglas Gregor107de902010-04-24 15:35:55 +00005211 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005212 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00005213 if (T.isNull())
5214 return true;
John McCall63b43852010-04-29 23:50:39 +00005215
5216 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5217 if (isa<DependentNameType>(T)) {
5218 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005219 TL.setKeywordLoc(TypenameLoc);
5220 TL.setQualifierRange(SS.getRange());
5221 TL.setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005222 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005223 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005224 TL.setKeywordLoc(TypenameLoc);
5225 TL.setQualifierRange(SS.getRange());
5226 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005227 }
5228
5229 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregord57959a2009-03-27 23:10:48 +00005230}
5231
Douglas Gregor17343172009-04-01 00:28:59 +00005232Sema::TypeResult
5233Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5234 SourceLocation TemplateLoc, TypeTy *Ty) {
John McCall4e449832010-05-28 23:32:21 +00005235 TypeSourceInfo *InnerTSI = 0;
5236 QualType T = GetTypeFromParser(Ty, &InnerTSI);
Mike Stump1eb44332009-09-09 15:08:12 +00005237 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00005238 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
John McCall4e449832010-05-28 23:32:21 +00005239
5240 assert(isa<TemplateSpecializationType>(T) &&
5241 "Expected a template specialization type");
Douglas Gregor17343172009-04-01 00:28:59 +00005242
Douglas Gregor6946baf2009-09-02 13:05:45 +00005243 if (computeDeclContext(SS, false)) {
5244 // If we can compute a declaration context, then the "typename"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005245 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor6946baf2009-09-02 13:05:45 +00005246 // track of the nested-name-specifier.
John McCall4e449832010-05-28 23:32:21 +00005247
5248 // Push the inner type, preserving its source locations if possible.
5249 TypeLocBuilder Builder;
5250 if (InnerTSI)
5251 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5252 else
5253 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5254
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005255 T = Context.getElaboratedType(ETK_Typename, NNS, T);
John McCall4e449832010-05-28 23:32:21 +00005256 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5257 TL.setKeywordLoc(TypenameLoc);
5258 TL.setQualifierRange(SS.getRange());
5259
5260 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCall63b43852010-04-29 23:50:39 +00005261 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor6946baf2009-09-02 13:05:45 +00005262 }
Mike Stump1eb44332009-09-09 15:08:12 +00005263
John McCall4e449832010-05-28 23:32:21 +00005264 T = Context.getDependentNameType(ETK_Typename, NNS,
5265 cast<TemplateSpecializationType>(T));
John McCall63b43852010-04-29 23:50:39 +00005266 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5267 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005268 TL.setKeywordLoc(TypenameLoc);
5269 TL.setQualifierRange(SS.getRange());
5270
5271 // FIXME: the inner type is a template here; remember its full source info
5272 TL.setNameLoc(InnerTSI ? InnerTSI->getTypeLoc().getBeginLoc() : TemplateLoc);
John McCall63b43852010-04-29 23:50:39 +00005273 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00005274}
5275
Douglas Gregord57959a2009-03-27 23:10:48 +00005276/// \brief Build the type that describes a C++ typename specifier,
5277/// e.g., "typename T::type".
5278QualType
Douglas Gregor107de902010-04-24 15:35:55 +00005279Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5280 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005281 SourceLocation KeywordLoc, SourceRange NNSRange,
5282 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00005283 CXXScopeSpec SS;
5284 SS.setScopeRep(NNS);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005285 SS.setRange(NNSRange);
Douglas Gregord57959a2009-03-27 23:10:48 +00005286
John McCall77bb1aa2010-05-01 00:40:08 +00005287 DeclContext *Ctx = computeDeclContext(SS);
5288 if (!Ctx) {
5289 // If the nested-name-specifier is dependent and couldn't be
5290 // resolved to a type, build a typename type.
5291 assert(NNS->isDependent());
5292 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00005293 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005294
John McCall77bb1aa2010-05-01 00:40:08 +00005295 // If the nested-name-specifier refers to the current instantiation,
5296 // the "typename" keyword itself is superfluous. In C++03, the
5297 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5298 // allows such extraneous "typename" keywords, and we retroactively
5299 // apply this DR to C++03 code. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00005300
John McCall77bb1aa2010-05-01 00:40:08 +00005301 if (RequireCompleteDeclContext(SS, Ctx))
5302 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00005303
5304 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005305 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005306 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005307 unsigned DiagID = 0;
5308 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005309 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005310 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005311 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005312 break;
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005313
5314 case LookupResult::NotFoundInCurrentInstantiation:
5315 // Okay, it's a member of an unknown instantiation.
Douglas Gregor107de902010-04-24 15:35:55 +00005316 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00005317
5318 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +00005319 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005320 // We found a type. Build an ElaboratedType, since the
5321 // typename-specifier was just sugar.
5322 return Context.getElaboratedType(ETK_Typename, NNS,
5323 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00005324 }
5325
5326 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00005327 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00005328 break;
5329
John McCall7ba107a2009-11-18 02:36:19 +00005330 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005331 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00005332 return QualType();
5333
Douglas Gregord57959a2009-03-27 23:10:48 +00005334 case LookupResult::FoundOverloaded:
5335 DiagID = diag::err_typename_nested_not_type;
5336 Referenced = *Result.begin();
5337 break;
5338
John McCall6e247262009-10-10 05:48:19 +00005339 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00005340 return QualType();
5341 }
5342
5343 // If we get here, it's because name lookup did not find a
5344 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005345 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5346 IILoc);
5347 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00005348 if (Referenced)
5349 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5350 << Name;
5351 return QualType();
5352}
Douglas Gregor4a959d82009-08-06 16:20:37 +00005353
5354namespace {
5355 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00005356 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00005357 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00005358 SourceLocation Loc;
5359 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00005360
Douglas Gregor4a959d82009-08-06 16:20:37 +00005361 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00005362 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5363
Mike Stump1eb44332009-09-09 15:08:12 +00005364 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005365 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005366 DeclarationName Entity)
5367 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00005368 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00005369
5370 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00005371 /// transformed.
5372 ///
5373 /// For the purposes of type reconstruction, a type has already been
5374 /// transformed if it is NULL or if it is not dependent.
5375 bool AlreadyTransformed(QualType T) {
5376 return T.isNull() || !T->isDependentType();
5377 }
Mike Stump1eb44332009-09-09 15:08:12 +00005378
5379 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00005380 /// rebuilt.
5381 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00005382
Douglas Gregor4a959d82009-08-06 16:20:37 +00005383 /// \brief Returns the name of the entity whose type is being rebuilt.
5384 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00005385
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005386 /// \brief Sets the "base" location and entity when that
5387 /// information is known based on another transformation.
5388 void setBase(SourceLocation Loc, DeclarationName Entity) {
5389 this->Loc = Loc;
5390 this->Entity = Entity;
5391 }
5392
Douglas Gregor4a959d82009-08-06 16:20:37 +00005393 /// \brief Transforms an expression by returning the expression itself
5394 /// (an identity function).
5395 ///
5396 /// FIXME: This is completely unsafe; we will need to actually clone the
5397 /// expressions.
5398 Sema::OwningExprResult TransformExpr(Expr *E) {
Douglas Gregor895162d2010-04-30 18:55:50 +00005399 return getSema().Owned(E->Retain());
Douglas Gregor4a959d82009-08-06 16:20:37 +00005400 }
Mike Stump1eb44332009-09-09 15:08:12 +00005401
Douglas Gregor4a959d82009-08-06 16:20:37 +00005402 /// \brief Transforms a typename type by determining whether the type now
5403 /// refers to a member of the current instantiation, and then
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005404 /// type-checking and building an ElaboratedType (when possible).
5405 QualType TransformDependentNameType(TypeLocBuilder &TLB,
5406 DependentNameTypeLoc TL,
5407 QualType ObjectType);
Douglas Gregor4a959d82009-08-06 16:20:37 +00005408 };
5409}
5410
Mike Stump1eb44332009-09-09 15:08:12 +00005411QualType
Douglas Gregor4714c122010-03-31 17:34:00 +00005412CurrentInstantiationRebuilder::TransformDependentNameType(TypeLocBuilder &TLB,
5413 DependentNameTypeLoc TL,
Douglas Gregor124b8782010-02-16 19:09:40 +00005414 QualType ObjectType) {
Douglas Gregor4714c122010-03-31 17:34:00 +00005415 DependentNameType *T = TL.getTypePtr();
John McCalla2becad2009-10-21 00:40:46 +00005416
Douglas Gregor4a959d82009-08-06 16:20:37 +00005417 NestedNameSpecifier *NNS
5418 = TransformNestedNameSpecifier(T->getQualifier(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005419 TL.getQualifierRange(),
Douglas Gregor124b8782010-02-16 19:09:40 +00005420 ObjectType);
Douglas Gregor4a959d82009-08-06 16:20:37 +00005421 if (!NNS)
5422 return QualType();
5423
5424 // If the nested-name-specifier did not change, and we cannot compute the
5425 // context corresponding to the nested-name-specifier, then this
5426 // typename type will not change; exit early.
5427 CXXScopeSpec SS;
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005428 SS.setRange(TL.getQualifierRange());
Douglas Gregor4a959d82009-08-06 16:20:37 +00005429 SS.setScopeRep(NNS);
John McCall833ca992009-10-29 08:12:44 +00005430
5431 QualType Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00005432 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall833ca992009-10-29 08:12:44 +00005433 Result = QualType(T, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00005434
5435 // Rebuild the typename type, which will probably turn into a
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005436 // ElaboratedType.
John McCall833ca992009-10-29 08:12:44 +00005437 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005438 QualType NewTemplateId
Douglas Gregor4a959d82009-08-06 16:20:37 +00005439 = TransformType(QualType(TemplateId, 0));
5440 if (NewTemplateId.isNull())
5441 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005442
Douglas Gregor4a959d82009-08-06 16:20:37 +00005443 if (NNS == T->getQualifier() &&
5444 NewTemplateId == QualType(TemplateId, 0))
John McCall833ca992009-10-29 08:12:44 +00005445 Result = QualType(T, 0);
5446 else
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005447 Result = getDerived().RebuildDependentNameType(T->getKeyword(),
Douglas Gregor4a2023f2010-03-31 20:19:30 +00005448 NNS, NewTemplateId);
John McCall833ca992009-10-29 08:12:44 +00005449 } else
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005450 Result = getDerived().RebuildDependentNameType(T->getKeyword(), NNS,
5451 T->getIdentifier(),
5452 TL.getKeywordLoc(),
5453 TL.getQualifierRange(),
5454 TL.getNameLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00005455
Douglas Gregora50ce322010-03-07 23:26:22 +00005456 if (Result.isNull())
5457 return QualType();
5458
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005459 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
5460 QualType NamedT = ElabT->getNamedType();
5461 if (isa<TemplateSpecializationType>(NamedT)) {
5462 TemplateSpecializationTypeLoc NamedTLoc
5463 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
5464 // FIXME: fill locations
5465 NamedTLoc.initializeLocal(TL.getNameLoc());
5466 } else {
5467 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
5468 }
5469 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5470 NewTL.setKeywordLoc(TL.getKeywordLoc());
5471 NewTL.setQualifierRange(TL.getQualifierRange());
5472 }
5473 else {
5474 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
5475 NewTL.setKeywordLoc(TL.getKeywordLoc());
5476 NewTL.setQualifierRange(TL.getQualifierRange());
5477 NewTL.setNameLoc(TL.getNameLoc());
5478 }
John McCall833ca992009-10-29 08:12:44 +00005479 return Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00005480}
5481
5482/// \brief Rebuilds a type within the context of the current instantiation.
5483///
Mike Stump1eb44332009-09-09 15:08:12 +00005484/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00005485/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00005486/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00005487/// partial specialization thereof). This routine will rebuild that type now
5488/// that we have entered the declarator's scope, which may produce different
5489/// canonical types, e.g.,
5490///
5491/// \code
5492/// template<typename T>
5493/// struct X {
5494/// typedef T* pointer;
5495/// pointer data();
5496/// };
5497///
5498/// template<typename T>
5499/// typename X<T>::pointer X<T>::data() { ... }
5500/// \endcode
5501///
Douglas Gregor4714c122010-03-31 17:34:00 +00005502/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005503/// since we do not know that we can look into X<T> when we parsed the type.
5504/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005505/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00005506/// as the canonical type of T*, allowing the return types of the out-of-line
5507/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00005508TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5509 SourceLocation Loc,
5510 DeclarationName Name) {
5511 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00005512 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00005513
Douglas Gregor4a959d82009-08-06 16:20:37 +00005514 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5515 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00005516}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005517
John McCall63b43852010-04-29 23:50:39 +00005518bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5519 if (SS.isInvalid()) return true;
John McCall31f17ec2010-04-27 00:57:59 +00005520
5521 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5522 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5523 DeclarationName());
5524 NestedNameSpecifier *Rebuilt =
5525 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall63b43852010-04-29 23:50:39 +00005526 if (!Rebuilt) return true;
5527
5528 SS.setScopeRep(Rebuilt);
5529 return false;
John McCall31f17ec2010-04-27 00:57:59 +00005530}
5531
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005532/// \brief Produces a formatted string that describes the binding of
5533/// template parameters to template arguments.
5534std::string
5535Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5536 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005537 // FIXME: For variadic templates, we'll need to get the structured list.
5538 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5539 Args.flat_size());
5540}
5541
5542std::string
5543Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5544 const TemplateArgument *Args,
5545 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005546 std::string Result;
5547
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005548 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005549 return Result;
5550
5551 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005552 if (I >= NumArgs)
5553 break;
5554
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005555 if (I == 0)
5556 Result += "[with ";
5557 else
5558 Result += ", ";
5559
5560 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5561 Result += Id->getName();
5562 } else {
5563 Result += '$';
5564 Result += llvm::utostr(I);
5565 }
5566
5567 Result += " = ";
5568
5569 switch (Args[I].getKind()) {
5570 case TemplateArgument::Null:
5571 Result += "<no value>";
5572 break;
5573
5574 case TemplateArgument::Type: {
5575 std::string TypeStr;
5576 Args[I].getAsType().getAsStringInternal(TypeStr,
5577 Context.PrintingPolicy);
5578 Result += TypeStr;
5579 break;
5580 }
5581
5582 case TemplateArgument::Declaration: {
5583 bool Unnamed = true;
5584 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5585 if (ND->getDeclName()) {
5586 Unnamed = false;
5587 Result += ND->getNameAsString();
5588 }
5589 }
5590
5591 if (Unnamed) {
5592 Result += "<anonymous>";
5593 }
5594 break;
5595 }
5596
Douglas Gregor788cd062009-11-11 01:00:40 +00005597 case TemplateArgument::Template: {
5598 std::string Str;
5599 llvm::raw_string_ostream OS(Str);
5600 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5601 Result += OS.str();
5602 break;
5603 }
5604
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005605 case TemplateArgument::Integral: {
5606 Result += Args[I].getAsIntegral()->toString(10);
5607 break;
5608 }
5609
5610 case TemplateArgument::Expression: {
Douglas Gregor77e2c672010-04-29 04:55:13 +00005611 // FIXME: This is non-optimal, since we're regurgitating the
5612 // expression we were given.
5613 std::string Str;
5614 {
5615 llvm::raw_string_ostream OS(Str);
5616 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5617 Context.PrintingPolicy);
5618 }
5619 Result += Str;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005620 break;
5621 }
5622
5623 case TemplateArgument::Pack:
5624 // FIXME: Format template argument packs
5625 Result += "<template argument pack>";
5626 break;
5627 }
5628 }
5629
5630 Result += ']';
5631 return Result;
5632}