blob: 6a4f34731ea4db7b6c130d2275f9baaffed70e47 [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 Gregor2dd078a2009-09-02 22:59:36 +0000103 TemplateTy &TemplateResult) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000104 assert(getLangOptions().CPlusPlus && "No template names in C!");
105
Douglas Gregor014e88d2009-11-03 23:16:33 +0000106 DeclarationName TName;
107
108 switch (Name.getKind()) {
109 case UnqualifiedId::IK_Identifier:
110 TName = DeclarationName(Name.Identifier);
111 break;
112
113 case UnqualifiedId::IK_OperatorFunctionId:
114 TName = Context.DeclarationNames.getCXXOperatorName(
115 Name.OperatorFunctionId.Operator);
116 break;
117
Sean Hunte6252d12009-11-28 08:58:14 +0000118 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +0000119 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
120 break;
Sean Hunte6252d12009-11-28 08:58:14 +0000121
Douglas Gregor014e88d2009-11-03 23:16:33 +0000122 default:
123 return TNK_Non_template;
124 }
Mike Stump1eb44332009-09-09 15:08:12 +0000125
John McCallf7a1a742009-11-24 19:00:30 +0000126 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000127
Douglas Gregorbfea2392009-12-31 08:11:17 +0000128 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
129 LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +0000130 R.suppressDiagnostics();
131 LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000132 if (R.empty() || R.isAmbiguous())
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000133 return TNK_Non_template;
134
John McCall0bd6feb2009-12-02 08:04:21 +0000135 TemplateName Template;
136 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000137
John McCall0bd6feb2009-12-02 08:04:21 +0000138 unsigned ResultCount = R.end() - R.begin();
139 if (ResultCount > 1) {
140 // We assume that we'll preserve the qualifier from a function
141 // template name in other ways.
142 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
143 TemplateKind = TNK_Function_template;
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000144 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000145 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
146
147 if (SS.isSet() && !SS.isInvalid()) {
148 NestedNameSpecifier *Qualifier
149 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
150 Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
151 } else {
152 Template = TemplateName(TD);
153 }
154
155 if (isa<FunctionTemplateDecl>(TD))
156 TemplateKind = TNK_Function_template;
157 else {
158 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
159 TemplateKind = TNK_Type_template;
160 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000161 }
Mike Stump1eb44332009-09-09 15:08:12 +0000162
John McCall0bd6feb2009-12-02 08:04:21 +0000163 TemplateResult = TemplateTy::make(Template);
164 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000165}
166
Douglas Gregor84d0a192010-01-12 21:28:44 +0000167bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
168 SourceLocation IILoc,
169 Scope *S,
170 const CXXScopeSpec *SS,
171 TemplateTy &SuggestedTemplate,
172 TemplateNameKind &SuggestedKind) {
173 // We can't recover unless there's a dependent scope specifier preceding the
174 // template name.
175 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
176 computeDeclContext(*SS))
177 return false;
178
179 // The code is missing a 'template' keyword prior to the dependent template
180 // name.
181 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
182 Diag(IILoc, diag::err_template_kw_missing)
183 << Qualifier << II.getName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000184 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor84d0a192010-01-12 21:28:44 +0000185 SuggestedTemplate
186 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
187 SuggestedKind = TNK_Dependent_template_name;
188 return true;
189}
190
John McCallf7a1a742009-11-24 19:00:30 +0000191void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000192 Scope *S, CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +0000193 QualType ObjectType,
194 bool EnteringContext) {
195 // Determine where to perform name lookup
196 DeclContext *LookupCtx = 0;
197 bool isDependent = false;
198 if (!ObjectType.isNull()) {
199 // This nested-name-specifier occurs in a member access expression, e.g.,
200 // x->B::f, and we are looking into the type of the object.
201 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
202 LookupCtx = computeDeclContext(ObjectType);
203 isDependent = ObjectType->isDependentType();
204 assert((isDependent || !ObjectType->isIncompleteType()) &&
205 "Caller should have completed object type");
206 } else if (SS.isSet()) {
207 // This nested-name-specifier occurs after another nested-name-specifier,
208 // so long into the context associated with the prior nested-name-specifier.
209 LookupCtx = computeDeclContext(SS, EnteringContext);
210 isDependent = isDependentScopeSpecifier(SS);
211
212 // The declaration context must be complete.
John McCall77bb1aa2010-05-01 00:40:08 +0000213 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCallf7a1a742009-11-24 19:00:30 +0000214 return;
215 }
216
217 bool ObjectTypeSearchedInScope = false;
218 if (LookupCtx) {
219 // Perform "qualified" name lookup into the declaration context we
220 // computed, which is either the type of the base of a member access
221 // expression or the declaration context associated with a prior
222 // nested-name-specifier.
223 LookupQualifiedName(Found, LookupCtx);
224
225 if (!ObjectType.isNull() && Found.empty()) {
226 // C++ [basic.lookup.classref]p1:
227 // In a class member access expression (5.2.5), if the . or -> token is
228 // immediately followed by an identifier followed by a <, the
229 // identifier must be looked up to determine whether the < is the
230 // beginning of a template argument list (14.2) or a less-than operator.
231 // The identifier is first looked up in the class of the object
232 // expression. If the identifier is not found, it is then looked up in
233 // the context of the entire postfix-expression and shall name a class
234 // or function template.
235 //
236 // FIXME: When we're instantiating a template, do we actually have to
237 // look in the scope of the template? Seems fishy...
238 if (S) LookupName(Found, S);
239 ObjectTypeSearchedInScope = true;
240 }
241 } else if (isDependent) {
Douglas Gregor2e933882010-01-12 17:06:20 +0000242 // We cannot look into a dependent object type or nested nme
243 // specifier.
John McCallf7a1a742009-11-24 19:00:30 +0000244 return;
245 } else {
246 // Perform unqualified name lookup in the current scope.
247 LookupName(Found, S);
248 }
249
Douglas Gregor2e933882010-01-12 17:06:20 +0000250 if (Found.empty() && !isDependent) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000251 // If we did not find any names, attempt to correct any typos.
252 DeclarationName Name = Found.getLookupName();
Douglas Gregoraaf87162010-04-14 20:04:41 +0000253 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
254 false, CTC_CXXCasts)) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000255 FilterAcceptableTemplateNames(Context, Found);
256 if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
257 if (LookupCtx)
258 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
259 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000260 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000261 Found.getLookupName().getAsString());
262 else
263 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
264 << Name << Found.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000265 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000266 Found.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000267 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
268 Diag(Template->getLocation(), diag::note_previous_decl)
269 << Template->getDeclName();
Douglas Gregorbfea2392009-12-31 08:11:17 +0000270 } else
271 Found.clear();
272 } else {
273 Found.clear();
274 }
275 }
276
John McCallf7a1a742009-11-24 19:00:30 +0000277 FilterAcceptableTemplateNames(Context, Found);
278 if (Found.empty())
279 return;
280
281 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
282 // C++ [basic.lookup.classref]p1:
283 // [...] If the lookup in the class of the object expression finds a
284 // template, the name is also looked up in the context of the entire
285 // postfix-expression and [...]
286 //
287 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
288 LookupOrdinaryName);
289 LookupName(FoundOuter, S);
290 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000291
John McCallf7a1a742009-11-24 19:00:30 +0000292 if (FoundOuter.empty()) {
293 // - if the name is not found, the name found in the class of the
294 // object expression is used, otherwise
295 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
296 // - if the name is found in the context of the entire
297 // postfix-expression and does not name a class template, the name
298 // found in the class of the object expression is used, otherwise
299 } else {
300 // - if the name found is a class template, it must refer to the same
301 // entity as the one found in the class of the object expression,
302 // otherwise the program is ill-formed.
303 if (!Found.isSingleResult() ||
304 Found.getFoundDecl()->getCanonicalDecl()
305 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
306 Diag(Found.getNameLoc(),
307 diag::err_nested_name_member_ref_lookup_ambiguous)
308 << Found.getLookupName();
309 Diag(Found.getRepresentativeDecl()->getLocation(),
310 diag::note_ambig_member_ref_object_type)
311 << ObjectType;
312 Diag(FoundOuter.getFoundDecl()->getLocation(),
313 diag::note_ambig_member_ref_scope);
314
315 // Recover by taking the template that we found in the object
316 // expression's type.
317 }
318 }
319 }
320}
321
John McCall2f841ba2009-12-02 03:53:29 +0000322/// ActOnDependentIdExpression - Handle a dependent id-expression that
323/// was just parsed. This is only possible with an explicit scope
324/// specifier naming a dependent type.
John McCallf7a1a742009-11-24 19:00:30 +0000325Sema::OwningExprResult
326Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
327 DeclarationName Name,
328 SourceLocation NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +0000329 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000330 const TemplateArgumentListInfo *TemplateArgs) {
331 NestedNameSpecifier *Qualifier
332 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallea1471e2010-05-20 01:18:31 +0000333
334 DeclContext *DC = getFunctionLevelDeclContext();
John McCallf7a1a742009-11-24 19:00:30 +0000335
John McCall2f841ba2009-12-02 03:53:29 +0000336 if (!isAddressOfOperand &&
John McCallea1471e2010-05-20 01:18:31 +0000337 isa<CXXMethodDecl>(DC) &&
338 cast<CXXMethodDecl>(DC)->isInstance()) {
339 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2f841ba2009-12-02 03:53:29 +0000340
John McCallf7a1a742009-11-24 19:00:30 +0000341 // Since the 'this' expression is synthesized, we don't need to
342 // perform the double-lookup check.
343 NamedDecl *FirstQualifierInScope = 0;
344
John McCallaa81e162009-12-01 22:10:20 +0000345 return Owned(CXXDependentScopeMemberExpr::Create(Context,
346 /*This*/ 0, ThisType,
347 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000348 /*Op*/ SourceLocation(),
349 Qualifier, SS.getRange(),
350 FirstQualifierInScope,
351 Name, NameLoc,
352 TemplateArgs));
353 }
354
355 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
356}
357
358Sema::OwningExprResult
359Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
360 DeclarationName Name,
361 SourceLocation NameLoc,
362 const TemplateArgumentListInfo *TemplateArgs) {
363 return Owned(DependentScopeDeclRefExpr::Create(Context,
364 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
365 SS.getRange(),
366 Name, NameLoc,
367 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000368}
369
Douglas Gregor72c3f312008-12-05 18:15:24 +0000370/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
371/// that the template parameter 'PrevDecl' is being shadowed by a new
372/// declaration at location Loc. Returns true to indicate that this is
373/// an error, and false otherwise.
374bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000375 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000376
377 // Microsoft Visual C++ permits template parameters to be shadowed.
378 if (getLangOptions().Microsoft)
379 return false;
380
381 // C++ [temp.local]p4:
382 // A template-parameter shall not be redeclared within its
383 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000384 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000385 << cast<NamedDecl>(PrevDecl)->getDeclName();
386 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
387 return true;
388}
389
Douglas Gregor2943aed2009-03-03 04:44:36 +0000390/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000391/// the parameter D to reference the templated declaration and return a pointer
392/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000393TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor13d2d6c2009-10-06 21:27:51 +0000394 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000395 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000396 return Temp;
397 }
398 return 0;
399}
400
Douglas Gregor788cd062009-11-11 01:00:40 +0000401static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
402 const ParsedTemplateArgument &Arg) {
403
404 switch (Arg.getKind()) {
405 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000406 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000407 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
408 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000409 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000410 return TemplateArgumentLoc(TemplateArgument(T), DI);
411 }
412
413 case ParsedTemplateArgument::NonType: {
414 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
415 return TemplateArgumentLoc(TemplateArgument(E), E);
416 }
417
418 case ParsedTemplateArgument::Template: {
419 TemplateName Template
420 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
421 return TemplateArgumentLoc(TemplateArgument(Template),
422 Arg.getScopeSpec().getRange(),
423 Arg.getLocation());
424 }
425 }
426
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000427 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000428 return TemplateArgumentLoc();
429}
430
431/// \brief Translates template arguments as provided by the parser
432/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000433void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
434 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000435 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000436 TemplateArgs.addArgument(translateTemplateArgument(*this,
437 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000438}
439
Douglas Gregor72c3f312008-12-05 18:15:24 +0000440/// ActOnTypeParameter - Called when a C++ template type parameter
441/// (e.g., "typename T") has been parsed. Typename specifies whether
442/// the keyword "typename" was used to declare the type parameter
443/// (otherwise, "class" was used), and KeyLoc is the location of the
444/// "class" or "typename" keyword. ParamName is the name of the
445/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump1eb44332009-09-09 15:08:12 +0000446/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000447/// If the type parameter has a default argument, it will be added
448/// later via ActOnTypeParameterDefault.
Mike Stump1eb44332009-09-09 15:08:12 +0000449Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson941df7d2009-06-12 19:58:00 +0000450 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000451 SourceLocation KeyLoc,
452 IdentifierInfo *ParamName,
453 SourceLocation ParamNameLoc,
454 unsigned Depth, unsigned Position) {
Mike Stump1eb44332009-09-09 15:08:12 +0000455 assert(S->isTemplateParamScope() &&
456 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000457 bool Invalid = false;
458
459 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000460 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000461 LookupOrdinaryName,
462 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000463 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000464 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000465 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000466 }
467
Douglas Gregorddc29e12009-02-06 22:42:48 +0000468 SourceLocation Loc = ParamNameLoc;
469 if (!ParamName)
470 Loc = KeyLoc;
471
Douglas Gregor72c3f312008-12-05 18:15:24 +0000472 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000473 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
474 Loc, Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000475 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000476 if (Invalid)
477 Param->setInvalidDecl();
478
479 if (ParamName) {
480 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000481 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000482 IdResolver.AddDecl(Param);
483 }
484
Chris Lattnerb28317a2009-03-28 19:18:32 +0000485 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000486}
487
Douglas Gregord684b002009-02-10 19:49:53 +0000488/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump1eb44332009-09-09 15:08:12 +0000489/// Default) to the given template type parameter (TypeParam).
490void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000491 SourceLocation EqualLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000492 SourceLocation DefaultLoc,
Douglas Gregord684b002009-02-10 19:49:53 +0000493 TypeTy *DefaultT) {
Mike Stump1eb44332009-09-09 15:08:12 +0000494 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000495 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall833ca992009-10-29 08:12:44 +0000496
John McCalla93c9342009-12-07 02:54:59 +0000497 TypeSourceInfo *DefaultTInfo;
498 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall833ca992009-10-29 08:12:44 +0000499
John McCalla93c9342009-12-07 02:54:59 +0000500 assert(DefaultTInfo && "expected source information for type");
Douglas Gregord684b002009-02-10 19:49:53 +0000501
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000502 // C++0x [temp.param]p9:
503 // A default template-argument may be specified for any kind of
Mike Stump1eb44332009-09-09 15:08:12 +0000504 // template-parameter that is not a template parameter pack.
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000505 if (Parm->isParameterPack()) {
506 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000507 return;
508 }
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Douglas Gregord684b002009-02-10 19:49:53 +0000510 // C++ [temp.param]p14:
511 // A template-parameter shall not be used in its own default argument.
512 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Douglas Gregord684b002009-02-10 19:49:53 +0000514 // Check the template argument itself.
John McCalla93c9342009-12-07 02:54:59 +0000515 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000516 Parm->setInvalidDecl();
517 return;
518 }
519
John McCalla93c9342009-12-07 02:54:59 +0000520 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000521}
522
Douglas Gregor2943aed2009-03-03 04:44:36 +0000523/// \brief Check that the type of a non-type template parameter is
524/// well-formed.
525///
526/// \returns the (possibly-promoted) parameter type if valid;
527/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000528QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000529Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
530 // C++ [temp.param]p4:
531 //
532 // A non-type template-parameter shall have one of the following
533 // (optionally cv-qualified) types:
534 //
535 // -- integral or enumeration type,
536 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000537 // -- pointer to object or pointer to function,
538 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000539 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
540 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000541 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000542 T->isReferenceType() ||
543 // -- pointer to member.
544 T->isMemberPointerType() ||
545 // If T is a dependent type, we can't do the check now, so we
546 // assume that it is well-formed.
547 T->isDependentType())
548 return T;
549 // C++ [temp.param]p8:
550 //
551 // A non-type template-parameter of type "array of T" or
552 // "function returning T" is adjusted to be of type "pointer to
553 // T" or "pointer to function returning T", respectively.
554 else if (T->isArrayType())
555 // FIXME: Keep the type prior to promotion?
556 return Context.getArrayDecayedType(T);
557 else if (T->isFunctionType())
558 // FIXME: Keep the type prior to promotion?
559 return Context.getPointerType(T);
560
561 Diag(Loc, diag::err_template_nontype_parm_bad_type)
562 << T;
563
564 return QualType();
565}
566
Douglas Gregor72c3f312008-12-05 18:15:24 +0000567/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
568/// template parameter (e.g., "int Size" in "template<int Size>
569/// class Array") has been parsed. S is the current scope and D is
570/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000571Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump1eb44332009-09-09 15:08:12 +0000572 unsigned Depth,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000573 unsigned Position) {
John McCalla93c9342009-12-07 02:54:59 +0000574 TypeSourceInfo *TInfo = 0;
575 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000576
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000577 assert(S->isTemplateParamScope() &&
578 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000579 bool Invalid = false;
580
581 IdentifierInfo *ParamName = D.getIdentifier();
582 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000583 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000584 LookupOrdinaryName,
585 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000586 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000587 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000588 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000589 }
590
Douglas Gregor2943aed2009-03-03 04:44:36 +0000591 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000592 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000593 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000594 Invalid = true;
595 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000596
Douglas Gregor72c3f312008-12-05 18:15:24 +0000597 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000598 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
599 D.getIdentifierLoc(),
John McCalla93c9342009-12-07 02:54:59 +0000600 Depth, Position, ParamName, T, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000601 if (Invalid)
602 Param->setInvalidDecl();
603
604 if (D.getIdentifier()) {
605 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000606 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000607 IdResolver.AddDecl(Param);
608 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000609 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000610}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000611
Douglas Gregord684b002009-02-10 19:49:53 +0000612/// \brief Adds a default argument to the given non-type template
613/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000614void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000615 SourceLocation EqualLoc,
616 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000617 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000618 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000619 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Douglas Gregord684b002009-02-10 19:49:53 +0000621 // C++ [temp.param]p14:
622 // A template-parameter shall not be used in its own default argument.
623 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000624
Douglas Gregord684b002009-02-10 19:49:53 +0000625 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000626 TemplateArgument Converted;
627 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
628 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000629 TemplateParm->setInvalidDecl();
630 return;
631 }
632
Anders Carlssone9146f22009-05-01 19:49:17 +0000633 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000634}
635
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000636
637/// ActOnTemplateTemplateParameter - Called when a C++ template template
638/// parameter (e.g. T in template <template <typename> class T> class array)
639/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000640Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
641 SourceLocation TmpLoc,
642 TemplateParamsTy *Params,
643 IdentifierInfo *Name,
644 SourceLocation NameLoc,
645 unsigned Depth,
Mike Stump1eb44332009-09-09 15:08:12 +0000646 unsigned Position) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000647 assert(S->isTemplateParamScope() &&
648 "Template template parameter not in template parameter scope!");
649
650 // Construct the parameter object.
651 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000652 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
653 TmpLoc, Depth, Position, Name,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000654 (TemplateParameterList*)Params);
655
656 // Make sure the parameter is valid.
657 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
658 // do anything yet. However, if the template parameter list or (eventual)
659 // default value is ever invalidated, that will propagate here.
660 bool Invalid = false;
661 if (Invalid) {
662 Param->setInvalidDecl();
663 }
664
665 // If the tt-param has a name, then link the identifier into the scope
666 // and lookup mechanisms.
667 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000668 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000669 IdResolver.AddDecl(Param);
670 }
671
Chris Lattnerb28317a2009-03-28 19:18:32 +0000672 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000673}
674
Douglas Gregord684b002009-02-10 19:49:53 +0000675/// \brief Adds a default argument to the given template template
676/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000677void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000678 SourceLocation EqualLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +0000679 const ParsedTemplateArgument &Default) {
Mike Stump1eb44332009-09-09 15:08:12 +0000680 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000681 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor788cd062009-11-11 01:00:40 +0000682
Douglas Gregord684b002009-02-10 19:49:53 +0000683 // C++ [temp.param]p14:
684 // A template-parameter shall not be used in its own default argument.
685 // FIXME: Implement this check! Needs a recursive walk over the types.
686
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000687 // Check only that we have a template template argument. We don't want to
688 // try to check well-formedness now, because our template template parameter
689 // might have dependent types in its template parameters, which we wouldn't
690 // be able to match now.
691 //
692 // If none of the template template parameter's template arguments mention
693 // other template parameters, we could actually perform more checking here.
694 // However, it isn't worth doing.
Douglas Gregor788cd062009-11-11 01:00:40 +0000695 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000696 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
697 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
698 << DefaultArg.getSourceRange();
Douglas Gregord684b002009-02-10 19:49:53 +0000699 return;
700 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000701
Douglas Gregor788cd062009-11-11 01:00:40 +0000702 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregord684b002009-02-10 19:49:53 +0000703}
704
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000705/// ActOnTemplateParameterList - Builds a TemplateParameterList that
706/// contains the template parameters in Params/NumParams.
707Sema::TemplateParamsTy *
708Sema::ActOnTemplateParameterList(unsigned Depth,
709 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000710 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000711 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000712 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000713 SourceLocation RAngleLoc) {
714 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000715 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000716
Douglas Gregorddc29e12009-02-06 22:42:48 +0000717 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000718 (NamedDecl**)Params, NumParams,
719 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000720}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000721
John McCallb6217662010-03-15 10:12:16 +0000722static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
723 if (SS.isSet())
724 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
725 SS.getRange());
726}
727
Douglas Gregor212e81c2009-03-25 00:13:59 +0000728Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000729Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000730 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000731 IdentifierInfo *Name, SourceLocation NameLoc,
732 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000733 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000734 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000735 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000736 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000737 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000738 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000739
740 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000741 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000742 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000743
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000744 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
745 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000746
747 // There is no such thing as an unnamed class template.
748 if (!Name) {
749 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000750 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000751 }
752
753 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000754 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000755 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000756 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000757 if (SS.isNotEmpty() && !SS.isInvalid()) {
758 SemanticContext = computeDeclContext(SS, true);
759 if (!SemanticContext) {
760 // FIXME: Produce a reasonable diagnostic here
761 return true;
762 }
Mike Stump1eb44332009-09-09 15:08:12 +0000763
John McCall77bb1aa2010-05-01 00:40:08 +0000764 if (RequireCompleteDeclContext(SS, SemanticContext))
765 return true;
766
John McCalla24dc2e2009-11-17 02:14:36 +0000767 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000768 } else {
769 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000770 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000771 }
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Douglas Gregor57265e32010-04-12 16:00:01 +0000773 if (Previous.isAmbiguous())
774 return true;
775
Douglas Gregorddc29e12009-02-06 22:42:48 +0000776 NamedDecl *PrevDecl = 0;
777 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000778 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000779
Douglas Gregorddc29e12009-02-06 22:42:48 +0000780 // If there is a previous declaration with the same name, check
781 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000782 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000783 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000784
785 // We may have found the injected-class-name of a class template,
786 // class template partial specialization, or class template specialization.
787 // In these cases, grab the template that is being defined or specialized.
788 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
789 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
790 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
791 PrevClassTemplate
792 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
793 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
794 PrevClassTemplate
795 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
796 ->getSpecializedTemplate();
797 }
798 }
799
John McCall65c49462009-12-18 11:25:59 +0000800 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000801 // C++ [namespace.memdef]p3:
802 // [...] When looking for a prior declaration of a class or a function
803 // declared as a friend, and when the name of the friend class or
804 // function is neither a qualified name nor a template-id, scopes outside
805 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000806 if (!SS.isSet()) {
807 DeclContext *OutermostContext = CurContext;
808 while (!OutermostContext->isFileContext())
809 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000810
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000811 if (PrevDecl &&
812 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
813 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
814 SemanticContext = PrevDecl->getDeclContext();
815 } else {
816 // Declarations in outer scopes don't matter. However, the outermost
817 // context we computed is the semantic context for our new
818 // declaration.
819 PrevDecl = PrevClassTemplate = 0;
820 SemanticContext = OutermostContext;
821 }
John McCalle129d442009-12-17 23:21:11 +0000822 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000823
John McCalle129d442009-12-17 23:21:11 +0000824 if (CurContext->isDependentContext()) {
825 // If this is a dependent context, we don't want to link the friend
826 // class template to the template in scope, because that would perform
827 // checking of the template parameter lists that can't be performed
828 // until the outer context is instantiated.
829 PrevDecl = PrevClassTemplate = 0;
830 }
831 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
832 PrevDecl = PrevClassTemplate = 0;
Douglas Gregor57265e32010-04-12 16:00:01 +0000833
Douglas Gregorddc29e12009-02-06 22:42:48 +0000834 if (PrevClassTemplate) {
835 // Ensure that the template parameter lists are compatible.
836 if (!TemplateParameterListsAreEqual(TemplateParams,
837 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000838 /*Complain=*/true,
839 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000840 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000841
842 // C++ [temp.class]p4:
843 // In a redeclaration, partial specialization, explicit
844 // specialization or explicit instantiation of a class template,
845 // the class-key shall agree in kind with the original class
846 // template declaration (7.1.5.3).
847 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000848 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000849 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000850 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000851 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000852 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000853 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000854 }
855
Douglas Gregorddc29e12009-02-06 22:42:48 +0000856 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000857 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000858 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000859 Diag(NameLoc, diag::err_redefinition) << Name;
860 Diag(Def->getLocation(), diag::note_previous_definition);
861 // FIXME: Would it make sense to try to "forget" the previous
862 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000863 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000864 }
865 }
866 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
867 // Maybe we will complain about the shadowed template parameter.
868 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
869 // Just pretend that we didn't see the previous declaration.
870 PrevDecl = 0;
871 } else if (PrevDecl) {
872 // C++ [temp]p5:
873 // A class template shall not have the same name as any other
874 // template, class, function, object, enumeration, enumerator,
875 // namespace, or type in the same scope (3.3), except as specified
876 // in (14.5.4).
877 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
878 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000879 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000880 }
881
Douglas Gregord684b002009-02-10 19:49:53 +0000882 // Check the template parameter list of this declaration, possibly
883 // merging in the template parameter list from the previous class
884 // template declaration.
885 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000886 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
887 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000888 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Douglas Gregor57265e32010-04-12 16:00:01 +0000890 if (SS.isSet()) {
891 // If the name of the template was qualified, we must be defining the
892 // template out-of-line.
893 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
894 !(TUK == TUK_Friend && CurContext->isDependentContext()))
895 Diag(NameLoc, diag::err_member_def_does_not_match)
896 << Name << SemanticContext << SS.getRange();
897 }
898
Mike Stump1eb44332009-09-09 15:08:12 +0000899 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000900 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000901 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000902 PrevClassTemplate->getTemplatedDecl() : 0,
903 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000904 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000905
906 ClassTemplateDecl *NewTemplate
907 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
908 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000909 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000910 NewClass->setDescribedClassTemplate(NewTemplate);
911
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000912 // Build the type for the class template declaration now.
John McCall3cb0ebd2010-03-10 03:28:59 +0000913 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
914 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000915 assert(T->isDependentType() && "Class template type is not dependent?");
916 (void)T;
917
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000918 // If we are providing an explicit specialization of a member that is a
919 // class template, make a note of that.
920 if (PrevClassTemplate &&
921 PrevClassTemplate->getInstantiatedFromMemberTemplate())
922 PrevClassTemplate->setMemberSpecialization();
923
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000924 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000925 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000926 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Douglas Gregorddc29e12009-02-06 22:42:48 +0000928 // Set the lexical context of these templates
929 NewClass->setLexicalDeclContext(CurContext);
930 NewTemplate->setLexicalDeclContext(CurContext);
931
John McCall0f434ec2009-07-31 02:45:11 +0000932 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000933 NewClass->startDefinition();
934
935 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000936 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000937
John McCall05b23ea2009-09-14 21:59:20 +0000938 if (TUK != TUK_Friend)
939 PushOnScopeChains(NewTemplate, S);
940 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000941 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000942 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000943 NewClass->setAccess(PrevClassTemplate->getAccess());
944 }
John McCall05b23ea2009-09-14 21:59:20 +0000945
Douglas Gregord85bea22009-09-26 06:47:28 +0000946 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
947 PrevClassTemplate != NULL);
948
John McCall05b23ea2009-09-14 21:59:20 +0000949 // Friend templates are visible in fairly strange ways.
950 if (!CurContext->isDependentContext()) {
951 DeclContext *DC = SemanticContext->getLookupContext();
952 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
953 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
954 PushOnScopeChains(NewTemplate, EnclosingScope,
955 /* AddToContext = */ false);
956 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000957
958 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
959 NewClass->getLocation(),
960 NewTemplate,
961 /*FIXME:*/NewClass->getLocation());
962 Friend->setAccess(AS_public);
963 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000964 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000965
Douglas Gregord684b002009-02-10 19:49:53 +0000966 if (Invalid) {
967 NewTemplate->setInvalidDecl();
968 NewClass->setInvalidDecl();
969 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000970 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000971}
972
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000973/// \brief Diagnose the presence of a default template argument on a
974/// template parameter, which is ill-formed in certain contexts.
975///
976/// \returns true if the default template argument should be dropped.
977static bool DiagnoseDefaultTemplateArgument(Sema &S,
978 Sema::TemplateParamListContext TPC,
979 SourceLocation ParamLoc,
980 SourceRange DefArgRange) {
981 switch (TPC) {
982 case Sema::TPC_ClassTemplate:
983 return false;
984
985 case Sema::TPC_FunctionTemplate:
986 // C++ [temp.param]p9:
987 // A default template-argument shall not be specified in a
988 // function template declaration or a function template
989 // definition [...]
990 // (This sentence is not in C++0x, per DR226).
991 if (!S.getLangOptions().CPlusPlus0x)
992 S.Diag(ParamLoc,
993 diag::err_template_parameter_default_in_function_template)
994 << DefArgRange;
995 return false;
996
997 case Sema::TPC_ClassTemplateMember:
998 // C++0x [temp.param]p9:
999 // A default template-argument shall not be specified in the
1000 // template-parameter-lists of the definition of a member of a
1001 // class template that appears outside of the member's class.
1002 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1003 << DefArgRange;
1004 return true;
1005
1006 case Sema::TPC_FriendFunctionTemplate:
1007 // C++ [temp.param]p9:
1008 // A default template-argument shall not be specified in a
1009 // friend template declaration.
1010 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1011 << DefArgRange;
1012 return true;
1013
1014 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1015 // for friend function templates if there is only a single
1016 // declaration (and it is a definition). Strange!
1017 }
1018
1019 return false;
1020}
1021
Douglas Gregord684b002009-02-10 19:49:53 +00001022/// \brief Checks the validity of a template parameter list, possibly
1023/// considering the template parameter list from a previous
1024/// declaration.
1025///
1026/// If an "old" template parameter list is provided, it must be
1027/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1028/// template parameter list.
1029///
1030/// \param NewParams Template parameter list for a new template
1031/// declaration. This template parameter list will be updated with any
1032/// default arguments that are carried through from the previous
1033/// template parameter list.
1034///
1035/// \param OldParams If provided, template parameter list from a
1036/// previous declaration of the same template. Default template
1037/// arguments will be merged from the old template parameter list to
1038/// the new template parameter list.
1039///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001040/// \param TPC Describes the context in which we are checking the given
1041/// template parameter list.
1042///
Douglas Gregord684b002009-02-10 19:49:53 +00001043/// \returns true if an error occurred, false otherwise.
1044bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001045 TemplateParameterList *OldParams,
1046 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001047 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Douglas Gregord684b002009-02-10 19:49:53 +00001049 // C++ [temp.param]p10:
1050 // The set of default template-arguments available for use with a
1051 // template declaration or definition is obtained by merging the
1052 // default arguments from the definition (if in scope) and all
1053 // declarations in scope in the same way default function
1054 // arguments are (8.3.6).
1055 bool SawDefaultArgument = false;
1056 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001057
Anders Carlsson49d25572009-06-12 23:20:15 +00001058 bool SawParameterPack = false;
1059 SourceLocation ParameterPackLoc;
1060
Mike Stump1a35fde2009-02-11 23:03:27 +00001061 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001062 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001063 if (OldParams)
1064 OldParam = OldParams->begin();
1065
1066 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1067 NewParamEnd = NewParams->end();
1068 NewParam != NewParamEnd; ++NewParam) {
1069 // Variables used to diagnose redundant default arguments
1070 bool RedundantDefaultArg = false;
1071 SourceLocation OldDefaultLoc;
1072 SourceLocation NewDefaultLoc;
1073
1074 // Variables used to diagnose missing default arguments
1075 bool MissingDefaultArg = false;
1076
Anders Carlsson49d25572009-06-12 23:20:15 +00001077 // C++0x [temp.param]p11:
1078 // If a template parameter of a class template is a template parameter pack,
1079 // it must be the last template parameter.
1080 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001081 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001082 diag::err_template_param_pack_must_be_last_template_parameter);
1083 Invalid = true;
1084 }
1085
Douglas Gregord684b002009-02-10 19:49:53 +00001086 if (TemplateTypeParmDecl *NewTypeParm
1087 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001088 // Check the presence of a default argument here.
1089 if (NewTypeParm->hasDefaultArgument() &&
1090 DiagnoseDefaultTemplateArgument(*this, TPC,
1091 NewTypeParm->getLocation(),
1092 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001093 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001094 NewTypeParm->removeDefaultArgument();
1095
1096 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001097 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001098 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Anders Carlsson49d25572009-06-12 23:20:15 +00001100 if (NewTypeParm->isParameterPack()) {
1101 assert(!NewTypeParm->hasDefaultArgument() &&
1102 "Parameter packs can't have a default argument!");
1103 SawParameterPack = true;
1104 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001105 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001106 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001107 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1108 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1109 SawDefaultArgument = true;
1110 RedundantDefaultArg = true;
1111 PreviousDefaultArgLoc = NewDefaultLoc;
1112 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1113 // Merge the default argument from the old declaration to the
1114 // new declaration.
1115 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001116 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001117 true);
1118 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1119 } else if (NewTypeParm->hasDefaultArgument()) {
1120 SawDefaultArgument = true;
1121 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1122 } else if (SawDefaultArgument)
1123 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001124 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001125 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001126 // Check the presence of a default argument here.
1127 if (NewNonTypeParm->hasDefaultArgument() &&
1128 DiagnoseDefaultTemplateArgument(*this, TPC,
1129 NewNonTypeParm->getLocation(),
1130 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1131 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1132 NewNonTypeParm->setDefaultArgument(0);
1133 }
1134
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001135 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001136 NonTypeTemplateParmDecl *OldNonTypeParm
1137 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001138 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001139 NewNonTypeParm->hasDefaultArgument()) {
1140 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1141 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1142 SawDefaultArgument = true;
1143 RedundantDefaultArg = true;
1144 PreviousDefaultArgLoc = NewDefaultLoc;
1145 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1146 // Merge the default argument from the old declaration to the
1147 // new declaration.
1148 SawDefaultArgument = true;
1149 // FIXME: We need to create a new kind of "default argument"
1150 // expression that points to a previous template template
1151 // parameter.
1152 NewNonTypeParm->setDefaultArgument(
1153 OldNonTypeParm->getDefaultArgument());
1154 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1155 } else if (NewNonTypeParm->hasDefaultArgument()) {
1156 SawDefaultArgument = true;
1157 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1158 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001159 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001160 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001161 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001162 TemplateTemplateParmDecl *NewTemplateParm
1163 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001164 if (NewTemplateParm->hasDefaultArgument() &&
1165 DiagnoseDefaultTemplateArgument(*this, TPC,
1166 NewTemplateParm->getLocation(),
1167 NewTemplateParm->getDefaultArgument().getSourceRange()))
1168 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1169
1170 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001171 TemplateTemplateParmDecl *OldTemplateParm
1172 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001173 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001174 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001175 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1176 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001177 SawDefaultArgument = true;
1178 RedundantDefaultArg = true;
1179 PreviousDefaultArgLoc = NewDefaultLoc;
1180 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1181 // Merge the default argument from the old declaration to the
1182 // new declaration.
1183 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001184 // FIXME: We need to create a new kind of "default argument" expression
1185 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001186 NewTemplateParm->setDefaultArgument(
1187 OldTemplateParm->getDefaultArgument());
Douglas Gregor788cd062009-11-11 01:00:40 +00001188 PreviousDefaultArgLoc
1189 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001190 } else if (NewTemplateParm->hasDefaultArgument()) {
1191 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001192 PreviousDefaultArgLoc
1193 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001194 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001195 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001196 }
1197
1198 if (RedundantDefaultArg) {
1199 // C++ [temp.param]p12:
1200 // A template-parameter shall not be given default arguments
1201 // by two different declarations in the same scope.
1202 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1203 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1204 Invalid = true;
1205 } else if (MissingDefaultArg) {
1206 // C++ [temp.param]p11:
1207 // If a template-parameter has a default template-argument,
1208 // all subsequent template-parameters shall have a default
1209 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001210 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001211 diag::err_template_param_default_arg_missing);
1212 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1213 Invalid = true;
1214 }
1215
1216 // If we have an old template parameter list that we're merging
1217 // in, move on to the next parameter.
1218 if (OldParams)
1219 ++OldParam;
1220 }
1221
1222 return Invalid;
1223}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001224
Mike Stump1eb44332009-09-09 15:08:12 +00001225/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001226/// specifier, returning the template parameter list that applies to the
1227/// name.
1228///
1229/// \param DeclStartLoc the start of the declaration that has a scope
1230/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001231///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001232/// \param SS the scope specifier that will be matched to the given template
1233/// parameter lists. This scope specifier precedes a qualified name that is
1234/// being declared.
1235///
1236/// \param ParamLists the template parameter lists, from the outermost to the
1237/// innermost template parameter lists.
1238///
1239/// \param NumParamLists the number of template parameter lists in ParamLists.
1240///
John McCall77e8b112010-04-13 20:37:33 +00001241/// \param IsFriend Whether to apply the slightly different rules for
1242/// matching template parameters to scope specifiers in friend
1243/// declarations.
1244///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001245/// \param IsExplicitSpecialization will be set true if the entity being
1246/// declared is an explicit specialization, false otherwise.
1247///
Mike Stump1eb44332009-09-09 15:08:12 +00001248/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001249/// name that is preceded by the scope specifier @p SS. This template
1250/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001251/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001252/// template specialization), or may be NULL (if we were's declaring isn't
1253/// itself a template).
1254TemplateParameterList *
1255Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1256 const CXXScopeSpec &SS,
1257 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001258 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001259 bool IsFriend,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001260 bool &IsExplicitSpecialization) {
1261 IsExplicitSpecialization = false;
1262
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001263 // Find the template-ids that occur within the nested-name-specifier. These
1264 // template-ids will match up with the template parameter lists.
1265 llvm::SmallVector<const TemplateSpecializationType *, 4>
1266 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001267 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1268 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001269 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1270 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001271 const Type *T = NNS->getAsType();
1272 if (!T) break;
1273
1274 // C++0x [temp.expl.spec]p17:
1275 // A member or a member template may be nested within many
1276 // enclosing class templates. In an explicit specialization for
1277 // such a member, the member declaration shall be preceded by a
1278 // template<> for each enclosing class template that is
1279 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001280 //
1281 // Following the existing practice of GNU and EDG, we allow a typedef of a
1282 // template specialization type.
1283 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1284 T = TT->LookThroughTypedefs().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001285
Mike Stump1eb44332009-09-09 15:08:12 +00001286 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001287 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001288 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1289 if (!Template)
1290 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Ted Kremenek6217b802009-07-29 21:53:49 +00001292 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001293 ClassTemplateSpecializationDecl *SpecDecl
1294 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1295 // If the nested name specifier refers to an explicit specialization,
1296 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001297 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1298 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001299 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001300 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001301 }
Mike Stump1eb44332009-09-09 15:08:12 +00001302
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001303 TemplateIdsInSpecifier.push_back(SpecType);
1304 }
1305 }
Mike Stump1eb44332009-09-09 15:08:12 +00001306
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001307 // Reverse the list of template-ids in the scope specifier, so that we can
1308 // more easily match up the template-ids and the template parameter lists.
1309 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001310
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001311 SourceLocation FirstTemplateLoc = DeclStartLoc;
1312 if (NumParamLists)
1313 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001315 // Match the template-ids found in the specifier to the template parameter
1316 // lists.
1317 unsigned Idx = 0;
1318 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1319 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001320 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1321 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001322 if (Idx >= NumParamLists) {
1323 // We have a template-id without a corresponding template parameter
1324 // list.
John McCall77e8b112010-04-13 20:37:33 +00001325
1326 // ...which is fine if this is a friend declaration.
1327 if (IsFriend) {
1328 IsExplicitSpecialization = true;
1329 break;
1330 }
1331
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001332 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001333 // FIXME: the location information here isn't great.
1334 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001335 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001336 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001337 << SS.getRange();
1338 } else {
1339 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1340 << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00001341 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001342 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001343 }
1344 return 0;
1345 }
Mike Stump1eb44332009-09-09 15:08:12 +00001346
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001347 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001348 if (DependentTemplateId) {
John McCall31f17ec2010-04-27 00:57:59 +00001349 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00001350
John McCall31f17ec2010-04-27 00:57:59 +00001351 // Are there cases in (e.g.) friends where this won't match?
1352 if (const InjectedClassNameType *Injected
1353 = TemplateId->getAs<InjectedClassNameType>()) {
1354 CXXRecordDecl *Record = Injected->getDecl();
1355 if (ClassTemplatePartialSpecializationDecl *Partial =
1356 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1357 ExpectedTemplateParams = Partial->getTemplateParameters();
1358 else
1359 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1360 ->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001361 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001362
John McCall31f17ec2010-04-27 00:57:59 +00001363 if (ExpectedTemplateParams)
1364 TemplateParameterListsAreEqual(ParamLists[Idx],
1365 ExpectedTemplateParams,
1366 true, TPL_TemplateMatch);
1367
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001368 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregorb88e8882009-07-30 17:40:51 +00001369 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001370 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001371 diag::err_template_param_list_matches_nontemplate)
1372 << TemplateId
1373 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001374 else
1375 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001376 }
Mike Stump1eb44332009-09-09 15:08:12 +00001377
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001378 // If there were at least as many template-ids as there were template
1379 // parameter lists, then there are no template parameter lists remaining for
1380 // the declaration itself.
1381 if (Idx >= NumParamLists)
1382 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001383
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001384 // If there were too many template parameter lists, complain about that now.
1385 if (Idx != NumParamLists - 1) {
1386 while (Idx < NumParamLists - 1) {
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001387 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001388 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001389 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1390 : diag::err_template_spec_extra_headers)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001391 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1392 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001393
1394 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1395 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1396 diag::note_explicit_template_spec_does_not_need_header)
1397 << ExplicitSpecializationsInSpecifier.back();
1398 ExplicitSpecializationsInSpecifier.pop_back();
1399 }
1400
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001401 ++Idx;
1402 }
1403 }
Mike Stump1eb44332009-09-09 15:08:12 +00001404
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001405 // Return the last template parameter list, which corresponds to the
1406 // entity being declared.
1407 return ParamLists[NumParamLists - 1];
1408}
1409
Douglas Gregor7532dc62009-03-30 22:58:21 +00001410QualType Sema::CheckTemplateIdType(TemplateName Name,
1411 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001412 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001413 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001414 if (!Template) {
1415 // The template name does not resolve to a template, so we just
1416 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001417 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001418 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001419
Douglas Gregor40808ce2009-03-09 23:48:35 +00001420 // Check that the template argument list is well-formed for this
1421 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001422 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCalld5532b62009-11-23 01:53:49 +00001423 TemplateArgs.size());
1424 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001425 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001426 return QualType();
1427
Mike Stump1eb44332009-09-09 15:08:12 +00001428 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001429 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001430 "Converted template argument list is too short!");
1431
1432 QualType CanonType;
John McCall31f17ec2010-04-27 00:57:59 +00001433 bool IsCurrentInstantiation = false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001434
Douglas Gregorcaddba02009-11-12 18:38:13 +00001435 if (Name.isDependent() ||
1436 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001437 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001438 // This class template specialization is a dependent
1439 // type. Therefore, its canonical type is another class template
1440 // specialization type that contains all of the converted
1441 // arguments in canonical form. This ensures that, e.g., A<T> and
1442 // A<T, T> have identical types when A is declared as:
1443 //
1444 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001445 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001446 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001447 Converted.getFlatArguments(),
1448 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Douglas Gregor1275ae02009-07-28 23:00:59 +00001450 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001451 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001452 // In the future, we need to teach getTemplateSpecializationType to only
1453 // build the canonical type and return that to us.
1454 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001455
1456 // This might work out to be a current instantiation, in which
1457 // case the canonical type needs to be the InjectedClassNameType.
1458 //
1459 // TODO: in theory this could be a simple hashtable lookup; most
1460 // changes to CurContext don't change the set of current
1461 // instantiations.
1462 if (isa<ClassTemplateDecl>(Template)) {
1463 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1464 // If we get out to a namespace, we're done.
1465 if (Ctx->isFileContext()) break;
1466
1467 // If this isn't a record, keep looking.
1468 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1469 if (!Record) continue;
1470
1471 // Look for one of the two cases with InjectedClassNameTypes
1472 // and check whether it's the same template.
1473 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1474 !Record->getDescribedClassTemplate())
1475 continue;
1476
1477 // Fetch the injected class name type and check whether its
1478 // injected type is equal to the type we just built.
1479 QualType ICNT = Context.getTypeDeclType(Record);
1480 QualType Injected = cast<InjectedClassNameType>(ICNT)
1481 ->getInjectedSpecializationType();
1482
1483 if (CanonType != Injected->getCanonicalTypeInternal())
1484 continue;
1485
1486 // If so, the canonical type of this TST is the injected
1487 // class name type of the record we just found.
1488 assert(ICNT.isCanonical());
1489 CanonType = ICNT;
1490 IsCurrentInstantiation = true;
1491 break;
1492 }
1493 }
Mike Stump1eb44332009-09-09 15:08:12 +00001494 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001495 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001496 // Find the class template specialization declaration that
1497 // corresponds to these arguments.
1498 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001499 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001500 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001501 Converted.flatSize(),
1502 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001503 void *InsertPos = 0;
1504 ClassTemplateSpecializationDecl *Decl
1505 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1506 if (!Decl) {
1507 // This is the first time we have referenced this class template
1508 // specialization. Create the canonical declaration and add it to
1509 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001510 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00001511 ClassTemplate->getTemplatedDecl()->getTagKind(),
1512 ClassTemplate->getDeclContext(),
1513 ClassTemplate->getLocation(),
1514 ClassTemplate,
1515 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001516 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1517 Decl->setLexicalDeclContext(CurContext);
1518 }
1519
1520 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001521 assert(isa<RecordType>(CanonType) &&
1522 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001523 }
Mike Stump1eb44332009-09-09 15:08:12 +00001524
Douglas Gregor40808ce2009-03-09 23:48:35 +00001525 // Build the fully-sugared type for this class template
1526 // specialization, which refers back to the class template
1527 // specialization we created or found.
John McCall31f17ec2010-04-27 00:57:59 +00001528 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType,
1529 IsCurrentInstantiation);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001530}
1531
Douglas Gregorcc636682009-02-17 23:15:12 +00001532Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001533Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001534 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001535 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001536 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001537 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001538
Douglas Gregor40808ce2009-03-09 23:48:35 +00001539 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001540 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001541 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001542
John McCalld5532b62009-11-23 01:53:49 +00001543 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001544 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001545
1546 if (Result.isNull())
1547 return true;
1548
John McCalla93c9342009-12-07 02:54:59 +00001549 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001550 TemplateSpecializationTypeLoc TL
1551 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1552 TL.setTemplateNameLoc(TemplateLoc);
1553 TL.setLAngleLoc(LAngleLoc);
1554 TL.setRAngleLoc(RAngleLoc);
1555 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1556 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1557
1558 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCall6b2becf2009-09-08 17:47:29 +00001559}
John McCallf1bbbb42009-09-04 01:14:41 +00001560
John McCall6b2becf2009-09-08 17:47:29 +00001561Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1562 TagUseKind TUK,
1563 DeclSpec::TST TagSpec,
1564 SourceLocation TagLoc) {
1565 if (TypeResult.isInvalid())
1566 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001567
John McCall833ca992009-10-29 08:12:44 +00001568 // FIXME: preserve source info, ideally without copying the DI.
John McCalla93c9342009-12-07 02:54:59 +00001569 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001570 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001571
John McCall6b2becf2009-09-08 17:47:29 +00001572 // Verify the tag specifier.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001573 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001574
John McCall6b2becf2009-09-08 17:47:29 +00001575 if (const RecordType *RT = Type->getAs<RecordType>()) {
1576 RecordDecl *D = RT->getDecl();
1577
1578 IdentifierInfo *Id = D->getIdentifier();
1579 assert(Id && "templated class must have an identifier");
1580
1581 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1582 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001583 << Type
Douglas Gregor849b2432010-03-31 17:46:05 +00001584 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001585 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001586 }
1587 }
1588
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001589 ElaboratedTypeKeyword Keyword
1590 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1591 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCall6b2becf2009-09-08 17:47:29 +00001592
1593 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001594}
1595
John McCallf7a1a742009-11-24 19:00:30 +00001596Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1597 LookupResult &R,
1598 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001599 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001600 // FIXME: Can we do any checking at this point? I guess we could check the
1601 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001602 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001603 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001604
1605 // These should be filtered out by our callers.
1606 assert(!R.empty() && "empty lookup results when building templateid");
1607 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1608
1609 NestedNameSpecifier *Qualifier = 0;
1610 SourceRange QualifierRange;
1611 if (SS.isSet()) {
1612 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1613 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001614 }
John McCallc373d482010-01-27 01:50:18 +00001615
1616 // We don't want lookup warnings at this point.
1617 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001618
John McCallf7a1a742009-11-24 19:00:30 +00001619 bool Dependent
1620 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1621 &TemplateArgs);
1622 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001623 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001624 Qualifier, QualifierRange,
1625 R.getLookupName(), R.getNameLoc(),
1626 RequiresADL, TemplateArgs);
John McCallc373d482010-01-27 01:50:18 +00001627 ULE->addDecls(R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001628
1629 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001630}
1631
John McCallf7a1a742009-11-24 19:00:30 +00001632// We actually only call this from template instantiation.
1633Sema::OwningExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001634Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001635 DeclarationName Name,
1636 SourceLocation NameLoc,
1637 const TemplateArgumentListInfo &TemplateArgs) {
1638 DeclContext *DC;
1639 if (!(DC = computeDeclContext(SS, false)) ||
1640 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00001641 RequireCompleteDeclContext(SS, DC))
John McCallf7a1a742009-11-24 19:00:30 +00001642 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001643
John McCallf7a1a742009-11-24 19:00:30 +00001644 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1645 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00001646
John McCallf7a1a742009-11-24 19:00:30 +00001647 if (R.isAmbiguous())
1648 return ExprError();
1649
1650 if (R.empty()) {
1651 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1652 << Name << SS.getRange();
1653 return ExprError();
1654 }
1655
1656 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1657 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1658 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1659 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1660 return ExprError();
1661 }
1662
1663 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001664}
1665
Douglas Gregorc45c2322009-03-31 00:43:58 +00001666/// \brief Form a dependent template name.
1667///
1668/// This action forms a dependent template name given the template
1669/// name and its (presumably dependent) scope specifier. For
1670/// example, given "MetaFun::template apply", the scope specifier \p
1671/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1672/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump1eb44332009-09-09 15:08:12 +00001673Sema::TemplateTy
Douglas Gregorc45c2322009-03-31 00:43:58 +00001674Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001675 CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +00001676 UnqualifiedId &Name,
Douglas Gregora481edb2009-11-20 23:39:24 +00001677 TypeTy *ObjectType,
1678 bool EnteringContext) {
Douglas Gregor0707bc52010-01-19 16:01:07 +00001679 DeclContext *LookupCtx = 0;
1680 if (SS.isSet())
1681 LookupCtx = computeDeclContext(SS, EnteringContext);
1682 if (!LookupCtx && ObjectType)
1683 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1684 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001685 // C++0x [temp.names]p5:
1686 // If a name prefixed by the keyword template is not the name of
1687 // a template, the program is ill-formed. [Note: the keyword
1688 // template may not be applied to non-template members of class
1689 // templates. -end note ] [ Note: as is the case with the
1690 // typename prefix, the template prefix is allowed in cases
1691 // where it is not strictly necessary; i.e., when the
1692 // nested-name-specifier or the expression on the left of the ->
1693 // or . is not dependent on a template-parameter, or the use
1694 // does not appear in the scope of a template. -end note]
1695 //
1696 // Note: C++03 was more strict here, because it banned the use of
1697 // the "template" keyword prior to a template-name that was not a
1698 // dependent name. C++ DR468 relaxed this requirement (the
1699 // "template" keyword is now permitted). We follow the C++0x
1700 // rules, even in C++03 mode, retroactively applying the DR.
1701 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001702 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregora481edb2009-11-20 23:39:24 +00001703 EnteringContext, Template);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001704 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1705 isa<CXXRecordDecl>(LookupCtx) &&
1706 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001707 // This is a dependent template.
1708 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001709 Diag(Name.getSourceRange().getBegin(),
1710 diag::err_template_kw_refers_to_non_template)
1711 << GetNameFromUnqualifiedId(Name)
Douglas Gregor0278e122010-05-05 05:58:24 +00001712 << Name.getSourceRange()
1713 << TemplateKWLoc;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001714 return TemplateTy();
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001715 } else {
1716 // We found something; return it.
1717 return Template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001718 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001719 }
1720
Mike Stump1eb44332009-09-09 15:08:12 +00001721 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001722 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001723
1724 switch (Name.getKind()) {
1725 case UnqualifiedId::IK_Identifier:
1726 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1727 Name.Identifier));
1728
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001729 case UnqualifiedId::IK_OperatorFunctionId:
1730 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1731 Name.OperatorFunctionId.Operator));
Sean Hunte6252d12009-11-28 08:58:14 +00001732
1733 case UnqualifiedId::IK_LiteralOperatorId:
1734 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1735
Douglas Gregor014e88d2009-11-03 23:16:33 +00001736 default:
1737 break;
1738 }
1739
1740 Diag(Name.getSourceRange().getBegin(),
1741 diag::err_template_kw_refers_to_non_template)
1742 << GetNameFromUnqualifiedId(Name)
Douglas Gregor0278e122010-05-05 05:58:24 +00001743 << Name.getSourceRange()
1744 << TemplateKWLoc;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001745 return TemplateTy();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001746}
1747
Mike Stump1eb44332009-09-09 15:08:12 +00001748bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001749 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001750 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001751 const TemplateArgument &Arg = AL.getArgument();
1752
Anders Carlsson436b1562009-06-13 00:33:33 +00001753 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001754 switch(Arg.getKind()) {
1755 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00001756 // C++ [temp.arg.type]p1:
1757 // A template-argument for a template-parameter which is a
1758 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001759 break;
1760 case TemplateArgument::Template: {
1761 // We have a template type parameter but the template argument
1762 // is a template without any arguments.
1763 SourceRange SR = AL.getSourceRange();
1764 TemplateName Name = Arg.getAsTemplate();
1765 Diag(SR.getBegin(), diag::err_template_missing_args)
1766 << Name << SR;
1767 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1768 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00001769
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001770 return true;
1771 }
1772 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00001773 // We have a template type parameter but the template argument
1774 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001775 SourceRange SR = AL.getSourceRange();
1776 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001777 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Anders Carlsson436b1562009-06-13 00:33:33 +00001779 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001780 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001781 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001782
John McCalla93c9342009-12-07 02:54:59 +00001783 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001784 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Anders Carlsson436b1562009-06-13 00:33:33 +00001786 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001787 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001788 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001789 return false;
1790}
1791
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001792/// \brief Substitute template arguments into the default template argument for
1793/// the given template type parameter.
1794///
1795/// \param SemaRef the semantic analysis object for which we are performing
1796/// the substitution.
1797///
1798/// \param Template the template that we are synthesizing template arguments
1799/// for.
1800///
1801/// \param TemplateLoc the location of the template name that started the
1802/// template-id we are checking.
1803///
1804/// \param RAngleLoc the location of the right angle bracket ('>') that
1805/// terminates the template-id.
1806///
1807/// \param Param the template template parameter whose default we are
1808/// substituting into.
1809///
1810/// \param Converted the list of template arguments provided for template
1811/// parameters that precede \p Param in the template parameter list.
1812///
1813/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001814static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001815SubstDefaultTemplateArgument(Sema &SemaRef,
1816 TemplateDecl *Template,
1817 SourceLocation TemplateLoc,
1818 SourceLocation RAngleLoc,
1819 TemplateTypeParmDecl *Param,
1820 TemplateArgumentListBuilder &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001821 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001822
1823 // If the argument type is dependent, instantiate it now based
1824 // on the previously-computed template arguments.
1825 if (ArgType->getType()->isDependentType()) {
1826 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1827 /*TakeArgs=*/false);
1828
1829 MultiLevelTemplateArgumentList AllTemplateArgs
1830 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1831
1832 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1833 Template, Converted.getFlatArguments(),
1834 Converted.flatSize(),
1835 SourceRange(TemplateLoc, RAngleLoc));
1836
1837 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1838 Param->getDefaultArgumentLoc(),
1839 Param->getDeclName());
1840 }
1841
1842 return ArgType;
1843}
1844
1845/// \brief Substitute template arguments into the default template argument for
1846/// the given non-type template parameter.
1847///
1848/// \param SemaRef the semantic analysis object for which we are performing
1849/// the substitution.
1850///
1851/// \param Template the template that we are synthesizing template arguments
1852/// for.
1853///
1854/// \param TemplateLoc the location of the template name that started the
1855/// template-id we are checking.
1856///
1857/// \param RAngleLoc the location of the right angle bracket ('>') that
1858/// terminates the template-id.
1859///
Douglas Gregor788cd062009-11-11 01:00:40 +00001860/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001861/// substituting into.
1862///
1863/// \param Converted the list of template arguments provided for template
1864/// parameters that precede \p Param in the template parameter list.
1865///
1866/// \returns the substituted template argument, or NULL if an error occurred.
1867static Sema::OwningExprResult
1868SubstDefaultTemplateArgument(Sema &SemaRef,
1869 TemplateDecl *Template,
1870 SourceLocation TemplateLoc,
1871 SourceLocation RAngleLoc,
1872 NonTypeTemplateParmDecl *Param,
1873 TemplateArgumentListBuilder &Converted) {
1874 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1875 /*TakeArgs=*/false);
1876
1877 MultiLevelTemplateArgumentList AllTemplateArgs
1878 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1879
1880 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1881 Template, Converted.getFlatArguments(),
1882 Converted.flatSize(),
1883 SourceRange(TemplateLoc, RAngleLoc));
1884
1885 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1886}
1887
Douglas Gregor788cd062009-11-11 01:00:40 +00001888/// \brief Substitute template arguments into the default template argument for
1889/// the given template template parameter.
1890///
1891/// \param SemaRef the semantic analysis object for which we are performing
1892/// the substitution.
1893///
1894/// \param Template the template that we are synthesizing template arguments
1895/// for.
1896///
1897/// \param TemplateLoc the location of the template name that started the
1898/// template-id we are checking.
1899///
1900/// \param RAngleLoc the location of the right angle bracket ('>') that
1901/// terminates the template-id.
1902///
1903/// \param Param the template template parameter whose default we are
1904/// substituting into.
1905///
1906/// \param Converted the list of template arguments provided for template
1907/// parameters that precede \p Param in the template parameter list.
1908///
1909/// \returns the substituted template argument, or NULL if an error occurred.
1910static TemplateName
1911SubstDefaultTemplateArgument(Sema &SemaRef,
1912 TemplateDecl *Template,
1913 SourceLocation TemplateLoc,
1914 SourceLocation RAngleLoc,
1915 TemplateTemplateParmDecl *Param,
1916 TemplateArgumentListBuilder &Converted) {
1917 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1918 /*TakeArgs=*/false);
1919
1920 MultiLevelTemplateArgumentList AllTemplateArgs
1921 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1922
1923 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1924 Template, Converted.getFlatArguments(),
1925 Converted.flatSize(),
1926 SourceRange(TemplateLoc, RAngleLoc));
1927
1928 return SemaRef.SubstTemplateName(
1929 Param->getDefaultArgument().getArgument().getAsTemplate(),
1930 Param->getDefaultArgument().getTemplateNameLoc(),
1931 AllTemplateArgs);
1932}
1933
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001934/// \brief If the given template parameter has a default template
1935/// argument, substitute into that default template argument and
1936/// return the corresponding template argument.
1937TemplateArgumentLoc
1938Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1939 SourceLocation TemplateLoc,
1940 SourceLocation RAngleLoc,
1941 Decl *Param,
1942 TemplateArgumentListBuilder &Converted) {
1943 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1944 if (!TypeParm->hasDefaultArgument())
1945 return TemplateArgumentLoc();
1946
John McCalla93c9342009-12-07 02:54:59 +00001947 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001948 TemplateLoc,
1949 RAngleLoc,
1950 TypeParm,
1951 Converted);
1952 if (DI)
1953 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1954
1955 return TemplateArgumentLoc();
1956 }
1957
1958 if (NonTypeTemplateParmDecl *NonTypeParm
1959 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1960 if (!NonTypeParm->hasDefaultArgument())
1961 return TemplateArgumentLoc();
1962
1963 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1964 TemplateLoc,
1965 RAngleLoc,
1966 NonTypeParm,
1967 Converted);
1968 if (Arg.isInvalid())
1969 return TemplateArgumentLoc();
1970
1971 Expr *ArgE = Arg.takeAs<Expr>();
1972 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1973 }
1974
1975 TemplateTemplateParmDecl *TempTempParm
1976 = cast<TemplateTemplateParmDecl>(Param);
1977 if (!TempTempParm->hasDefaultArgument())
1978 return TemplateArgumentLoc();
1979
1980 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1981 TemplateLoc,
1982 RAngleLoc,
1983 TempTempParm,
1984 Converted);
1985 if (TName.isNull())
1986 return TemplateArgumentLoc();
1987
1988 return TemplateArgumentLoc(TemplateArgument(TName),
1989 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1990 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1991}
1992
Douglas Gregore7526412009-11-11 19:31:23 +00001993/// \brief Check that the given template argument corresponds to the given
1994/// template parameter.
1995bool Sema::CheckTemplateArgument(NamedDecl *Param,
1996 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00001997 TemplateDecl *Template,
1998 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00001999 SourceLocation RAngleLoc,
Douglas Gregor02024a92010-03-28 02:42:43 +00002000 TemplateArgumentListBuilder &Converted,
2001 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002002 // Check template type parameters.
2003 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002004 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00002005
Douglas Gregord9e15302009-11-11 19:41:09 +00002006 // Check non-type template parameters.
2007 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002008 // Do substitution on the type of the non-type template parameter
2009 // with the template arguments we've seen thus far.
2010 QualType NTTPType = NTTP->getType();
2011 if (NTTPType->isDependentType()) {
2012 // Do substitution on the type of the non-type template parameter.
2013 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2014 NTTP, Converted.getFlatArguments(),
2015 Converted.flatSize(),
2016 SourceRange(TemplateLoc, RAngleLoc));
2017
2018 TemplateArgumentList TemplateArgs(Context, Converted,
2019 /*TakeArgs=*/false);
2020 NTTPType = SubstType(NTTPType,
2021 MultiLevelTemplateArgumentList(TemplateArgs),
2022 NTTP->getLocation(),
2023 NTTP->getDeclName());
2024 // If that worked, check the non-type template parameter type
2025 // for validity.
2026 if (!NTTPType.isNull())
2027 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2028 NTTP->getLocation());
2029 if (NTTPType.isNull())
2030 return true;
2031 }
2032
2033 switch (Arg.getArgument().getKind()) {
2034 case TemplateArgument::Null:
2035 assert(false && "Should never see a NULL template argument here");
2036 return true;
2037
2038 case TemplateArgument::Expression: {
2039 Expr *E = Arg.getArgument().getAsExpr();
2040 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002041 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00002042 return true;
2043
2044 Converted.Append(Result);
2045 break;
2046 }
2047
2048 case TemplateArgument::Declaration:
2049 case TemplateArgument::Integral:
2050 // We've already checked this template argument, so just copy
2051 // it to the list of converted arguments.
2052 Converted.Append(Arg.getArgument());
2053 break;
2054
2055 case TemplateArgument::Template:
2056 // We were given a template template argument. It may not be ill-formed;
2057 // see below.
2058 if (DependentTemplateName *DTN
2059 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2060 // We have a template argument such as \c T::template X, which we
2061 // parsed as a template template argument. However, since we now
2062 // know that we need a non-type template argument, convert this
2063 // template name into an expression.
John McCallf7a1a742009-11-24 19:00:30 +00002064 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2065 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002066 Arg.getTemplateQualifierRange(),
John McCallf7a1a742009-11-24 19:00:30 +00002067 DTN->getIdentifier(),
2068 Arg.getTemplateNameLoc());
Douglas Gregore7526412009-11-11 19:31:23 +00002069
2070 TemplateArgument Result;
2071 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2072 return true;
2073
2074 Converted.Append(Result);
2075 break;
2076 }
2077
2078 // We have a template argument that actually does refer to a class
2079 // template, template alias, or template template parameter, and
2080 // therefore cannot be a non-type template argument.
2081 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2082 << Arg.getSourceRange();
2083
2084 Diag(Param->getLocation(), diag::note_template_param_here);
2085 return true;
2086
2087 case TemplateArgument::Type: {
2088 // We have a non-type template parameter but the template
2089 // argument is a type.
2090
2091 // C++ [temp.arg]p2:
2092 // In a template-argument, an ambiguity between a type-id and
2093 // an expression is resolved to a type-id, regardless of the
2094 // form of the corresponding template-parameter.
2095 //
2096 // We warn specifically about this case, since it can be rather
2097 // confusing for users.
2098 QualType T = Arg.getArgument().getAsType();
2099 SourceRange SR = Arg.getSourceRange();
2100 if (T->isFunctionType())
2101 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2102 else
2103 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2104 Diag(Param->getLocation(), diag::note_template_param_here);
2105 return true;
2106 }
2107
2108 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002109 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002110 break;
2111 }
2112
2113 return false;
2114 }
2115
2116
2117 // Check template template parameters.
2118 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2119
2120 // Substitute into the template parameter list of the template
2121 // template parameter, since previously-supplied template arguments
2122 // may appear within the template template parameter.
2123 {
2124 // Set up a template instantiation context.
2125 LocalInstantiationScope Scope(*this);
2126 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2127 TempParm, Converted.getFlatArguments(),
2128 Converted.flatSize(),
2129 SourceRange(TemplateLoc, RAngleLoc));
2130
2131 TemplateArgumentList TemplateArgs(Context, Converted,
2132 /*TakeArgs=*/false);
2133 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2134 SubstDecl(TempParm, CurContext,
2135 MultiLevelTemplateArgumentList(TemplateArgs)));
2136 if (!TempParm)
2137 return true;
2138
2139 // FIXME: TempParam is leaked.
2140 }
2141
2142 switch (Arg.getArgument().getKind()) {
2143 case TemplateArgument::Null:
2144 assert(false && "Should never see a NULL template argument here");
2145 return true;
2146
2147 case TemplateArgument::Template:
2148 if (CheckTemplateArgument(TempParm, Arg))
2149 return true;
2150
2151 Converted.Append(Arg.getArgument());
2152 break;
2153
2154 case TemplateArgument::Expression:
2155 case TemplateArgument::Type:
2156 // We have a template template parameter but the template
2157 // argument does not refer to a template.
2158 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2159 return true;
2160
2161 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002162 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002163 "Declaration argument with template template parameter");
2164 break;
2165 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002166 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002167 "Integral argument with template template parameter");
2168 break;
2169
2170 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002171 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002172 break;
2173 }
2174
2175 return false;
2176}
2177
Douglas Gregorc15cb382009-02-09 23:23:08 +00002178/// \brief Check that the given template argument list is well-formed
2179/// for specializing the given template.
2180bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2181 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002182 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002183 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002184 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002185 TemplateParameterList *Params = Template->getTemplateParameters();
2186 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002187 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002188 bool Invalid = false;
2189
John McCalld5532b62009-11-23 01:53:49 +00002190 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2191
Mike Stump1eb44332009-09-09 15:08:12 +00002192 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002193 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002195 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002196 (NumArgs < Params->getMinRequiredArguments() &&
2197 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002198 // FIXME: point at either the first arg beyond what we can handle,
2199 // or the '>', depending on whether we have too many or too few
2200 // arguments.
2201 SourceRange Range;
2202 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002203 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002204 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2205 << (NumArgs > NumParams)
2206 << (isa<ClassTemplateDecl>(Template)? 0 :
2207 isa<FunctionTemplateDecl>(Template)? 1 :
2208 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2209 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002210 Diag(Template->getLocation(), diag::note_template_decl_here)
2211 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002212 Invalid = true;
2213 }
Mike Stump1eb44332009-09-09 15:08:12 +00002214
2215 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002216 // [...] The type and form of each template-argument specified in
2217 // a template-id shall match the type and form specified for the
2218 // corresponding parameter declared by the template in its
2219 // template-parameter-list.
2220 unsigned ArgIdx = 0;
2221 for (TemplateParameterList::iterator Param = Params->begin(),
2222 ParamEnd = Params->end();
2223 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002224 if (ArgIdx > NumArgs && PartialTemplateArgs)
2225 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002226
Douglas Gregord9e15302009-11-11 19:41:09 +00002227 // If we have a template parameter pack, check every remaining template
2228 // argument against that template parameter pack.
2229 if ((*Param)->isTemplateParameterPack()) {
2230 Converted.BeginPack();
2231 for (; ArgIdx < NumArgs; ++ArgIdx) {
2232 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2233 TemplateLoc, RAngleLoc, Converted)) {
2234 Invalid = true;
2235 break;
2236 }
2237 }
2238 Converted.EndPack();
2239 continue;
2240 }
2241
Douglas Gregorf35f8282009-11-11 21:54:23 +00002242 if (ArgIdx < NumArgs) {
2243 // Check the template argument we were given.
2244 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2245 TemplateLoc, RAngleLoc, Converted))
2246 return true;
2247
2248 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002249 }
Douglas Gregore7526412009-11-11 19:31:23 +00002250
Douglas Gregorf35f8282009-11-11 21:54:23 +00002251 // We have a default template argument that we will use.
2252 TemplateArgumentLoc Arg;
2253
2254 // Retrieve the default template argument from the template
2255 // parameter. For each kind of template parameter, we substitute the
2256 // template arguments provided thus far and any "outer" template arguments
2257 // (when the template parameter was part of a nested template) into
2258 // the default argument.
2259 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2260 if (!TTP->hasDefaultArgument()) {
2261 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2262 break;
2263 }
2264
John McCalla93c9342009-12-07 02:54:59 +00002265 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002266 Template,
2267 TemplateLoc,
2268 RAngleLoc,
2269 TTP,
2270 Converted);
2271 if (!ArgType)
2272 return true;
2273
2274 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2275 ArgType);
2276 } else if (NonTypeTemplateParmDecl *NTTP
2277 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2278 if (!NTTP->hasDefaultArgument()) {
2279 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2280 break;
2281 }
2282
2283 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2284 TemplateLoc,
2285 RAngleLoc,
2286 NTTP,
2287 Converted);
2288 if (E.isInvalid())
2289 return true;
2290
2291 Expr *Ex = E.takeAs<Expr>();
2292 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2293 } else {
2294 TemplateTemplateParmDecl *TempParm
2295 = cast<TemplateTemplateParmDecl>(*Param);
2296
2297 if (!TempParm->hasDefaultArgument()) {
2298 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2299 break;
2300 }
2301
2302 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2303 TemplateLoc,
2304 RAngleLoc,
2305 TempParm,
2306 Converted);
2307 if (Name.isNull())
2308 return true;
2309
2310 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2311 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2312 TempParm->getDefaultArgument().getTemplateNameLoc());
2313 }
2314
2315 // Introduce an instantiation record that describes where we are using
2316 // the default template argument.
2317 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2318 Converted.getFlatArguments(),
2319 Converted.flatSize(),
2320 SourceRange(TemplateLoc, RAngleLoc));
2321
2322 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002323 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002324 RAngleLoc, Converted))
2325 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002326 }
2327
2328 return Invalid;
2329}
2330
2331/// \brief Check a template argument against its corresponding
2332/// template type parameter.
2333///
2334/// This routine implements the semantics of C++ [temp.arg.type]. It
2335/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002336bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002337 TypeSourceInfo *ArgInfo) {
2338 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002339 QualType Arg = ArgInfo->getType();
2340
Douglas Gregorc15cb382009-02-09 23:23:08 +00002341 // C++ [temp.arg.type]p2:
2342 // A local type, a type with no linkage, an unnamed type or a type
2343 // compounded from any of these types shall not be used as a
2344 // template-argument for a template type-parameter.
2345 //
2346 // FIXME: Perform the recursive and no-linkage type checks.
2347 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00002348 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002349 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00002350 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002351 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00002352 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002353 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall833ca992009-10-29 08:12:44 +00002354 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2355 << QualType(Tag, 0) << SR;
2356 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00002357 !Tag->getDecl()->getTypedefForAnonDecl()) {
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002358 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall833ca992009-10-29 08:12:44 +00002359 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002360 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2361 return true;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002362 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002363 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregor4b52e252009-12-21 23:17:24 +00002364 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002365 }
2366
2367 return false;
2368}
2369
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002370/// \brief Checks whether the given template argument is the address
2371/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002372static bool
2373CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2374 NonTypeTemplateParmDecl *Param,
2375 QualType ParamType,
2376 Expr *ArgIn,
2377 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002378 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002379 Expr *Arg = ArgIn;
2380 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002381
2382 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002383 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002384 Arg = Cast->getSubExpr();
2385
2386 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002387 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002388 // A template-argument for a non-type, non-template
2389 // template-parameter shall be one of: [...]
2390 //
2391 // -- the address of an object or function with external
2392 // linkage, including function templates and function
2393 // template-ids but excluding non-static class members,
2394 // expressed as & id-expression where the & is optional if
2395 // the name refers to a function or array, or if the
2396 // corresponding template-parameter is a reference; or
2397 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002398
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002399 // Ignore (and complain about) any excess parentheses.
2400 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2401 if (!Invalid) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002402 S.Diag(Arg->getSourceRange().getBegin(),
2403 diag::err_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002404 << Arg->getSourceRange();
2405 Invalid = true;
2406 }
2407
2408 Arg = Parens->getSubExpr();
2409 }
2410
Douglas Gregorb7a09262010-04-01 18:32:35 +00002411 bool AddressTaken = false;
2412 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002413 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002414 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002415 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb7a09262010-04-01 18:32:35 +00002416 AddressTaken = true;
2417 AddrOpLoc = UnOp->getOperatorLoc();
2418 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002419 } else
2420 DRE = dyn_cast<DeclRefExpr>(Arg);
2421
Douglas Gregorb7a09262010-04-01 18:32:35 +00002422 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002423 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2424 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002425 S.Diag(Param->getLocation(), diag::note_template_param_here);
2426 return true;
2427 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002428
2429 // Stop checking the precise nature of the argument if it is value dependent,
2430 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002431 if (Arg->isValueDependent()) {
2432 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth038cc392010-01-31 10:01:20 +00002433 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002434 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002435
Douglas Gregorb7a09262010-04-01 18:32:35 +00002436 if (!isa<ValueDecl>(DRE->getDecl())) {
2437 S.Diag(Arg->getSourceRange().getBegin(),
2438 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002439 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002440 S.Diag(Param->getLocation(), diag::note_template_param_here);
2441 return true;
2442 }
2443
2444 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002445
2446 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00002447 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2448 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002449 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002450 S.Diag(Param->getLocation(), diag::note_template_param_here);
2451 return true;
2452 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002453
2454 // Cannot refer to non-static member functions
2455 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00002456 if (!Method->isStatic()) {
2457 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002458 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002459 S.Diag(Param->getLocation(), diag::note_template_param_here);
2460 return true;
2461 }
Mike Stump1eb44332009-09-09 15:08:12 +00002462
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002463 // Functions must have external linkage.
2464 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002465 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002466 S.Diag(Arg->getSourceRange().getBegin(),
2467 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002468 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002469 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002470 << true;
2471 return true;
2472 }
2473
2474 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002475 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002476
Douglas Gregorb7a09262010-04-01 18:32:35 +00002477 // If the template parameter has pointer type, the function decays.
2478 if (ParamType->isPointerType() && !AddressTaken)
2479 ArgType = S.Context.getPointerType(Func->getType());
2480 else if (AddressTaken && ParamType->isReferenceType()) {
2481 // If we originally had an address-of operator, but the
2482 // parameter has reference type, complain and (if things look
2483 // like they will work) drop the address-of operator.
2484 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2485 ParamType.getNonReferenceType())) {
2486 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2487 << ParamType;
2488 S.Diag(Param->getLocation(), diag::note_template_param_here);
2489 return true;
2490 }
2491
2492 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2493 << ParamType
2494 << FixItHint::CreateRemoval(AddrOpLoc);
2495 S.Diag(Param->getLocation(), diag::note_template_param_here);
2496
2497 ArgType = Func->getType();
2498 }
2499 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002500 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002501 S.Diag(Arg->getSourceRange().getBegin(),
2502 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002503 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002504 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002505 << true;
2506 return true;
2507 }
2508
Douglas Gregorb7a09262010-04-01 18:32:35 +00002509 // A value of reference type is not an object.
2510 if (Var->getType()->isReferenceType()) {
2511 S.Diag(Arg->getSourceRange().getBegin(),
2512 diag::err_template_arg_reference_var)
2513 << Var->getType() << Arg->getSourceRange();
2514 S.Diag(Param->getLocation(), diag::note_template_param_here);
2515 return true;
2516 }
2517
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002518 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002519 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002520
2521 // If the template parameter has pointer type, we must have taken
2522 // the address of this object.
2523 if (ParamType->isReferenceType()) {
2524 if (AddressTaken) {
2525 // If we originally had an address-of operator, but the
2526 // parameter has reference type, complain and (if things look
2527 // like they will work) drop the address-of operator.
2528 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2529 ParamType.getNonReferenceType())) {
2530 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2531 << ParamType;
2532 S.Diag(Param->getLocation(), diag::note_template_param_here);
2533 return true;
2534 }
2535
2536 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2537 << ParamType
2538 << FixItHint::CreateRemoval(AddrOpLoc);
2539 S.Diag(Param->getLocation(), diag::note_template_param_here);
2540
2541 ArgType = Var->getType();
2542 }
2543 } else if (!AddressTaken && ParamType->isPointerType()) {
2544 if (Var->getType()->isArrayType()) {
2545 // Array-to-pointer decay.
2546 ArgType = S.Context.getArrayDecayedType(Var->getType());
2547 } else {
2548 // If the template parameter has pointer type but the address of
2549 // this object was not taken, complain and (possibly) recover by
2550 // taking the address of the entity.
2551 ArgType = S.Context.getPointerType(Var->getType());
2552 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2553 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2554 << ParamType;
2555 S.Diag(Param->getLocation(), diag::note_template_param_here);
2556 return true;
2557 }
2558
2559 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2560 << ParamType
2561 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2562
2563 S.Diag(Param->getLocation(), diag::note_template_param_here);
2564 }
2565 }
2566 } else {
2567 // We found something else, but we don't know specifically what it is.
2568 S.Diag(Arg->getSourceRange().getBegin(),
2569 diag::err_template_arg_not_object_or_func)
2570 << Arg->getSourceRange();
2571 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2572 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002573 }
Mike Stump1eb44332009-09-09 15:08:12 +00002574
Douglas Gregorb7a09262010-04-01 18:32:35 +00002575 if (ParamType->isPointerType() &&
2576 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2577 S.IsQualificationConversion(ArgType, ParamType)) {
2578 // For pointer-to-object types, qualification conversions are
2579 // permitted.
2580 } else {
2581 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2582 if (!ParamRef->getPointeeType()->isFunctionType()) {
2583 // C++ [temp.arg.nontype]p5b3:
2584 // For a non-type template-parameter of type reference to
2585 // object, no conversions apply. The type referred to by the
2586 // reference may be more cv-qualified than the (otherwise
2587 // identical) type of the template- argument. The
2588 // template-parameter is bound directly to the
2589 // template-argument, which shall be an lvalue.
2590
2591 // FIXME: Other qualifiers?
2592 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2593 unsigned ArgQuals = ArgType.getCVRQualifiers();
2594
2595 if ((ParamQuals | ArgQuals) != ParamQuals) {
2596 S.Diag(Arg->getSourceRange().getBegin(),
2597 diag::err_template_arg_ref_bind_ignores_quals)
2598 << ParamType << Arg->getType()
2599 << Arg->getSourceRange();
2600 S.Diag(Param->getLocation(), diag::note_template_param_here);
2601 return true;
2602 }
2603 }
2604 }
2605
2606 // At this point, the template argument refers to an object or
2607 // function with external linkage. We now need to check whether the
2608 // argument and parameter types are compatible.
2609 if (!S.Context.hasSameUnqualifiedType(ArgType,
2610 ParamType.getNonReferenceType())) {
2611 // We can't perform this conversion or binding.
2612 if (ParamType->isReferenceType())
2613 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2614 << ParamType << Arg->getType() << Arg->getSourceRange();
2615 else
2616 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2617 << Arg->getType() << ParamType << Arg->getSourceRange();
2618 S.Diag(Param->getLocation(), diag::note_template_param_here);
2619 return true;
2620 }
2621 }
2622
2623 // Create the template argument.
2624 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor77c13e02010-04-24 18:20:53 +00002625 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00002626 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002627}
2628
2629/// \brief Checks whether the given template argument is a pointer to
2630/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002631bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2632 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002633 bool Invalid = false;
2634
2635 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002636 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002637 Arg = Cast->getSubExpr();
2638
2639 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002640 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002641 // A template-argument for a non-type, non-template
2642 // template-parameter shall be one of: [...]
2643 //
2644 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002645 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002646
2647 // Ignore (and complain about) any excess parentheses.
2648 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2649 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002650 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002651 diag::err_template_arg_extra_parens)
2652 << Arg->getSourceRange();
2653 Invalid = true;
2654 }
2655
2656 Arg = Parens->getSubExpr();
2657 }
2658
Douglas Gregorcaddba02009-11-12 18:38:13 +00002659 // A pointer-to-member constant written &Class::member.
2660 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002661 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2662 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2663 if (DRE && !DRE->getQualifier())
2664 DRE = 0;
2665 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002666 }
2667 // A constant of pointer-to-member type.
2668 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2669 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2670 if (VD->getType()->isMemberPointerType()) {
2671 if (isa<NonTypeTemplateParmDecl>(VD) ||
2672 (isa<VarDecl>(VD) &&
2673 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2674 if (Arg->isTypeDependent() || Arg->isValueDependent())
2675 Converted = TemplateArgument(Arg->Retain());
2676 else
2677 Converted = TemplateArgument(VD->getCanonicalDecl());
2678 return Invalid;
2679 }
2680 }
2681 }
2682
2683 DRE = 0;
2684 }
2685
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002686 if (!DRE)
2687 return Diag(Arg->getSourceRange().getBegin(),
2688 diag::err_template_arg_not_pointer_to_member_form)
2689 << Arg->getSourceRange();
2690
2691 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2692 assert((isa<FieldDecl>(DRE->getDecl()) ||
2693 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2694 "Only non-static member pointers can make it here");
2695
2696 // Okay: this is the address of a non-static member, and therefore
2697 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002698 if (Arg->isTypeDependent() || Arg->isValueDependent())
2699 Converted = TemplateArgument(Arg->Retain());
2700 else
2701 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002702 return Invalid;
2703 }
2704
2705 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002706 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002707 diag::err_template_arg_not_pointer_to_member_form)
2708 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002709 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002710 diag::note_template_arg_refers_here);
2711 return true;
2712}
2713
Douglas Gregorc15cb382009-02-09 23:23:08 +00002714/// \brief Check a template argument against its corresponding
2715/// non-type template parameter.
2716///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002717/// This routine implements the semantics of C++ [temp.arg.nontype].
2718/// It returns true if an error occurred, and false otherwise. \p
2719/// InstantiatedParamType is the type of the non-type template
2720/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002721///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002722/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002723bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002724 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00002725 TemplateArgument &Converted,
2726 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002727 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2728
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002729 // If either the parameter has a dependent type or the argument is
2730 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00002731 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2732 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002733 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002734 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002735 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002736
2737 // C++ [temp.arg.nontype]p5:
2738 // The following conversions are performed on each expression used
2739 // as a non-type template-argument. If a non-type
2740 // template-argument cannot be converted to the type of the
2741 // corresponding template-parameter then the program is
2742 // ill-formed.
2743 //
2744 // -- for a non-type template-parameter of integral or
2745 // enumeration type, integral promotions (4.5) and integral
2746 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002747 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002748 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002749 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002750 // C++ [temp.arg.nontype]p1:
2751 // A template-argument for a non-type, non-template
2752 // template-parameter shall be one of:
2753 //
2754 // -- an integral constant-expression of integral or enumeration
2755 // type; or
2756 // -- the name of a non-type template-parameter; or
2757 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002758 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002759 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002760 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002761 diag::err_template_arg_not_integral_or_enumeral)
2762 << ArgType << Arg->getSourceRange();
2763 Diag(Param->getLocation(), diag::note_template_param_here);
2764 return true;
2765 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002766 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002767 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2768 << ArgType << Arg->getSourceRange();
2769 return true;
2770 }
2771
Douglas Gregor02024a92010-03-28 02:42:43 +00002772 // From here on out, all we care about are the unqualified forms
2773 // of the parameter and argument types.
2774 ParamType = ParamType.getUnqualifiedType();
2775 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002776
2777 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002778 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002779 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00002780 } else if (CTAK == CTAK_Deduced) {
2781 // C++ [temp.deduct.type]p17:
2782 // If, in the declaration of a function template with a non-type
2783 // template-parameter, the non-type template- parameter is used
2784 // in an expression in the function parameter-list and, if the
2785 // corresponding template-argument is deduced, the
2786 // template-argument type shall match the type of the
2787 // template-parameter exactly, except that a template-argument
2788 // deduced from an array bound may be of any integral type.
2789 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2790 << ArgType << ParamType;
2791 Diag(Param->getLocation(), diag::note_template_param_here);
2792 return true;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002793 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2794 !ParamType->isEnumeralType()) {
2795 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002796 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002797 } else {
2798 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002799 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002800 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002801 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002802 Diag(Param->getLocation(), diag::note_template_param_here);
2803 return true;
2804 }
2805
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002806 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002807 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002808 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002809
2810 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002811 llvm::APSInt OldValue = Value;
2812
2813 // Coerce the template argument's value to the value it will have
2814 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002815 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002816 if (Value.getBitWidth() != AllowedBits)
2817 Value.extOrTrunc(AllowedBits);
2818 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002819
2820 // Complain if an unsigned parameter received a negative value.
2821 if (IntegerType->isUnsignedIntegerType()
2822 && (OldValue.isSigned() && OldValue.isNegative())) {
2823 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2824 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2825 << Arg->getSourceRange();
2826 Diag(Param->getLocation(), diag::note_template_param_here);
2827 }
2828
2829 // Complain if we overflowed the template parameter's type.
2830 unsigned RequiredBits;
2831 if (IntegerType->isUnsignedIntegerType())
2832 RequiredBits = OldValue.getActiveBits();
2833 else if (OldValue.isUnsigned())
2834 RequiredBits = OldValue.getActiveBits() + 1;
2835 else
2836 RequiredBits = OldValue.getMinSignedBits();
2837 if (RequiredBits > AllowedBits) {
2838 Diag(Arg->getSourceRange().getBegin(),
2839 diag::warn_template_arg_too_large)
2840 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2841 << Arg->getSourceRange();
2842 Diag(Param->getLocation(), diag::note_template_param_here);
2843 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002844 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002845
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002846 // Add the value of this argument to the list of converted
2847 // arguments. We use the bitwidth and signedness of the template
2848 // parameter.
2849 if (Arg->isValueDependent()) {
2850 // The argument is value-dependent. Create a new
2851 // TemplateArgument with the converted expression.
2852 Converted = TemplateArgument(Arg);
2853 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002854 }
2855
John McCall833ca992009-10-29 08:12:44 +00002856 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002857 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002858 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002859 return false;
2860 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002861
John McCall6bb80172010-03-30 21:47:33 +00002862 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2863
Douglas Gregorb7a09262010-04-01 18:32:35 +00002864 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2865 // from a template argument of type std::nullptr_t to a non-type
2866 // template parameter of type pointer to object, pointer to
2867 // function, or pointer-to-member, respectively.
2868 if (ArgType->isNullPtrType() &&
2869 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2870 Converted = TemplateArgument((NamedDecl *)0);
2871 return false;
2872 }
2873
Douglas Gregorb86b0572009-02-11 01:18:59 +00002874 // Handle pointer-to-function, reference-to-function, and
2875 // pointer-to-member-function all in (roughly) the same way.
2876 if (// -- For a non-type template-parameter of type pointer to
2877 // function, only the function-to-pointer conversion (4.3) is
2878 // applied. If the template-argument represents a set of
2879 // overloaded functions (or a pointer to such), the matching
2880 // function is selected from the set (13.4).
2881 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002882 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002883 // -- For a non-type template-parameter of type reference to
2884 // function, no conversions apply. If the template-argument
2885 // represents a set of overloaded functions, the matching
2886 // function is selected from the set (13.4).
2887 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002888 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002889 // -- For a non-type template-parameter of type pointer to
2890 // member function, no conversions apply. If the
2891 // template-argument represents a set of overloaded member
2892 // functions, the matching member function is selected from
2893 // the set (13.4).
2894 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002895 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002896 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002897
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002898 if (Arg->getType() == Context.OverloadTy) {
2899 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2900 true,
2901 FoundResult)) {
2902 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2903 return true;
2904
2905 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2906 ArgType = Arg->getType();
2907 } else
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002908 return true;
Douglas Gregora35284b2009-02-11 00:19:33 +00002909 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002910
Douglas Gregorb7a09262010-04-01 18:32:35 +00002911 if (!ParamType->isMemberPointerType())
2912 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2913 ParamType,
2914 Arg, Converted);
2915
2916 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
2917 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2918 Arg->isLvalue(Context) == Expr::LV_Valid);
2919 } else if (!Context.hasSameUnqualifiedType(ArgType,
2920 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002921 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002922 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002923 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002924 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002925 Diag(Param->getLocation(), diag::note_template_param_here);
2926 return true;
2927 }
Mike Stump1eb44332009-09-09 15:08:12 +00002928
Douglas Gregorb7a09262010-04-01 18:32:35 +00002929 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregora35284b2009-02-11 00:19:33 +00002930 }
2931
Chris Lattnerfe90de72009-02-20 21:37:53 +00002932 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002933 // -- for a non-type template-parameter of type pointer to
2934 // object, qualification conversions (4.4) and the
2935 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002936 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002937 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002938 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002939
Douglas Gregorb7a09262010-04-01 18:32:35 +00002940 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2941 ParamType,
2942 Arg, Converted);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002943 }
Mike Stump1eb44332009-09-09 15:08:12 +00002944
Ted Kremenek6217b802009-07-29 21:53:49 +00002945 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002946 // -- For a non-type template-parameter of type reference to
2947 // object, no conversions apply. The type referred to by the
2948 // reference may be more cv-qualified than the (otherwise
2949 // identical) type of the template-argument. The
2950 // template-parameter is bound directly to the
2951 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002952 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002953 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002954
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002955 if (Arg->getType() == Context.OverloadTy) {
2956 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2957 ParamRefType->getPointeeType(),
2958 true,
2959 FoundResult)) {
2960 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2961 return true;
2962
2963 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2964 ArgType = Arg->getType();
2965 } else
Douglas Gregorb7a09262010-04-01 18:32:35 +00002966 return true;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002967 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002968
Douglas Gregorb7a09262010-04-01 18:32:35 +00002969 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2970 ParamType,
2971 Arg, Converted);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002972 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002973
2974 // -- For a non-type template-parameter of type pointer to data
2975 // member, qualification conversions (4.4) are applied.
2976 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2977
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002978 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002979 // Types match exactly: nothing more to do here.
2980 } else if (IsQualificationConversion(ArgType, ParamType)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002981 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2982 Arg->isLvalue(Context) == Expr::LV_Valid);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002983 } else {
2984 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002985 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00002986 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002987 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00002988 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002989 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00002990 }
2991
Douglas Gregorcaddba02009-11-12 18:38:13 +00002992 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002993}
2994
2995/// \brief Check a template argument against its corresponding
2996/// template template parameter.
2997///
2998/// This routine implements the semantics of C++ [temp.arg.template].
2999/// It returns true if an error occurred, and false otherwise.
3000bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00003001 const TemplateArgumentLoc &Arg) {
3002 TemplateName Name = Arg.getArgument().getAsTemplate();
3003 TemplateDecl *Template = Name.getAsTemplateDecl();
3004 if (!Template) {
3005 // Any dependent template name is fine.
3006 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3007 return false;
3008 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003009
3010 // C++ [temp.arg.template]p1:
3011 // A template-argument for a template template-parameter shall be
3012 // the name of a class template, expressed as id-expression. Only
3013 // primary class templates are considered when matching the
3014 // template template argument with the corresponding parameter;
3015 // partial specializations are not considered even if their
3016 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003017 //
3018 // Note that we also allow template template parameters here, which
3019 // will happen when we are dealing with, e.g., class template
3020 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00003021 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003022 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003023 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00003024 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00003025 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00003026 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003027 << Template;
3028 }
3029
3030 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3031 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00003032 true,
3033 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00003034 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00003035}
3036
Douglas Gregor02024a92010-03-28 02:42:43 +00003037/// \brief Given a non-type template argument that refers to a
3038/// declaration and the type of its corresponding non-type template
3039/// parameter, produce an expression that properly refers to that
3040/// declaration.
3041Sema::OwningExprResult
3042Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3043 QualType ParamType,
3044 SourceLocation Loc) {
3045 assert(Arg.getKind() == TemplateArgument::Declaration &&
3046 "Only declaration template arguments permitted here");
3047 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3048
3049 if (VD->getDeclContext()->isRecord() &&
3050 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3051 // If the value is a class member, we might have a pointer-to-member.
3052 // Determine whether the non-type template template parameter is of
3053 // pointer-to-member type. If so, we need to build an appropriate
3054 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3055 // would refer to the member itself.
3056 if (ParamType->isMemberPointerType()) {
3057 QualType ClassType
3058 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3059 NestedNameSpecifier *Qualifier
3060 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
3061 CXXScopeSpec SS;
3062 SS.setScopeRep(Qualifier);
3063 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
3064 VD->getType().getNonReferenceType(),
3065 Loc,
3066 &SS);
3067 if (RefExpr.isInvalid())
3068 return ExprError();
3069
3070 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregorc0c83002010-04-30 21:46:38 +00003071
3072 // We might need to perform a trailing qualification conversion, since
3073 // the element type on the parameter could be more qualified than the
3074 // element type in the expression we constructed.
3075 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3076 ParamType.getUnqualifiedType())) {
3077 Expr *RefE = RefExpr.takeAs<Expr>();
3078 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(),
3079 CastExpr::CK_NoOp);
3080 RefExpr = Owned(RefE);
3081 }
3082
Douglas Gregor02024a92010-03-28 02:42:43 +00003083 assert(!RefExpr.isInvalid() &&
3084 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00003085 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00003086 return move(RefExpr);
3087 }
3088 }
3089
3090 QualType T = VD->getType().getNonReferenceType();
3091 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003092 // When the non-type template parameter is a pointer, take the
3093 // address of the declaration.
Douglas Gregor02024a92010-03-28 02:42:43 +00003094 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3095 if (RefExpr.isInvalid())
3096 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003097
3098 if (T->isFunctionType() || T->isArrayType()) {
3099 // Decay functions and arrays.
3100 Expr *RefE = (Expr *)RefExpr.get();
3101 DefaultFunctionArrayConversion(RefE);
3102 if (RefE != RefExpr.get()) {
3103 RefExpr.release();
3104 RefExpr = Owned(RefE);
3105 }
3106
3107 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00003108 }
3109
Douglas Gregorb7a09262010-04-01 18:32:35 +00003110 // Take the address of everything else
3111 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregor02024a92010-03-28 02:42:43 +00003112 }
3113
3114 // If the non-type template parameter has reference type, qualify the
3115 // resulting declaration reference with the extra qualifiers on the
3116 // type that the reference refers to.
3117 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3118 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3119
3120 return BuildDeclRefExpr(VD, T, Loc);
3121}
3122
3123/// \brief Construct a new expression that refers to the given
3124/// integral template argument with the given source-location
3125/// information.
3126///
3127/// This routine takes care of the mapping from an integral template
3128/// argument (which may have any integral type) to the appropriate
3129/// literal value.
3130Sema::OwningExprResult
3131Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3132 SourceLocation Loc) {
3133 assert(Arg.getKind() == TemplateArgument::Integral &&
3134 "Operation is only value for integral template arguments");
3135 QualType T = Arg.getIntegralType();
3136 if (T->isCharType() || T->isWideCharType())
3137 return Owned(new (Context) CharacterLiteral(
3138 Arg.getAsIntegral()->getZExtValue(),
3139 T->isWideCharType(),
3140 T,
3141 Loc));
3142 if (T->isBooleanType())
3143 return Owned(new (Context) CXXBoolLiteralExpr(
3144 Arg.getAsIntegral()->getBoolValue(),
3145 T,
3146 Loc));
3147
3148 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3149}
3150
3151
Douglas Gregorddc29e12009-02-06 22:42:48 +00003152/// \brief Determine whether the given template parameter lists are
3153/// equivalent.
3154///
Mike Stump1eb44332009-09-09 15:08:12 +00003155/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00003156/// source code as part of a new template declaration.
3157///
3158/// \param Old The old template parameter list, typically found via
3159/// name lookup of the template declared with this template parameter
3160/// list.
3161///
3162/// \param Complain If true, this routine will produce a diagnostic if
3163/// the template parameter lists are not equivalent.
3164///
Douglas Gregorfb898e12009-11-12 16:20:59 +00003165/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00003166///
3167/// \param TemplateArgLoc If this source location is valid, then we
3168/// are actually checking the template parameter list of a template
3169/// argument (New) against the template parameter list of its
3170/// corresponding template template parameter (Old). We produce
3171/// slightly different diagnostics in this scenario.
3172///
Douglas Gregorddc29e12009-02-06 22:42:48 +00003173/// \returns True if the template parameter lists are equal, false
3174/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003175bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00003176Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3177 TemplateParameterList *Old,
3178 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003179 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003180 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003181 if (Old->size() != New->size()) {
3182 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003183 unsigned NextDiag = diag::err_template_param_list_different_arity;
3184 if (TemplateArgLoc.isValid()) {
3185 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3186 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00003187 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003188 Diag(New->getTemplateLoc(), NextDiag)
3189 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00003190 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003191 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00003192 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003193 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003194 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3195 }
3196
3197 return false;
3198 }
3199
3200 for (TemplateParameterList::iterator OldParm = Old->begin(),
3201 OldParmEnd = Old->end(), NewParm = New->begin();
3202 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3203 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003204 if (Complain) {
3205 unsigned NextDiag = diag::err_template_param_different_kind;
3206 if (TemplateArgLoc.isValid()) {
3207 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3208 NextDiag = diag::note_template_param_different_kind;
3209 }
3210 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003211 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003212 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003213 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00003214 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003215 return false;
3216 }
3217
3218 if (isa<TemplateTypeParmDecl>(*OldParm)) {
3219 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00003220 // know we're at the same index).
Mike Stump1eb44332009-09-09 15:08:12 +00003221 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003222 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3223 // The types of non-type template parameters must agree.
3224 NonTypeTemplateParmDecl *NewNTTP
3225 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00003226
3227 // If we are matching a template template argument to a template
3228 // template parameter and one of the non-type template parameter types
3229 // is dependent, then we must wait until template instantiation time
3230 // to actually compare the arguments.
3231 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3232 (OldNTTP->getType()->isDependentType() ||
3233 NewNTTP->getType()->isDependentType()))
3234 continue;
3235
Douglas Gregorddc29e12009-02-06 22:42:48 +00003236 if (Context.getCanonicalType(OldNTTP->getType()) !=
3237 Context.getCanonicalType(NewNTTP->getType())) {
3238 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003239 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3240 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003241 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003242 diag::err_template_arg_template_params_mismatch);
3243 NextDiag = diag::note_template_nontype_parm_different_type;
3244 }
3245 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003246 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00003247 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00003248 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00003249 diag::note_template_nontype_parm_prev_declaration)
3250 << OldNTTP->getType();
3251 }
3252 return false;
3253 }
3254 } else {
3255 // The template parameter lists of template template
3256 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00003257 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00003258 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00003259 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003260 = cast<TemplateTemplateParmDecl>(*OldParm);
3261 TemplateTemplateParmDecl *NewTTP
3262 = cast<TemplateTemplateParmDecl>(*NewParm);
3263 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3264 OldTTP->getTemplateParameters(),
3265 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003266 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00003267 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003268 return false;
3269 }
3270 }
3271
3272 return true;
3273}
3274
3275/// \brief Check whether a template can be declared within this scope.
3276///
3277/// If the template declaration is valid in this scope, returns
3278/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003279bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003280Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003281 // Find the nearest enclosing declaration scope.
3282 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3283 (S->getFlags() & Scope::TemplateParamScope) != 0)
3284 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003285
Douglas Gregorddc29e12009-02-06 22:42:48 +00003286 // C++ [temp]p2:
3287 // A template-declaration can appear only as a namespace scope or
3288 // class scope declaration.
3289 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003290 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3291 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003292 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003293 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003294
Eli Friedman1503f772009-07-31 01:43:05 +00003295 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003296 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003297
3298 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3299 return false;
3300
Mike Stump1eb44332009-09-09 15:08:12 +00003301 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003302 diag::err_template_outside_namespace_or_class_scope)
3303 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003304}
Douglas Gregorcc636682009-02-17 23:15:12 +00003305
Douglas Gregord5cb8762009-10-07 00:13:32 +00003306/// \brief Determine what kind of template specialization the given declaration
3307/// is.
3308static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3309 if (!D)
3310 return TSK_Undeclared;
3311
Douglas Gregorf6b11852009-10-08 15:14:33 +00003312 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3313 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003314 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3315 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003316 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3317 return Var->getTemplateSpecializationKind();
3318
Douglas Gregord5cb8762009-10-07 00:13:32 +00003319 return TSK_Undeclared;
3320}
3321
Douglas Gregor9302da62009-10-14 23:50:59 +00003322/// \brief Check whether a specialization is well-formed in the current
3323/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003324///
Douglas Gregor9302da62009-10-14 23:50:59 +00003325/// This routine determines whether a template specialization can be declared
3326/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003327///
3328/// \param S the semantic analysis object for which this check is being
3329/// performed.
3330///
3331/// \param Specialized the entity being specialized or instantiated, which
3332/// may be a kind of template (class template, function template, etc.) or
3333/// a member of a class template (member function, static data member,
3334/// member class).
3335///
3336/// \param PrevDecl the previous declaration of this entity, if any.
3337///
3338/// \param Loc the location of the explicit specialization or instantiation of
3339/// this entity.
3340///
3341/// \param IsPartialSpecialization whether this is a partial specialization of
3342/// a class template.
3343///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003344/// \returns true if there was an error that we cannot recover from, false
3345/// otherwise.
3346static bool CheckTemplateSpecializationScope(Sema &S,
3347 NamedDecl *Specialized,
3348 NamedDecl *PrevDecl,
3349 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003350 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003351 // Keep these "kind" numbers in sync with the %select statements in the
3352 // various diagnostics emitted by this routine.
3353 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003354 bool isTemplateSpecialization = false;
3355 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003356 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003357 isTemplateSpecialization = true;
3358 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003359 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003360 isTemplateSpecialization = true;
3361 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003362 EntityKind = 3;
3363 else if (isa<VarDecl>(Specialized))
3364 EntityKind = 4;
3365 else if (isa<RecordDecl>(Specialized))
3366 EntityKind = 5;
3367 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003368 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3369 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003370 return true;
3371 }
3372
Douglas Gregor88b70942009-02-25 22:02:03 +00003373 // C++ [temp.expl.spec]p2:
3374 // An explicit specialization shall be declared in the namespace
3375 // of which the template is a member, or, for member templates, in
3376 // the namespace of which the enclosing class or enclosing class
3377 // template is a member. An explicit specialization of a member
3378 // function, member class or static data member of a class
3379 // template shall be declared in the namespace of which the class
3380 // template is a member. Such a declaration may also be a
3381 // definition. If the declaration is not a definition, the
3382 // specialization may be defined later in the name- space in which
3383 // the explicit specialization was declared, or in a namespace
3384 // that encloses the one in which the explicit specialization was
3385 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003386 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3387 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003388 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003389 return true;
3390 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003391
Douglas Gregor0a407472009-10-07 17:30:37 +00003392 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3393 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003394 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003395 return true;
3396 }
3397
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003398 // C++ [temp.class.spec]p6:
3399 // A class template partial specialization may be declared or redeclared
3400 // in any namespace scope in which its definition may be defined (14.5.1
3401 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003402 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003403 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003404 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003405 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003406 if ((!PrevDecl ||
3407 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3408 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3409 // There is no prior declaration of this entity, so this
3410 // specialization must be in the same context as the template
3411 // itself.
3412 if (!DC->Equals(SpecializedContext)) {
3413 if (isa<TranslationUnitDecl>(SpecializedContext))
3414 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3415 << EntityKind << Specialized;
3416 else if (isa<NamespaceDecl>(SpecializedContext))
3417 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3418 << EntityKind << Specialized
3419 << cast<NamedDecl>(SpecializedContext);
3420
3421 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3422 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003423 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003424 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003425
3426 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003427 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003428 // Note that HandleDeclarator() performs this check for explicit
3429 // specializations of function templates, static data members, and member
3430 // functions, so we skip the check here for those kinds of entities.
3431 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003432 // Should we refactor that check, so that it occurs later?
3433 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003434 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3435 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003436 if (isa<TranslationUnitDecl>(SpecializedContext))
3437 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3438 << EntityKind << Specialized;
3439 else if (isa<NamespaceDecl>(SpecializedContext))
3440 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3441 << EntityKind << Specialized
3442 << cast<NamedDecl>(SpecializedContext);
3443
Douglas Gregor9302da62009-10-14 23:50:59 +00003444 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003445 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003446
3447 // FIXME: check for specialization-after-instantiation errors and such.
3448
Douglas Gregor88b70942009-02-25 22:02:03 +00003449 return false;
3450}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003451
Douglas Gregore94866f2009-06-12 21:21:02 +00003452/// \brief Check the non-type template arguments of a class template
3453/// partial specialization according to C++ [temp.class.spec]p9.
3454///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003455/// \param TemplateParams the template parameters of the primary class
3456/// template.
3457///
3458/// \param TemplateArg the template arguments of the class template
3459/// partial specialization.
3460///
3461/// \param MirrorsPrimaryTemplate will be set true if the class
3462/// template partial specialization arguments are identical to the
3463/// implicit template arguments of the primary template. This is not
3464/// necessarily an error (C++0x), and it is left to the caller to diagnose
3465/// this condition when it is an error.
3466///
Douglas Gregore94866f2009-06-12 21:21:02 +00003467/// \returns true if there was an error, false otherwise.
3468bool Sema::CheckClassTemplatePartialSpecializationArgs(
3469 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00003470 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003471 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003472 // FIXME: the interface to this function will have to change to
3473 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003474 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003475
Anders Carlssonfb250522009-06-23 01:26:57 +00003476 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00003477
Douglas Gregore94866f2009-06-12 21:21:02 +00003478 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003479 // Determine whether the template argument list of the partial
3480 // specialization is identical to the implicit argument list of
3481 // the primary template. The caller may need to diagnostic this as
3482 // an error per C++ [temp.class.spec]p9b3.
3483 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003484 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003485 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3486 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003487 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003488 MirrorsPrimaryTemplate = false;
3489 } else if (TemplateTemplateParmDecl *TTP
3490 = dyn_cast<TemplateTemplateParmDecl>(
3491 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003492 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003493 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003494 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003495 if (!ArgDecl ||
3496 ArgDecl->getIndex() != TTP->getIndex() ||
3497 ArgDecl->getDepth() != TTP->getDepth())
3498 MirrorsPrimaryTemplate = false;
3499 }
3500 }
3501
Mike Stump1eb44332009-09-09 15:08:12 +00003502 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003503 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003504 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003505 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003506 }
3507
Anders Carlsson6360be72009-06-13 18:20:51 +00003508 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003509 if (!ArgExpr) {
3510 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003511 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003512 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003513
3514 // C++ [temp.class.spec]p8:
3515 // A non-type argument is non-specialized if it is the name of a
3516 // non-type parameter. All other non-type arguments are
3517 // specialized.
3518 //
3519 // Below, we check the two conditions that only apply to
3520 // specialized non-type arguments, so skip any non-specialized
3521 // arguments.
3522 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003523 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003524 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003525 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003526 (Param->getIndex() != NTTP->getIndex() ||
3527 Param->getDepth() != NTTP->getDepth()))
3528 MirrorsPrimaryTemplate = false;
3529
Douglas Gregore94866f2009-06-12 21:21:02 +00003530 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003531 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003532
3533 // C++ [temp.class.spec]p9:
3534 // Within the argument list of a class template partial
3535 // specialization, the following restrictions apply:
3536 // -- A partially specialized non-type argument expression
3537 // shall not involve a template parameter of the partial
3538 // specialization except when the argument expression is a
3539 // simple identifier.
3540 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003541 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003542 diag::err_dependent_non_type_arg_in_partial_spec)
3543 << ArgExpr->getSourceRange();
3544 return true;
3545 }
3546
3547 // -- The type of a template parameter corresponding to a
3548 // specialized non-type argument shall not be dependent on a
3549 // parameter of the specialization.
3550 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003551 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003552 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3553 << Param->getType()
3554 << ArgExpr->getSourceRange();
3555 Diag(Param->getLocation(), diag::note_template_param_here);
3556 return true;
3557 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003558
3559 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003560 }
3561
3562 return false;
3563}
3564
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003565/// \brief Retrieve the previous declaration of the given declaration.
3566static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3567 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3568 return VD->getPreviousDeclaration();
3569 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3570 return FD->getPreviousDeclaration();
3571 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3572 return TD->getPreviousDeclaration();
3573 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3574 return TD->getPreviousDeclaration();
3575 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3576 return FTD->getPreviousDeclaration();
3577 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3578 return CTD->getPreviousDeclaration();
3579 return 0;
3580}
3581
Douglas Gregor212e81c2009-03-25 00:13:59 +00003582Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003583Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3584 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00003585 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003586 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003587 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00003588 SourceLocation TemplateNameLoc,
3589 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00003590 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00003591 SourceLocation RAngleLoc,
3592 AttributeList *Attr,
3593 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003594 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00003595
Douglas Gregorcc636682009-02-17 23:15:12 +00003596 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00003597 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003598 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00003599 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3600
3601 if (!ClassTemplate) {
3602 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3603 << (Name.getAsTemplateDecl() &&
3604 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3605 return true;
3606 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003607
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003608 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003609 bool isPartialSpecialization = false;
3610
Douglas Gregor88b70942009-02-25 22:02:03 +00003611 // Check the validity of the template headers that introduce this
3612 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003613 // FIXME: We probably shouldn't complain about these headers for
3614 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00003615 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00003616 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3617 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003618 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00003619 TUK == TUK_Friend,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003620 isExplicitSpecialization);
Douglas Gregor05396e22009-08-25 17:23:04 +00003621 if (TemplateParams && TemplateParams->size() > 0) {
3622 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003623
Douglas Gregor05396e22009-08-25 17:23:04 +00003624 // C++ [temp.class.spec]p10:
3625 // The template parameter list of a specialization shall not
3626 // contain default template argument values.
3627 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3628 Decl *Param = TemplateParams->getParam(I);
3629 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3630 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003631 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003632 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00003633 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003634 }
3635 } else if (NonTypeTemplateParmDecl *NTTP
3636 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3637 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003638 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003639 diag::err_default_arg_in_partial_spec)
3640 << DefArg->getSourceRange();
3641 NTTP->setDefaultArgument(0);
3642 DefArg->Destroy(Context);
3643 }
3644 } else {
3645 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003646 if (TTP->hasDefaultArgument()) {
3647 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003648 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003649 << TTP->getDefaultArgument().getSourceRange();
3650 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003651 }
3652 }
3653 }
Douglas Gregora735b202009-10-13 14:39:41 +00003654 } else if (TemplateParams) {
3655 if (TUK == TUK_Friend)
3656 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00003657 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00003658 SourceRange(TemplateParams->getTemplateLoc(),
3659 TemplateParams->getRAngleLoc()))
3660 << SourceRange(LAngleLoc, RAngleLoc);
3661 else
3662 isExplicitSpecialization = true;
3663 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003664 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00003665 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003666 isExplicitSpecialization = true;
3667 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003668
Douglas Gregorcc636682009-02-17 23:15:12 +00003669 // Check that the specialization uses the same tag kind as the
3670 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003671 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3672 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003673 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003674 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003675 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003676 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003677 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00003678 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003679 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003680 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003681 diag::note_previous_use);
3682 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3683 }
3684
Douglas Gregor40808ce2009-03-09 23:48:35 +00003685 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00003686 TemplateArgumentListInfo TemplateArgs;
3687 TemplateArgs.setLAngleLoc(LAngleLoc);
3688 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00003689 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003690
Douglas Gregorcc636682009-02-17 23:15:12 +00003691 // Check that the template argument list is well-formed for this
3692 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003693 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3694 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00003695 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3696 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003697 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003698
Mike Stump1eb44332009-09-09 15:08:12 +00003699 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003700 ClassTemplate->getTemplateParameters()->size()) &&
3701 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003702
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003703 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003704 // corresponds to these arguments.
3705 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003706 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003707 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003708 if (CheckClassTemplatePartialSpecializationArgs(
3709 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003710 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003711 return true;
3712
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003713 if (MirrorsPrimaryTemplate) {
3714 // C++ [temp.class.spec]p9b3:
3715 //
Mike Stump1eb44332009-09-09 15:08:12 +00003716 // -- The argument list of the specialization shall not be identical
3717 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003718 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003719 << (TUK == TUK_Definition)
Douglas Gregor849b2432010-03-31 17:46:05 +00003720 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003721 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003722 ClassTemplate->getIdentifier(),
3723 TemplateNameLoc,
3724 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003725 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003726 AS_none);
3727 }
3728
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003729 // FIXME: Diagnose friend partial specializations
3730
Douglas Gregorde090962010-02-09 00:37:32 +00003731 if (!Name.isDependent() &&
3732 !TemplateSpecializationType::anyDependentTemplateArguments(
3733 TemplateArgs.getArgumentArray(),
3734 TemplateArgs.size())) {
3735 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3736 << ClassTemplate->getDeclName();
3737 isPartialSpecialization = false;
3738 } else {
3739 // FIXME: Template parameter list matters, too
3740 ClassTemplatePartialSpecializationDecl::Profile(ID,
3741 Converted.getFlatArguments(),
3742 Converted.flatSize(),
3743 Context);
3744 }
3745 }
3746
3747 if (!isPartialSpecialization)
Anders Carlsson1c5976e2009-06-05 03:43:12 +00003748 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003749 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003750 Converted.flatSize(),
3751 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00003752 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003753 ClassTemplateSpecializationDecl *PrevDecl = 0;
3754
3755 if (isPartialSpecialization)
3756 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00003757 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003758 InsertPos);
3759 else
3760 PrevDecl
3761 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003762
3763 ClassTemplateSpecializationDecl *Specialization = 0;
3764
Douglas Gregor88b70942009-02-25 22:02:03 +00003765 // Check whether we can declare a class template specialization in
3766 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003767 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003768 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003769 TemplateNameLoc,
3770 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003771 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003772
Douglas Gregorb88e8882009-07-30 17:40:51 +00003773 // The canonical type
3774 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003775 if (PrevDecl &&
3776 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00003777 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003778 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003779 // arguments was referenced but not declared, or we're only
3780 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003781 // declaration node as our own, updating its source location to
3782 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003783 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003784 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003785 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003786 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003787 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003788 // Build the canonical type that describes the converted template
3789 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00003790 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3791 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb88e8882009-07-30 17:40:51 +00003792 Converted.getFlatArguments(),
3793 Converted.flatSize());
3794
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003795 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003796 ClassTemplatePartialSpecializationDecl *PrevPartial
3797 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00003798 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
3799 : ClassTemplate->getPartialSpecializations().size();
Mike Stump1eb44332009-09-09 15:08:12 +00003800 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00003801 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003802 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003803 TemplateNameLoc,
3804 TemplateParams,
3805 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003806 Converted,
John McCalld5532b62009-11-23 01:53:49 +00003807 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00003808 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00003809 PrevPartial,
3810 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00003811 SetNestedNameSpecifier(Partial, SS);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003812
3813 if (PrevPartial) {
3814 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3815 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3816 } else {
3817 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3818 }
3819 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003820
Douglas Gregored9c0f92009-10-29 00:04:11 +00003821 // If we are providing an explicit specialization of a member class
3822 // template specialization, make a note of that.
3823 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3824 PrevPartial->setMemberSpecialization();
3825
Douglas Gregor031a5882009-06-13 00:26:55 +00003826 // Check that all of the template parameters of the class template
3827 // partial specialization are deducible from the template
3828 // arguments. If not, this class template partial specialization
3829 // will never be used.
3830 llvm::SmallVector<bool, 8> DeducibleParams;
3831 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003832 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003833 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003834 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003835 unsigned NumNonDeducible = 0;
3836 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3837 if (!DeducibleParams[I])
3838 ++NumNonDeducible;
3839
3840 if (NumNonDeducible) {
3841 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3842 << (NumNonDeducible > 1)
3843 << SourceRange(TemplateNameLoc, RAngleLoc);
3844 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3845 if (!DeducibleParams[I]) {
3846 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3847 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003848 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003849 diag::note_partial_spec_unused_parameter)
3850 << Param->getDeclName();
3851 else
Mike Stump1eb44332009-09-09 15:08:12 +00003852 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003853 diag::note_partial_spec_unused_parameter)
3854 << std::string("<anonymous>");
3855 }
3856 }
3857 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003858 } else {
3859 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003860 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003861 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00003862 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00003863 ClassTemplate->getDeclContext(),
3864 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003865 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003866 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003867 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00003868 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregorcc636682009-02-17 23:15:12 +00003869
3870 if (PrevDecl) {
3871 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3872 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3873 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003874 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00003875 InsertPos);
3876 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00003877
3878 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003879 }
3880
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003881 // C++ [temp.expl.spec]p6:
3882 // If a template, a member template or the member of a class template is
3883 // explicitly specialized then that specialization shall be declared
3884 // before the first use of that specialization that would cause an implicit
3885 // instantiation to take place, in every translation unit in which such a
3886 // use occurs; no diagnostic is required.
3887 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003888 bool Okay = false;
3889 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3890 // Is there any previous explicit specialization declaration?
3891 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3892 Okay = true;
3893 break;
3894 }
3895 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003896
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003897 if (!Okay) {
3898 SourceRange Range(TemplateNameLoc, RAngleLoc);
3899 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3900 << Context.getTypeDeclType(Specialization) << Range;
3901
3902 Diag(PrevDecl->getPointOfInstantiation(),
3903 diag::note_instantiation_required_here)
3904 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003905 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003906 return true;
3907 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003908 }
3909
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003910 // If this is not a friend, note that this is an explicit specialization.
3911 if (TUK != TUK_Friend)
3912 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003913
3914 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003915 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00003916 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003917 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003918 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003919 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003920 Diag(Def->getLocation(), diag::note_previous_definition);
3921 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003922 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003923 }
3924 }
3925
Douglas Gregorfc705b82009-02-26 22:19:44 +00003926 // Build the fully-sugared type for this class template
3927 // specialization as the user wrote in the specialization
3928 // itself. This means that we'll pretty-print the type retrieved
3929 // from the specialization's declaration the way that the user
3930 // actually wrote the specialization, rather than formatting the
3931 // name based on the "canonical" representation used to store the
3932 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00003933 TypeSourceInfo *WrittenTy
3934 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3935 TemplateArgs, CanonType);
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003936 if (TUK != TUK_Friend)
3937 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003938 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00003939
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003940 // C++ [temp.expl.spec]p9:
3941 // A template explicit specialization is in the scope of the
3942 // namespace in which the template was defined.
3943 //
3944 // We actually implement this paragraph where we set the semantic
3945 // context (in the creation of the ClassTemplateSpecializationDecl),
3946 // but we also maintain the lexical context where the actual
3947 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00003948 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003949
Douglas Gregorcc636682009-02-17 23:15:12 +00003950 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003951 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00003952 Specialization->startDefinition();
3953
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003954 if (TUK == TUK_Friend) {
3955 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3956 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00003957 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003958 /*FIXME:*/KWLoc);
3959 Friend->setAccess(AS_public);
3960 CurContext->addDecl(Friend);
3961 } else {
3962 // Add the specialization into its lexical context, so that it can
3963 // be seen when iterating through the list of declarations in that
3964 // context. However, specializations are not found by name lookup.
3965 CurContext->addDecl(Specialization);
3966 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003967 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003968}
Douglas Gregord57959a2009-03-27 23:10:48 +00003969
Mike Stump1eb44332009-09-09 15:08:12 +00003970Sema::DeclPtrTy
3971Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00003972 MultiTemplateParamsArg TemplateParameterLists,
3973 Declarator &D) {
3974 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3975}
3976
Mike Stump1eb44332009-09-09 15:08:12 +00003977Sema::DeclPtrTy
3978Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003979 MultiTemplateParamsArg TemplateParameterLists,
3980 Declarator &D) {
3981 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3982 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3983 "Not a function declarator!");
3984 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00003985
Douglas Gregor52591bf2009-06-24 00:54:41 +00003986 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00003987 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00003988 }
Mike Stump1eb44332009-09-09 15:08:12 +00003989
Douglas Gregor52591bf2009-06-24 00:54:41 +00003990 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003991
3992 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003993 move(TemplateParameterLists),
3994 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003995 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003996 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00003997 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00003998 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003999 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
4000 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00004001 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00004002}
4003
John McCall75042392010-02-11 01:33:53 +00004004/// \brief Strips various properties off an implicit instantiation
4005/// that has just been explicitly specialized.
4006static void StripImplicitInstantiation(NamedDecl *D) {
4007 D->invalidateAttrs();
4008
4009 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4010 FD->setInlineSpecified(false);
4011 }
4012}
4013
Douglas Gregor454885e2009-10-15 15:54:05 +00004014/// \brief Diagnose cases where we have an explicit template specialization
4015/// before/after an explicit template instantiation, producing diagnostics
4016/// for those cases where they are required and determining whether the
4017/// new specialization/instantiation will have any effect.
4018///
Douglas Gregor454885e2009-10-15 15:54:05 +00004019/// \param NewLoc the location of the new explicit specialization or
4020/// instantiation.
4021///
4022/// \param NewTSK the kind of the new explicit specialization or instantiation.
4023///
4024/// \param PrevDecl the previous declaration of the entity.
4025///
4026/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4027///
4028/// \param PrevPointOfInstantiation if valid, indicates where the previus
4029/// declaration was instantiated (either implicitly or explicitly).
4030///
4031/// \param SuppressNew will be set to true to indicate that the new
4032/// specialization or instantiation has no effect and should be ignored.
4033///
4034/// \returns true if there was an error that should prevent the introduction of
4035/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00004036bool
4037Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4038 TemplateSpecializationKind NewTSK,
4039 NamedDecl *PrevDecl,
4040 TemplateSpecializationKind PrevTSK,
4041 SourceLocation PrevPointOfInstantiation,
4042 bool &SuppressNew) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004043 SuppressNew = false;
4044
4045 switch (NewTSK) {
4046 case TSK_Undeclared:
4047 case TSK_ImplicitInstantiation:
4048 assert(false && "Don't check implicit instantiations here");
4049 return false;
4050
4051 case TSK_ExplicitSpecialization:
4052 switch (PrevTSK) {
4053 case TSK_Undeclared:
4054 case TSK_ExplicitSpecialization:
4055 // Okay, we're just specializing something that is either already
4056 // explicitly specialized or has merely been mentioned without any
4057 // instantiation.
4058 return false;
4059
4060 case TSK_ImplicitInstantiation:
4061 if (PrevPointOfInstantiation.isInvalid()) {
4062 // The declaration itself has not actually been instantiated, so it is
4063 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00004064 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00004065 return false;
4066 }
4067 // Fall through
4068
4069 case TSK_ExplicitInstantiationDeclaration:
4070 case TSK_ExplicitInstantiationDefinition:
4071 assert((PrevTSK == TSK_ImplicitInstantiation ||
4072 PrevPointOfInstantiation.isValid()) &&
4073 "Explicit instantiation without point of instantiation?");
4074
4075 // C++ [temp.expl.spec]p6:
4076 // If a template, a member template or the member of a class template
4077 // is explicitly specialized then that specialization shall be declared
4078 // before the first use of that specialization that would cause an
4079 // implicit instantiation to take place, in every translation unit in
4080 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004081 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4082 // Is there any previous explicit specialization declaration?
4083 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4084 return false;
4085 }
4086
Douglas Gregor0d035142009-10-27 18:42:08 +00004087 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00004088 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004089 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00004090 << (PrevTSK != TSK_ImplicitInstantiation);
4091
4092 return true;
4093 }
4094 break;
4095
4096 case TSK_ExplicitInstantiationDeclaration:
4097 switch (PrevTSK) {
4098 case TSK_ExplicitInstantiationDeclaration:
4099 // This explicit instantiation declaration is redundant (that's okay).
4100 SuppressNew = true;
4101 return false;
4102
4103 case TSK_Undeclared:
4104 case TSK_ImplicitInstantiation:
4105 // We're explicitly instantiating something that may have already been
4106 // implicitly instantiated; that's fine.
4107 return false;
4108
4109 case TSK_ExplicitSpecialization:
4110 // C++0x [temp.explicit]p4:
4111 // For a given set of template parameters, if an explicit instantiation
4112 // of a template appears after a declaration of an explicit
4113 // specialization for that template, the explicit instantiation has no
4114 // effect.
John McCalle97c32f2010-03-02 23:09:38 +00004115 SuppressNew = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004116 return false;
4117
4118 case TSK_ExplicitInstantiationDefinition:
4119 // C++0x [temp.explicit]p10:
4120 // If an entity is the subject of both an explicit instantiation
4121 // declaration and an explicit instantiation definition in the same
4122 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00004123 Diag(NewLoc,
4124 diag::err_explicit_instantiation_declaration_after_definition);
4125 Diag(PrevPointOfInstantiation,
4126 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00004127 assert(PrevPointOfInstantiation.isValid() &&
4128 "Explicit instantiation without point of instantiation?");
4129 SuppressNew = true;
4130 return false;
4131 }
4132 break;
4133
4134 case TSK_ExplicitInstantiationDefinition:
4135 switch (PrevTSK) {
4136 case TSK_Undeclared:
4137 case TSK_ImplicitInstantiation:
4138 // We're explicitly instantiating something that may have already been
4139 // implicitly instantiated; that's fine.
4140 return false;
4141
4142 case TSK_ExplicitSpecialization:
4143 // C++ DR 259, C++0x [temp.explicit]p4:
4144 // For a given set of template parameters, if an explicit
4145 // instantiation of a template appears after a declaration of
4146 // an explicit specialization for that template, the explicit
4147 // instantiation has no effect.
4148 //
4149 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00004150 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00004151 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00004152 if (!getLangOptions().CPlusPlus0x) {
4153 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00004154 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004155 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00004156 diag::note_previous_template_specialization);
4157 }
4158 SuppressNew = true;
4159 return false;
4160
4161 case TSK_ExplicitInstantiationDeclaration:
4162 // We're explicity instantiating a definition for something for which we
4163 // were previously asked to suppress instantiations. That's fine.
4164 return false;
4165
4166 case TSK_ExplicitInstantiationDefinition:
4167 // C++0x [temp.spec]p5:
4168 // For a given template and a given set of template-arguments,
4169 // - an explicit instantiation definition shall appear at most once
4170 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00004171 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00004172 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004173 Diag(PrevPointOfInstantiation,
4174 diag::note_previous_explicit_instantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00004175 SuppressNew = true;
4176 return false;
4177 }
4178 break;
4179 }
4180
4181 assert(false && "Missing specialization/instantiation case?");
4182
4183 return false;
4184}
4185
John McCallaf2094e2010-04-08 09:05:18 +00004186/// \brief Perform semantic analysis for the given dependent function
4187/// template specialization. The only possible way to get a dependent
4188/// function template specialization is with a friend declaration,
4189/// like so:
4190///
4191/// template <class T> void foo(T);
4192/// template <class T> class A {
4193/// friend void foo<>(T);
4194/// };
4195///
4196/// There really isn't any useful analysis we can do here, so we
4197/// just store the information.
4198bool
4199Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4200 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4201 LookupResult &Previous) {
4202 // Remove anything from Previous that isn't a function template in
4203 // the correct context.
4204 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4205 LookupResult::Filter F = Previous.makeFilter();
4206 while (F.hasNext()) {
4207 NamedDecl *D = F.next()->getUnderlyingDecl();
4208 if (!isa<FunctionTemplateDecl>(D) ||
4209 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4210 F.erase();
4211 }
4212 F.done();
4213
4214 // Should this be diagnosed here?
4215 if (Previous.empty()) return true;
4216
4217 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4218 ExplicitTemplateArgs);
4219 return false;
4220}
4221
Abramo Bagnarae03db982010-05-20 15:32:11 +00004222/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004223/// specialization.
4224///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004225/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004226/// explicit function template specialization. On successful completion,
4227/// the function declaration \p FD will become a function template
4228/// specialization.
4229///
4230/// \param FD the function declaration, which will be updated to become a
4231/// function template specialization.
4232///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004233/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4234/// if any. Note that this may be valid info even when 0 arguments are
4235/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4236/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004237///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004238/// \param PrevDecl the set of declarations that may be specialized by
4239/// this function specialization.
4240bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004241Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004242 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004243 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004244 // The set of function template specializations that could match this
4245 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004246 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004247
4248 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall68263142009-11-18 22:49:29 +00004249 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4250 I != E; ++I) {
4251 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4252 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004253 // Only consider templates found within the same semantic lookup scope as
4254 // FD.
4255 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4256 continue;
4257
4258 // C++ [temp.expl.spec]p11:
4259 // A trailing template-argument can be left unspecified in the
4260 // template-id naming an explicit function template specialization
4261 // provided it can be deduced from the function argument type.
4262 // Perform template argument deduction to determine whether we may be
4263 // specializing this template.
4264 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004265 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004266 FunctionDecl *Specialization = 0;
4267 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004268 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004269 FD->getType(),
4270 Specialization,
4271 Info)) {
4272 // FIXME: Template argument deduction failed; record why it failed, so
4273 // that we can provide nifty diagnostics.
4274 (void)TDK;
4275 continue;
4276 }
4277
4278 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004279 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004280 }
4281 }
4282
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004283 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004284 UnresolvedSetIterator Result
4285 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4286 TPOC_Other, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004287 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004288 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004289 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004290 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004291 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004292 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004293 return true;
John McCallc373d482010-01-27 01:50:18 +00004294
4295 // Ignore access information; it doesn't figure into redeclaration checking.
4296 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorc42b6522010-04-09 21:02:29 +00004297 Specialization->setLocation(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004298
4299 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004300 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004301
4302 // If this is a friend declaration, then we're not really declaring
4303 // an explicit specialization.
4304 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004305
Douglas Gregord5cb8762009-10-07 00:13:32 +00004306 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004307 if (!isFriend &&
4308 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004309 Specialization->getPrimaryTemplate(),
4310 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004311 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004312 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004313
4314 // C++ [temp.expl.spec]p6:
4315 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004316 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004317 // before the first use of that specialization that would cause an implicit
4318 // instantiation to take place, in every translation unit in which such a
4319 // use occurs; no diagnostic is required.
4320 FunctionTemplateSpecializationInfo *SpecInfo
4321 = Specialization->getTemplateSpecializationInfo();
4322 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004323
4324 bool SuppressNew = false;
John McCall7ad650f2010-03-24 07:46:06 +00004325 if (!isFriend &&
4326 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004327 TSK_ExplicitSpecialization,
4328 Specialization,
4329 SpecInfo->getTemplateSpecializationKind(),
4330 SpecInfo->getPointOfInstantiation(),
4331 SuppressNew))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004332 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004333
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004334 // Mark the prior declaration as an explicit specialization, so that later
4335 // clients know that this is an explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004336 if (!isFriend)
4337 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004338
4339 // Turn the given function declaration into a function template
4340 // specialization, with the template arguments from the previous
4341 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00004342 // Take copies of (semantic and syntactic) template argument lists.
4343 const TemplateArgumentList* TemplArgs = new (Context)
4344 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4345 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4346 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregor838db382010-02-11 01:19:42 +00004347 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00004348 TemplArgs, /*InsertPos=*/0,
4349 SpecInfo->getTemplateSpecializationKind(),
4350 TemplArgsAsWritten);
4351
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004352 // The "previous declaration" for this function template specialization is
4353 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004354 Previous.clear();
4355 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004356 return false;
4357}
4358
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004359/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004360/// specialization.
4361///
4362/// This routine performs all of the semantic analysis required for an
4363/// explicit member function specialization. On successful completion,
4364/// the function declaration \p FD will become a member function
4365/// specialization.
4366///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004367/// \param Member the member declaration, which will be updated to become a
4368/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004369///
John McCall68263142009-11-18 22:49:29 +00004370/// \param Previous the set of declarations, one of which may be specialized
4371/// by this function specialization; the set will be modified to contain the
4372/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004373bool
John McCall68263142009-11-18 22:49:29 +00004374Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004375 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00004376
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004377 // Try to find the member we are instantiating.
4378 NamedDecl *Instantiation = 0;
4379 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004380 MemberSpecializationInfo *MSInfo = 0;
4381
John McCall68263142009-11-18 22:49:29 +00004382 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004383 // Nowhere to look anyway.
4384 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004385 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4386 I != E; ++I) {
4387 NamedDecl *D = (*I)->getUnderlyingDecl();
4388 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004389 if (Context.hasSameType(Function->getType(), Method->getType())) {
4390 Instantiation = Method;
4391 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004392 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004393 break;
4394 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004395 }
4396 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004397 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004398 VarDecl *PrevVar;
4399 if (Previous.isSingleResult() &&
4400 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004401 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004402 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004403 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004404 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004405 }
4406 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004407 CXXRecordDecl *PrevRecord;
4408 if (Previous.isSingleResult() &&
4409 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4410 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004411 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004412 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004413 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004414 }
4415
4416 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004417 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004418 // specializations are always out-of-line, the caller will complain about
4419 // this mismatch later.
4420 return false;
4421 }
John McCall77e8b112010-04-13 20:37:33 +00004422
4423 // If this is a friend, just bail out here before we start turning
4424 // things into explicit specializations.
4425 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4426 // Preserve instantiation information.
4427 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4428 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4429 cast<CXXMethodDecl>(InstantiatedFrom),
4430 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4431 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4432 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4433 cast<CXXRecordDecl>(InstantiatedFrom),
4434 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4435 }
4436
4437 Previous.clear();
4438 Previous.addDecl(Instantiation);
4439 return false;
4440 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004441
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004442 // Make sure that this is a specialization of a member.
4443 if (!InstantiatedFrom) {
4444 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4445 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004446 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4447 return true;
4448 }
4449
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004450 // C++ [temp.expl.spec]p6:
4451 // If a template, a member template or the member of a class template is
4452 // explicitly specialized then that spe- cialization shall be declared
4453 // before the first use of that specialization that would cause an implicit
4454 // instantiation to take place, in every translation unit in which such a
4455 // use occurs; no diagnostic is required.
4456 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004457
4458 bool SuppressNew = false;
4459 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4460 TSK_ExplicitSpecialization,
4461 Instantiation,
4462 MSInfo->getTemplateSpecializationKind(),
4463 MSInfo->getPointOfInstantiation(),
4464 SuppressNew))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004465 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004466
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004467 // Check the scope of this explicit specialization.
4468 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004469 InstantiatedFrom,
4470 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004471 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004472 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004473
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004474 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004475 // the original declaration to note that it is an explicit specialization
4476 // (if it was previously an implicit instantiation). This latter step
4477 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004478 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004479 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4480 if (InstantiationFunction->getTemplateSpecializationKind() ==
4481 TSK_ImplicitInstantiation) {
4482 InstantiationFunction->setTemplateSpecializationKind(
4483 TSK_ExplicitSpecialization);
4484 InstantiationFunction->setLocation(Member->getLocation());
4485 }
4486
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004487 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4488 cast<CXXMethodDecl>(InstantiatedFrom),
4489 TSK_ExplicitSpecialization);
4490 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004491 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4492 if (InstantiationVar->getTemplateSpecializationKind() ==
4493 TSK_ImplicitInstantiation) {
4494 InstantiationVar->setTemplateSpecializationKind(
4495 TSK_ExplicitSpecialization);
4496 InstantiationVar->setLocation(Member->getLocation());
4497 }
4498
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004499 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4500 cast<VarDecl>(InstantiatedFrom),
4501 TSK_ExplicitSpecialization);
4502 } else {
4503 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004504 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4505 if (InstantiationClass->getTemplateSpecializationKind() ==
4506 TSK_ImplicitInstantiation) {
4507 InstantiationClass->setTemplateSpecializationKind(
4508 TSK_ExplicitSpecialization);
4509 InstantiationClass->setLocation(Member->getLocation());
4510 }
4511
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004512 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004513 cast<CXXRecordDecl>(InstantiatedFrom),
4514 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004515 }
4516
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004517 // Save the caller the trouble of having to figure out which declaration
4518 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004519 Previous.clear();
4520 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004521 return false;
4522}
4523
Douglas Gregor558c0322009-10-14 23:41:34 +00004524/// \brief Check the scope of an explicit instantiation.
4525static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4526 SourceLocation InstLoc,
4527 bool WasQualifiedName) {
4528 DeclContext *ExpectedContext
4529 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4530 DeclContext *CurContext = S.CurContext->getLookupContext();
4531
4532 // C++0x [temp.explicit]p2:
4533 // An explicit instantiation shall appear in an enclosing namespace of its
4534 // template.
4535 //
4536 // This is DR275, which we do not retroactively apply to C++98/03.
4537 if (S.getLangOptions().CPlusPlus0x &&
4538 !CurContext->Encloses(ExpectedContext)) {
4539 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregor2166beb2010-05-11 17:39:34 +00004540 S.Diag(InstLoc,
4541 S.getLangOptions().CPlusPlus0x?
4542 diag::err_explicit_instantiation_out_of_scope
4543 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004544 << D << NS;
4545 else
Douglas Gregor2166beb2010-05-11 17:39:34 +00004546 S.Diag(InstLoc,
4547 S.getLangOptions().CPlusPlus0x?
4548 diag::err_explicit_instantiation_must_be_global
4549 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004550 << D;
4551 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4552 return;
4553 }
4554
4555 // C++0x [temp.explicit]p2:
4556 // If the name declared in the explicit instantiation is an unqualified
4557 // name, the explicit instantiation shall appear in the namespace where
4558 // its template is declared or, if that namespace is inline (7.3.1), any
4559 // namespace from its enclosing namespace set.
4560 if (WasQualifiedName)
4561 return;
4562
4563 if (CurContext->Equals(ExpectedContext))
4564 return;
4565
Douglas Gregor2166beb2010-05-11 17:39:34 +00004566 S.Diag(InstLoc,
4567 S.getLangOptions().CPlusPlus0x?
4568 diag::err_explicit_instantiation_unqualified_wrong_namespace
4569 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004570 << D << ExpectedContext;
4571 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4572}
4573
4574/// \brief Determine whether the given scope specifier has a template-id in it.
4575static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4576 if (!SS.isSet())
4577 return false;
4578
4579 // C++0x [temp.explicit]p2:
4580 // If the explicit instantiation is for a member function, a member class
4581 // or a static data member of a class template specialization, the name of
4582 // the class template specialization in the qualified-id for the member
4583 // name shall be a simple-template-id.
4584 //
4585 // C++98 has the same restriction, just worded differently.
4586 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4587 NNS; NNS = NNS->getPrefix())
4588 if (Type *T = NNS->getAsType())
4589 if (isa<TemplateSpecializationType>(T))
4590 return true;
4591
4592 return false;
4593}
4594
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004595// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004596Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004597Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004598 SourceLocation ExternLoc,
4599 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004600 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004601 SourceLocation KWLoc,
4602 const CXXScopeSpec &SS,
4603 TemplateTy TemplateD,
4604 SourceLocation TemplateNameLoc,
4605 SourceLocation LAngleLoc,
4606 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004607 SourceLocation RAngleLoc,
4608 AttributeList *Attr) {
4609 // Find the class template we're specializing
4610 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004611 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004612 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4613
4614 // Check that the specialization uses the same tag kind as the
4615 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004616 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4617 assert(Kind != TTK_Enum &&
4618 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004619 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004620 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004621 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004622 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004623 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004624 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004625 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004626 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004627 diag::note_previous_use);
4628 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4629 }
4630
Douglas Gregor558c0322009-10-14 23:41:34 +00004631 // C++0x [temp.explicit]p2:
4632 // There are two forms of explicit instantiation: an explicit instantiation
4633 // definition and an explicit instantiation declaration. An explicit
4634 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00004635 TemplateSpecializationKind TSK
4636 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4637 : TSK_ExplicitInstantiationDeclaration;
4638
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004639 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004640 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004641 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004642
4643 // Check that the template argument list is well-formed for this
4644 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00004645 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4646 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00004647 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4648 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004649 return true;
4650
Mike Stump1eb44332009-09-09 15:08:12 +00004651 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004652 ClassTemplate->getTemplateParameters()->size()) &&
4653 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004654
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004655 // Find the class template specialization declaration that
4656 // corresponds to these arguments.
4657 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00004658 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00004659 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00004660 Converted.flatSize(),
4661 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004662 void *InsertPos = 0;
4663 ClassTemplateSpecializationDecl *PrevDecl
4664 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4665
Douglas Gregord5cb8762009-10-07 00:13:32 +00004666 // C++0x [temp.explicit]p2:
4667 // [...] An explicit instantiation shall appear in an enclosing
4668 // namespace of its template. [...]
4669 //
4670 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004671 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4672 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00004673
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004674 ClassTemplateSpecializationDecl *Specialization = 0;
4675
Douglas Gregord78f5982009-11-25 06:01:46 +00004676 bool ReusedDecl = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004677 if (PrevDecl) {
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004678 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004679 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004680 PrevDecl,
4681 PrevDecl->getSpecializationKind(),
4682 PrevDecl->getPointOfInstantiation(),
4683 SuppressNew))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004684 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004685
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004686 if (SuppressNew)
Douglas Gregor52604ab2009-09-11 21:19:12 +00004687 return DeclPtrTy::make(PrevDecl);
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004688
Douglas Gregor52604ab2009-09-11 21:19:12 +00004689 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4690 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4691 // Since the only prior class template specialization with these
4692 // arguments was referenced but not declared, reuse that
4693 // declaration node as our own, updating its source location to
4694 // reflect our new declaration.
4695 Specialization = PrevDecl;
4696 Specialization->setLocation(TemplateNameLoc);
4697 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00004698 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00004699 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004700 }
Douglas Gregor52604ab2009-09-11 21:19:12 +00004701
4702 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004703 // Create a new class template specialization declaration node for
4704 // this explicit specialization.
4705 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00004706 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004707 ClassTemplate->getDeclContext(),
4708 TemplateNameLoc,
4709 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00004710 Converted, PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004711 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004712
Douglas Gregor52604ab2009-09-11 21:19:12 +00004713 if (PrevDecl) {
4714 // Remove the previous declaration from the folding set, since we want
4715 // to introduce a new declaration.
4716 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4717 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4718 }
4719
4720 // Insert the new specialization.
4721 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004722 }
4723
4724 // Build the fully-sugared type for this explicit instantiation as
4725 // the user wrote in the explicit instantiation itself. This means
4726 // that we'll pretty-print the type retrieved from the
4727 // specialization's declaration the way that the user actually wrote
4728 // the explicit instantiation, rather than formatting the name based
4729 // on the "canonical" representation used to store the template
4730 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004731 TypeSourceInfo *WrittenTy
4732 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4733 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004734 Context.getTypeDeclType(Specialization));
4735 Specialization->setTypeAsWritten(WrittenTy);
4736 TemplateArgsIn.release();
4737
Douglas Gregord78f5982009-11-25 06:01:46 +00004738 if (!ReusedDecl) {
4739 // Add the explicit instantiation into its lexical context. However,
4740 // since explicit instantiations are never found by name lookup, we
4741 // just put it into the declaration context directly.
4742 Specialization->setLexicalDeclContext(CurContext);
4743 CurContext->addDecl(Specialization);
4744 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004745
4746 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004747 // A definition of a class template or class member template
4748 // shall be in scope at the point of the explicit instantiation of
4749 // the class template or class member template.
4750 //
4751 // This check comes when we actually try to perform the
4752 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004753 ClassTemplateSpecializationDecl *Def
4754 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004755 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004756 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004757 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004758 else if (TSK == TSK_ExplicitInstantiationDefinition)
4759 MarkVTableUsed(TemplateNameLoc, Specialization, true);
4760
Douglas Gregor0d035142009-10-27 18:42:08 +00004761 // Instantiate the members of this class template specialization.
4762 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004763 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004764 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00004765 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4766
4767 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4768 // TSK_ExplicitInstantiationDefinition
4769 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4770 TSK == TSK_ExplicitInstantiationDefinition)
4771 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004772
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004773 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004774 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004775
4776 return DeclPtrTy::make(Specialization);
4777}
4778
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004779// Explicit instantiation of a member class of a class template.
4780Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004781Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004782 SourceLocation ExternLoc,
4783 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004784 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004785 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004786 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004787 IdentifierInfo *Name,
4788 SourceLocation NameLoc,
4789 AttributeList *Attr) {
4790
Douglas Gregor402abb52009-05-28 23:31:59 +00004791 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004792 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00004793 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004794 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00004795 MultiTemplateParamsArg(*this, 0, 0),
4796 Owned, IsDependent);
4797 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4798
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004799 if (!TagD)
4800 return true;
4801
4802 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4803 if (Tag->isEnum()) {
4804 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4805 << Context.getTypeDeclType(Tag);
4806 return true;
4807 }
4808
Douglas Gregord0c87372009-05-27 17:30:49 +00004809 if (Tag->isInvalidDecl())
4810 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004811
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004812 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4813 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4814 if (!Pattern) {
4815 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4816 << Context.getTypeDeclType(Record);
4817 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4818 return true;
4819 }
4820
Douglas Gregor558c0322009-10-14 23:41:34 +00004821 // C++0x [temp.explicit]p2:
4822 // If the explicit instantiation is for a class or member class, the
4823 // elaborated-type-specifier in the declaration shall include a
4824 // simple-template-id.
4825 //
4826 // C++98 has the same restriction, just worded differently.
4827 if (!ScopeSpecifierHasTemplateId(SS))
4828 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4829 << Record << SS.getRange();
4830
4831 // C++0x [temp.explicit]p2:
4832 // There are two forms of explicit instantiation: an explicit instantiation
4833 // definition and an explicit instantiation declaration. An explicit
4834 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004835 TemplateSpecializationKind TSK
4836 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4837 : TSK_ExplicitInstantiationDeclaration;
4838
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004839 // C++0x [temp.explicit]p2:
4840 // [...] An explicit instantiation shall appear in an enclosing
4841 // namespace of its template. [...]
4842 //
4843 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004844 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004845
4846 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004847 CXXRecordDecl *PrevDecl
4848 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00004849 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00004850 PrevDecl = Record;
4851 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004852 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4853 bool SuppressNew = false;
4854 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004855 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004856 PrevDecl,
4857 MSInfo->getTemplateSpecializationKind(),
4858 MSInfo->getPointOfInstantiation(),
4859 SuppressNew))
4860 return true;
4861 if (SuppressNew)
4862 return TagD;
4863 }
4864
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004865 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00004866 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004867 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004868 // C++ [temp.explicit]p3:
4869 // A definition of a member class of a class template shall be in scope
4870 // at the point of an explicit instantiation of the member class.
4871 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00004872 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004873 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004874 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4875 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004876 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4877 << Pattern;
4878 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004879 } else {
4880 if (InstantiateClass(NameLoc, Record, Def,
4881 getTemplateInstantiationArgs(Record),
4882 TSK))
4883 return true;
4884
Douglas Gregor952b0172010-02-11 01:04:33 +00004885 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00004886 if (!RecordDef)
4887 return true;
4888 }
4889 }
4890
4891 // Instantiate all of the members of the class.
4892 InstantiateClassMembers(NameLoc, RecordDef,
4893 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004894
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004895 if (TSK == TSK_ExplicitInstantiationDefinition)
4896 MarkVTableUsed(NameLoc, RecordDef, true);
4897
Mike Stump390b4cc2009-05-16 07:39:55 +00004898 // FIXME: We don't have any representation for explicit instantiations of
4899 // member classes. Such a representation is not needed for compilation, but it
4900 // should be available for clients that want to see all of the declarations in
4901 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004902 return TagD;
4903}
4904
Douglas Gregord5a423b2009-09-25 18:43:00 +00004905Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4906 SourceLocation ExternLoc,
4907 SourceLocation TemplateLoc,
4908 Declarator &D) {
4909 // Explicit instantiations always require a name.
4910 DeclarationName Name = GetNameForDeclarator(D);
4911 if (!Name) {
4912 if (!D.isInvalidType())
4913 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4914 diag::err_explicit_instantiation_requires_name)
4915 << D.getDeclSpec().getSourceRange()
4916 << D.getSourceRange();
4917
4918 return true;
4919 }
4920
4921 // The scope passed in may not be a decl scope. Zip up the scope tree until
4922 // we find one that is.
4923 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4924 (S->getFlags() & Scope::TemplateParamScope) != 0)
4925 S = S->getParent();
4926
4927 // Determine the type of the declaration.
4928 QualType R = GetTypeForDeclarator(D, S, 0);
4929 if (R.isNull())
4930 return true;
4931
4932 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4933 // Cannot explicitly instantiate a typedef.
4934 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4935 << Name;
4936 return true;
4937 }
4938
Douglas Gregor663b5a02009-10-14 20:14:33 +00004939 // C++0x [temp.explicit]p1:
4940 // [...] An explicit instantiation of a function template shall not use the
4941 // inline or constexpr specifiers.
4942 // Presumably, this also applies to member functions of class templates as
4943 // well.
4944 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4945 Diag(D.getDeclSpec().getInlineSpecLoc(),
4946 diag::err_explicit_instantiation_inline)
Douglas Gregor849b2432010-03-31 17:46:05 +00004947 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00004948
4949 // FIXME: check for constexpr specifier.
4950
Douglas Gregor558c0322009-10-14 23:41:34 +00004951 // C++0x [temp.explicit]p2:
4952 // There are two forms of explicit instantiation: an explicit instantiation
4953 // definition and an explicit instantiation declaration. An explicit
4954 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00004955 TemplateSpecializationKind TSK
4956 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4957 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00004958
John McCalla24dc2e2009-11-17 02:14:36 +00004959 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4960 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004961
4962 if (!R->isFunctionType()) {
4963 // C++ [temp.explicit]p1:
4964 // A [...] static data member of a class template can be explicitly
4965 // instantiated from the member definition associated with its class
4966 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00004967 if (Previous.isAmbiguous())
4968 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004969
John McCall1bcee0a2009-12-02 08:25:40 +00004970 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004971 if (!Prev || !Prev->isStaticDataMember()) {
4972 // We expect to see a data data member here.
4973 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4974 << Name;
4975 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4976 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00004977 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004978 return true;
4979 }
4980
4981 if (!Prev->getInstantiatedFromStaticDataMember()) {
4982 // FIXME: Check for explicit specialization?
4983 Diag(D.getIdentifierLoc(),
4984 diag::err_explicit_instantiation_data_member_not_instantiated)
4985 << Prev;
4986 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4987 // FIXME: Can we provide a note showing where this was declared?
4988 return true;
4989 }
4990
Douglas Gregor558c0322009-10-14 23:41:34 +00004991 // C++0x [temp.explicit]p2:
4992 // If the explicit instantiation is for a member function, a member class
4993 // or a static data member of a class template specialization, the name of
4994 // the class template specialization in the qualified-id for the member
4995 // name shall be a simple-template-id.
4996 //
4997 // C++98 has the same restriction, just worded differently.
4998 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4999 Diag(D.getIdentifierLoc(),
5000 diag::err_explicit_instantiation_without_qualified_id)
5001 << Prev << D.getCXXScopeSpec().getRange();
5002
5003 // Check the scope of this explicit instantiation.
5004 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5005
Douglas Gregor454885e2009-10-15 15:54:05 +00005006 // Verify that it is okay to explicitly instantiate here.
5007 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5008 assert(MSInfo && "Missing static data member specialization info?");
5009 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005010 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00005011 MSInfo->getTemplateSpecializationKind(),
5012 MSInfo->getPointOfInstantiation(),
5013 SuppressNew))
5014 return true;
5015 if (SuppressNew)
5016 return DeclPtrTy();
5017
Douglas Gregord5a423b2009-09-25 18:43:00 +00005018 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005019 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005020 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00005021 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
5022 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005023
5024 // FIXME: Create an ExplicitInstantiation node?
5025 return DeclPtrTy();
5026 }
5027
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005028 // If the declarator is a template-id, translate the parser's template
5029 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00005030 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00005031 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005032 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5033 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00005034 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5035 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00005036 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5037 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00005038 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00005039 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00005040 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00005041 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00005042 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005043
Douglas Gregord5a423b2009-09-25 18:43:00 +00005044 // C++ [temp.explicit]p1:
5045 // A [...] function [...] can be explicitly instantiated from its template.
5046 // A member function [...] of a class template can be explicitly
5047 // instantiated from the member definition associated with its class
5048 // template.
John McCallc373d482010-01-27 01:50:18 +00005049 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005050 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5051 P != PEnd; ++P) {
5052 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00005053 if (!HasExplicitTemplateArgs) {
5054 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5055 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5056 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00005057
John McCallc373d482010-01-27 01:50:18 +00005058 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00005059 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5060 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00005061 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00005062 }
5063 }
5064
5065 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5066 if (!FunTmpl)
5067 continue;
5068
John McCall5769d612010-02-08 23:07:23 +00005069 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005070 FunctionDecl *Specialization = 0;
5071 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00005072 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00005073 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00005074 R, Specialization, Info)) {
5075 // FIXME: Keep track of almost-matches?
5076 (void)TDK;
5077 continue;
5078 }
5079
John McCallc373d482010-01-27 01:50:18 +00005080 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005081 }
5082
5083 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005084 UnresolvedSetIterator Result
5085 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregord5a423b2009-09-25 18:43:00 +00005086 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005087 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5088 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5089 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00005090
John McCallc373d482010-01-27 01:50:18 +00005091 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00005092 return true;
John McCallc373d482010-01-27 01:50:18 +00005093
5094 // Ignore access control bits, we don't need them for redeclaration checking.
5095 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005096
Douglas Gregor0a897e32009-10-15 17:21:20 +00005097 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005098 Diag(D.getIdentifierLoc(),
5099 diag::err_explicit_instantiation_member_function_not_instantiated)
5100 << Specialization
5101 << (Specialization->getTemplateSpecializationKind() ==
5102 TSK_ExplicitSpecialization);
5103 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5104 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005105 }
Douglas Gregor558c0322009-10-14 23:41:34 +00005106
Douglas Gregor0a897e32009-10-15 17:21:20 +00005107 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00005108 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5109 PrevDecl = Specialization;
5110
Douglas Gregor0a897e32009-10-15 17:21:20 +00005111 if (PrevDecl) {
5112 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005113 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00005114 PrevDecl,
5115 PrevDecl->getTemplateSpecializationKind(),
5116 PrevDecl->getPointOfInstantiation(),
5117 SuppressNew))
5118 return true;
5119
5120 // FIXME: We may still want to build some representation of this
5121 // explicit specialization.
5122 if (SuppressNew)
5123 return DeclPtrTy();
5124 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00005125
5126 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00005127
5128 if (TSK == TSK_ExplicitInstantiationDefinition)
5129 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5130 false, /*DefinitionRequired=*/true);
Douglas Gregor0a897e32009-10-15 17:21:20 +00005131
Douglas Gregor558c0322009-10-14 23:41:34 +00005132 // C++0x [temp.explicit]p2:
5133 // If the explicit instantiation is for a member function, a member class
5134 // or a static data member of a class template specialization, the name of
5135 // the class template specialization in the qualified-id for the member
5136 // name shall be a simple-template-id.
5137 //
5138 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005139 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005140 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00005141 D.getCXXScopeSpec().isSet() &&
5142 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5143 Diag(D.getIdentifierLoc(),
5144 diag::err_explicit_instantiation_without_qualified_id)
5145 << Specialization << D.getCXXScopeSpec().getRange();
5146
5147 CheckExplicitInstantiationScope(*this,
5148 FunTmpl? (NamedDecl *)FunTmpl
5149 : Specialization->getInstantiatedFromMemberFunction(),
5150 D.getIdentifierLoc(),
5151 D.getCXXScopeSpec().isSet());
5152
Douglas Gregord5a423b2009-09-25 18:43:00 +00005153 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5154 return DeclPtrTy();
5155}
5156
Douglas Gregord57959a2009-03-27 23:10:48 +00005157Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00005158Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5159 const CXXScopeSpec &SS, IdentifierInfo *Name,
5160 SourceLocation TagLoc, SourceLocation NameLoc) {
5161 // This has to hold, because SS is expected to be defined.
5162 assert(Name && "Expected a name in a dependent tag");
5163
5164 NestedNameSpecifier *NNS
5165 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5166 if (!NNS)
5167 return true;
5168
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005169 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005170
Douglas Gregor48c89f42010-04-24 16:38:41 +00005171 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5172 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005173 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00005174 return true;
5175 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005176
5177 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5178 return Context.getDependentNameType(Kwd, NNS, Name).getAsOpaquePtr();
John McCallc4e70192009-09-11 04:59:25 +00005179}
5180
John McCall63b43852010-04-29 23:50:39 +00005181static void FillTypeLoc(DependentNameTypeLoc TL,
5182 SourceLocation TypenameLoc,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005183 SourceRange QualifierRange,
5184 SourceLocation NameLoc) {
5185 TL.setKeywordLoc(TypenameLoc);
5186 TL.setQualifierRange(QualifierRange);
5187 TL.setNameLoc(NameLoc);
John McCall63b43852010-04-29 23:50:39 +00005188}
5189
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005190static void FillTypeLoc(ElaboratedTypeLoc TL,
John McCall63b43852010-04-29 23:50:39 +00005191 SourceLocation TypenameLoc,
5192 SourceRange QualifierRange) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005193 // FIXME: inner locations.
5194 TL.setKeywordLoc(TypenameLoc);
5195 TL.setQualifierRange(QualifierRange);
John McCall63b43852010-04-29 23:50:39 +00005196}
5197
John McCallc4e70192009-09-11 04:59:25 +00005198Sema::TypeResult
Douglas Gregord57959a2009-03-27 23:10:48 +00005199Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5200 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005201 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00005202 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5203 if (!NNS)
5204 return true;
5205
Douglas Gregor107de902010-04-24 15:35:55 +00005206 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005207 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00005208 if (T.isNull())
5209 return true;
John McCall63b43852010-04-29 23:50:39 +00005210
5211 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5212 if (isa<DependentNameType>(T)) {
5213 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
5214 // FIXME: fill inner type loc
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005215 FillTypeLoc(TL, TypenameLoc, SS.getRange(), IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005216 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005217 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall63b43852010-04-29 23:50:39 +00005218 // FIXME: fill inner type loc
5219 FillTypeLoc(TL, TypenameLoc, SS.getRange());
5220 }
5221
5222 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregord57959a2009-03-27 23:10:48 +00005223}
5224
Douglas Gregor17343172009-04-01 00:28:59 +00005225Sema::TypeResult
5226Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5227 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005228 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005229 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00005230 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +00005231 const TemplateSpecializationType *TemplateId
John McCall183700f2009-09-21 23:43:11 +00005232 = T->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00005233 assert(TemplateId && "Expected a template specialization type");
5234
Douglas Gregor6946baf2009-09-02 13:05:45 +00005235 if (computeDeclContext(SS, false)) {
5236 // If we can compute a declaration context, then the "typename"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005237 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor6946baf2009-09-02 13:05:45 +00005238 // track of the nested-name-specifier.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005239 T = Context.getElaboratedType(ETK_Typename, NNS, T);
John McCall63b43852010-04-29 23:50:39 +00005240 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005241 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall63b43852010-04-29 23:50:39 +00005242 // FIXME: fill inner type loc
5243 FillTypeLoc(TL, TypenameLoc, SS.getRange());
5244 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor6946baf2009-09-02 13:05:45 +00005245 }
Mike Stump1eb44332009-09-09 15:08:12 +00005246
John McCall63b43852010-04-29 23:50:39 +00005247 T = Context.getDependentNameType(ETK_Typename, NNS, TemplateId);
5248 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5249 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
5250 // FIXME: fill inner type loc
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005251 FillTypeLoc(TL, TypenameLoc, SS.getRange(), TemplateLoc);
John McCall63b43852010-04-29 23:50:39 +00005252 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00005253}
5254
Douglas Gregord57959a2009-03-27 23:10:48 +00005255/// \brief Build the type that describes a C++ typename specifier,
5256/// e.g., "typename T::type".
5257QualType
Douglas Gregor107de902010-04-24 15:35:55 +00005258Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5259 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005260 SourceLocation KeywordLoc, SourceRange NNSRange,
5261 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00005262 CXXScopeSpec SS;
5263 SS.setScopeRep(NNS);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005264 SS.setRange(NNSRange);
Douglas Gregord57959a2009-03-27 23:10:48 +00005265
John McCall77bb1aa2010-05-01 00:40:08 +00005266 DeclContext *Ctx = computeDeclContext(SS);
5267 if (!Ctx) {
5268 // If the nested-name-specifier is dependent and couldn't be
5269 // resolved to a type, build a typename type.
5270 assert(NNS->isDependent());
5271 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00005272 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005273
John McCall77bb1aa2010-05-01 00:40:08 +00005274 // If the nested-name-specifier refers to the current instantiation,
5275 // the "typename" keyword itself is superfluous. In C++03, the
5276 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5277 // allows such extraneous "typename" keywords, and we retroactively
5278 // apply this DR to C++03 code. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00005279
John McCall77bb1aa2010-05-01 00:40:08 +00005280 if (RequireCompleteDeclContext(SS, Ctx))
5281 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00005282
5283 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005284 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005285 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005286 unsigned DiagID = 0;
5287 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005288 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005289 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005290 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005291 break;
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005292
5293 case LookupResult::NotFoundInCurrentInstantiation:
5294 // Okay, it's a member of an unknown instantiation.
Douglas Gregor107de902010-04-24 15:35:55 +00005295 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00005296
5297 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +00005298 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005299 // We found a type. Build an ElaboratedType, since the
5300 // typename-specifier was just sugar.
5301 return Context.getElaboratedType(ETK_Typename, NNS,
5302 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00005303 }
5304
5305 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00005306 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00005307 break;
5308
John McCall7ba107a2009-11-18 02:36:19 +00005309 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005310 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00005311 return QualType();
5312
Douglas Gregord57959a2009-03-27 23:10:48 +00005313 case LookupResult::FoundOverloaded:
5314 DiagID = diag::err_typename_nested_not_type;
5315 Referenced = *Result.begin();
5316 break;
5317
John McCall6e247262009-10-10 05:48:19 +00005318 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00005319 return QualType();
5320 }
5321
5322 // If we get here, it's because name lookup did not find a
5323 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005324 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5325 IILoc);
5326 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00005327 if (Referenced)
5328 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5329 << Name;
5330 return QualType();
5331}
Douglas Gregor4a959d82009-08-06 16:20:37 +00005332
5333namespace {
5334 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00005335 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00005336 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00005337 SourceLocation Loc;
5338 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00005339
Douglas Gregor4a959d82009-08-06 16:20:37 +00005340 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00005341 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5342
Mike Stump1eb44332009-09-09 15:08:12 +00005343 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005344 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005345 DeclarationName Entity)
5346 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00005347 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00005348
5349 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00005350 /// transformed.
5351 ///
5352 /// For the purposes of type reconstruction, a type has already been
5353 /// transformed if it is NULL or if it is not dependent.
5354 bool AlreadyTransformed(QualType T) {
5355 return T.isNull() || !T->isDependentType();
5356 }
Mike Stump1eb44332009-09-09 15:08:12 +00005357
5358 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00005359 /// rebuilt.
5360 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00005361
Douglas Gregor4a959d82009-08-06 16:20:37 +00005362 /// \brief Returns the name of the entity whose type is being rebuilt.
5363 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00005364
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005365 /// \brief Sets the "base" location and entity when that
5366 /// information is known based on another transformation.
5367 void setBase(SourceLocation Loc, DeclarationName Entity) {
5368 this->Loc = Loc;
5369 this->Entity = Entity;
5370 }
5371
Douglas Gregor4a959d82009-08-06 16:20:37 +00005372 /// \brief Transforms an expression by returning the expression itself
5373 /// (an identity function).
5374 ///
5375 /// FIXME: This is completely unsafe; we will need to actually clone the
5376 /// expressions.
5377 Sema::OwningExprResult TransformExpr(Expr *E) {
Douglas Gregor895162d2010-04-30 18:55:50 +00005378 return getSema().Owned(E->Retain());
Douglas Gregor4a959d82009-08-06 16:20:37 +00005379 }
Mike Stump1eb44332009-09-09 15:08:12 +00005380
Douglas Gregor4a959d82009-08-06 16:20:37 +00005381 /// \brief Transforms a typename type by determining whether the type now
5382 /// refers to a member of the current instantiation, and then
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005383 /// type-checking and building an ElaboratedType (when possible).
5384 QualType TransformDependentNameType(TypeLocBuilder &TLB,
5385 DependentNameTypeLoc TL,
5386 QualType ObjectType);
Douglas Gregor4a959d82009-08-06 16:20:37 +00005387 };
5388}
5389
Mike Stump1eb44332009-09-09 15:08:12 +00005390QualType
Douglas Gregor4714c122010-03-31 17:34:00 +00005391CurrentInstantiationRebuilder::TransformDependentNameType(TypeLocBuilder &TLB,
5392 DependentNameTypeLoc TL,
Douglas Gregor124b8782010-02-16 19:09:40 +00005393 QualType ObjectType) {
Douglas Gregor4714c122010-03-31 17:34:00 +00005394 DependentNameType *T = TL.getTypePtr();
John McCalla2becad2009-10-21 00:40:46 +00005395
Douglas Gregor4a959d82009-08-06 16:20:37 +00005396 NestedNameSpecifier *NNS
5397 = TransformNestedNameSpecifier(T->getQualifier(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005398 TL.getQualifierRange(),
Douglas Gregor124b8782010-02-16 19:09:40 +00005399 ObjectType);
Douglas Gregor4a959d82009-08-06 16:20:37 +00005400 if (!NNS)
5401 return QualType();
5402
5403 // If the nested-name-specifier did not change, and we cannot compute the
5404 // context corresponding to the nested-name-specifier, then this
5405 // typename type will not change; exit early.
5406 CXXScopeSpec SS;
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005407 SS.setRange(TL.getQualifierRange());
Douglas Gregor4a959d82009-08-06 16:20:37 +00005408 SS.setScopeRep(NNS);
John McCall833ca992009-10-29 08:12:44 +00005409
5410 QualType Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00005411 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall833ca992009-10-29 08:12:44 +00005412 Result = QualType(T, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00005413
5414 // Rebuild the typename type, which will probably turn into a
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005415 // ElaboratedType.
John McCall833ca992009-10-29 08:12:44 +00005416 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005417 QualType NewTemplateId
Douglas Gregor4a959d82009-08-06 16:20:37 +00005418 = TransformType(QualType(TemplateId, 0));
5419 if (NewTemplateId.isNull())
5420 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005421
Douglas Gregor4a959d82009-08-06 16:20:37 +00005422 if (NNS == T->getQualifier() &&
5423 NewTemplateId == QualType(TemplateId, 0))
John McCall833ca992009-10-29 08:12:44 +00005424 Result = QualType(T, 0);
5425 else
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005426 Result = getDerived().RebuildDependentNameType(T->getKeyword(),
Douglas Gregor4a2023f2010-03-31 20:19:30 +00005427 NNS, NewTemplateId);
John McCall833ca992009-10-29 08:12:44 +00005428 } else
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005429 Result = getDerived().RebuildDependentNameType(T->getKeyword(), NNS,
5430 T->getIdentifier(),
5431 TL.getKeywordLoc(),
5432 TL.getQualifierRange(),
5433 TL.getNameLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00005434
Douglas Gregora50ce322010-03-07 23:26:22 +00005435 if (Result.isNull())
5436 return QualType();
5437
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005438 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
5439 QualType NamedT = ElabT->getNamedType();
5440 if (isa<TemplateSpecializationType>(NamedT)) {
5441 TemplateSpecializationTypeLoc NamedTLoc
5442 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
5443 // FIXME: fill locations
5444 NamedTLoc.initializeLocal(TL.getNameLoc());
5445 } else {
5446 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
5447 }
5448 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5449 NewTL.setKeywordLoc(TL.getKeywordLoc());
5450 NewTL.setQualifierRange(TL.getQualifierRange());
5451 }
5452 else {
5453 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
5454 NewTL.setKeywordLoc(TL.getKeywordLoc());
5455 NewTL.setQualifierRange(TL.getQualifierRange());
5456 NewTL.setNameLoc(TL.getNameLoc());
5457 }
John McCall833ca992009-10-29 08:12:44 +00005458 return Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00005459}
5460
5461/// \brief Rebuilds a type within the context of the current instantiation.
5462///
Mike Stump1eb44332009-09-09 15:08:12 +00005463/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00005464/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00005465/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00005466/// partial specialization thereof). This routine will rebuild that type now
5467/// that we have entered the declarator's scope, which may produce different
5468/// canonical types, e.g.,
5469///
5470/// \code
5471/// template<typename T>
5472/// struct X {
5473/// typedef T* pointer;
5474/// pointer data();
5475/// };
5476///
5477/// template<typename T>
5478/// typename X<T>::pointer X<T>::data() { ... }
5479/// \endcode
5480///
Douglas Gregor4714c122010-03-31 17:34:00 +00005481/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005482/// since we do not know that we can look into X<T> when we parsed the type.
5483/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005484/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00005485/// as the canonical type of T*, allowing the return types of the out-of-line
5486/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00005487TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5488 SourceLocation Loc,
5489 DeclarationName Name) {
5490 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00005491 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00005492
Douglas Gregor4a959d82009-08-06 16:20:37 +00005493 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5494 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00005495}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005496
John McCall63b43852010-04-29 23:50:39 +00005497bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5498 if (SS.isInvalid()) return true;
John McCall31f17ec2010-04-27 00:57:59 +00005499
5500 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5501 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5502 DeclarationName());
5503 NestedNameSpecifier *Rebuilt =
5504 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall63b43852010-04-29 23:50:39 +00005505 if (!Rebuilt) return true;
5506
5507 SS.setScopeRep(Rebuilt);
5508 return false;
John McCall31f17ec2010-04-27 00:57:59 +00005509}
5510
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005511/// \brief Produces a formatted string that describes the binding of
5512/// template parameters to template arguments.
5513std::string
5514Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5515 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005516 // FIXME: For variadic templates, we'll need to get the structured list.
5517 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5518 Args.flat_size());
5519}
5520
5521std::string
5522Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5523 const TemplateArgument *Args,
5524 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005525 std::string Result;
5526
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005527 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005528 return Result;
5529
5530 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005531 if (I >= NumArgs)
5532 break;
5533
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005534 if (I == 0)
5535 Result += "[with ";
5536 else
5537 Result += ", ";
5538
5539 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5540 Result += Id->getName();
5541 } else {
5542 Result += '$';
5543 Result += llvm::utostr(I);
5544 }
5545
5546 Result += " = ";
5547
5548 switch (Args[I].getKind()) {
5549 case TemplateArgument::Null:
5550 Result += "<no value>";
5551 break;
5552
5553 case TemplateArgument::Type: {
5554 std::string TypeStr;
5555 Args[I].getAsType().getAsStringInternal(TypeStr,
5556 Context.PrintingPolicy);
5557 Result += TypeStr;
5558 break;
5559 }
5560
5561 case TemplateArgument::Declaration: {
5562 bool Unnamed = true;
5563 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5564 if (ND->getDeclName()) {
5565 Unnamed = false;
5566 Result += ND->getNameAsString();
5567 }
5568 }
5569
5570 if (Unnamed) {
5571 Result += "<anonymous>";
5572 }
5573 break;
5574 }
5575
Douglas Gregor788cd062009-11-11 01:00:40 +00005576 case TemplateArgument::Template: {
5577 std::string Str;
5578 llvm::raw_string_ostream OS(Str);
5579 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5580 Result += OS.str();
5581 break;
5582 }
5583
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005584 case TemplateArgument::Integral: {
5585 Result += Args[I].getAsIntegral()->toString(10);
5586 break;
5587 }
5588
5589 case TemplateArgument::Expression: {
Douglas Gregor77e2c672010-04-29 04:55:13 +00005590 // FIXME: This is non-optimal, since we're regurgitating the
5591 // expression we were given.
5592 std::string Str;
5593 {
5594 llvm::raw_string_ostream OS(Str);
5595 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5596 Context.PrintingPolicy);
5597 }
5598 Result += Str;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005599 break;
5600 }
5601
5602 case TemplateArgument::Pack:
5603 // FIXME: Format template argument packs
5604 Result += "<template argument pack>";
5605 break;
5606 }
5607 }
5608
5609 Result += ']';
5610 return Result;
5611}