blob: 7a3e83a4979f7dc19e82c317ab089e1580e878f6 [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.
213 if (LookupCtx && RequireCompleteDeclContext(SS))
214 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());
333
John McCall2f841ba2009-12-02 03:53:29 +0000334 if (!isAddressOfOperand &&
335 isa<CXXMethodDecl>(CurContext) &&
336 cast<CXXMethodDecl>(CurContext)->isInstance()) {
337 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
338
John McCallf7a1a742009-11-24 19:00:30 +0000339 // Since the 'this' expression is synthesized, we don't need to
340 // perform the double-lookup check.
341 NamedDecl *FirstQualifierInScope = 0;
342
John McCallaa81e162009-12-01 22:10:20 +0000343 return Owned(CXXDependentScopeMemberExpr::Create(Context,
344 /*This*/ 0, ThisType,
345 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000346 /*Op*/ SourceLocation(),
347 Qualifier, SS.getRange(),
348 FirstQualifierInScope,
349 Name, NameLoc,
350 TemplateArgs));
351 }
352
353 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
354}
355
356Sema::OwningExprResult
357Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
358 DeclarationName Name,
359 SourceLocation NameLoc,
360 const TemplateArgumentListInfo *TemplateArgs) {
361 return Owned(DependentScopeDeclRefExpr::Create(Context,
362 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
363 SS.getRange(),
364 Name, NameLoc,
365 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000366}
367
Douglas Gregor72c3f312008-12-05 18:15:24 +0000368/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
369/// that the template parameter 'PrevDecl' is being shadowed by a new
370/// declaration at location Loc. Returns true to indicate that this is
371/// an error, and false otherwise.
372bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000373 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000374
375 // Microsoft Visual C++ permits template parameters to be shadowed.
376 if (getLangOptions().Microsoft)
377 return false;
378
379 // C++ [temp.local]p4:
380 // A template-parameter shall not be redeclared within its
381 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000382 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000383 << cast<NamedDecl>(PrevDecl)->getDeclName();
384 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
385 return true;
386}
387
Douglas Gregor2943aed2009-03-03 04:44:36 +0000388/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000389/// the parameter D to reference the templated declaration and return a pointer
390/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000391TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor13d2d6c2009-10-06 21:27:51 +0000392 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000393 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000394 return Temp;
395 }
396 return 0;
397}
398
Douglas Gregor788cd062009-11-11 01:00:40 +0000399static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
400 const ParsedTemplateArgument &Arg) {
401
402 switch (Arg.getKind()) {
403 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000404 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000405 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
406 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000407 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000408 return TemplateArgumentLoc(TemplateArgument(T), DI);
409 }
410
411 case ParsedTemplateArgument::NonType: {
412 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
413 return TemplateArgumentLoc(TemplateArgument(E), E);
414 }
415
416 case ParsedTemplateArgument::Template: {
417 TemplateName Template
418 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
419 return TemplateArgumentLoc(TemplateArgument(Template),
420 Arg.getScopeSpec().getRange(),
421 Arg.getLocation());
422 }
423 }
424
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000425 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000426 return TemplateArgumentLoc();
427}
428
429/// \brief Translates template arguments as provided by the parser
430/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000431void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
432 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000433 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000434 TemplateArgs.addArgument(translateTemplateArgument(*this,
435 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000436}
437
Douglas Gregor72c3f312008-12-05 18:15:24 +0000438/// ActOnTypeParameter - Called when a C++ template type parameter
439/// (e.g., "typename T") has been parsed. Typename specifies whether
440/// the keyword "typename" was used to declare the type parameter
441/// (otherwise, "class" was used), and KeyLoc is the location of the
442/// "class" or "typename" keyword. ParamName is the name of the
443/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump1eb44332009-09-09 15:08:12 +0000444/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000445/// If the type parameter has a default argument, it will be added
446/// later via ActOnTypeParameterDefault.
Mike Stump1eb44332009-09-09 15:08:12 +0000447Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson941df7d2009-06-12 19:58:00 +0000448 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000449 SourceLocation KeyLoc,
450 IdentifierInfo *ParamName,
451 SourceLocation ParamNameLoc,
452 unsigned Depth, unsigned Position) {
Mike Stump1eb44332009-09-09 15:08:12 +0000453 assert(S->isTemplateParamScope() &&
454 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000455 bool Invalid = false;
456
457 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000458 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000459 LookupOrdinaryName,
460 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000461 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000462 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000463 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000464 }
465
Douglas Gregorddc29e12009-02-06 22:42:48 +0000466 SourceLocation Loc = ParamNameLoc;
467 if (!ParamName)
468 Loc = KeyLoc;
469
Douglas Gregor72c3f312008-12-05 18:15:24 +0000470 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000471 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
472 Loc, Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000473 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000474 if (Invalid)
475 Param->setInvalidDecl();
476
477 if (ParamName) {
478 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000479 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000480 IdResolver.AddDecl(Param);
481 }
482
Chris Lattnerb28317a2009-03-28 19:18:32 +0000483 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000484}
485
Douglas Gregord684b002009-02-10 19:49:53 +0000486/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump1eb44332009-09-09 15:08:12 +0000487/// Default) to the given template type parameter (TypeParam).
488void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000489 SourceLocation EqualLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000490 SourceLocation DefaultLoc,
Douglas Gregord684b002009-02-10 19:49:53 +0000491 TypeTy *DefaultT) {
Mike Stump1eb44332009-09-09 15:08:12 +0000492 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000493 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall833ca992009-10-29 08:12:44 +0000494
John McCalla93c9342009-12-07 02:54:59 +0000495 TypeSourceInfo *DefaultTInfo;
496 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall833ca992009-10-29 08:12:44 +0000497
John McCalla93c9342009-12-07 02:54:59 +0000498 assert(DefaultTInfo && "expected source information for type");
Douglas Gregord684b002009-02-10 19:49:53 +0000499
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000500 // C++0x [temp.param]p9:
501 // A default template-argument may be specified for any kind of
Mike Stump1eb44332009-09-09 15:08:12 +0000502 // template-parameter that is not a template parameter pack.
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000503 if (Parm->isParameterPack()) {
504 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000505 return;
506 }
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Douglas Gregord684b002009-02-10 19:49:53 +0000508 // C++ [temp.param]p14:
509 // A template-parameter shall not be used in its own default argument.
510 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Douglas Gregord684b002009-02-10 19:49:53 +0000512 // Check the template argument itself.
John McCalla93c9342009-12-07 02:54:59 +0000513 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000514 Parm->setInvalidDecl();
515 return;
516 }
517
John McCalla93c9342009-12-07 02:54:59 +0000518 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000519}
520
Douglas Gregor2943aed2009-03-03 04:44:36 +0000521/// \brief Check that the type of a non-type template parameter is
522/// well-formed.
523///
524/// \returns the (possibly-promoted) parameter type if valid;
525/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000526QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000527Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
528 // C++ [temp.param]p4:
529 //
530 // A non-type template-parameter shall have one of the following
531 // (optionally cv-qualified) types:
532 //
533 // -- integral or enumeration type,
534 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000535 // -- pointer to object or pointer to function,
536 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000537 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
538 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000539 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000540 T->isReferenceType() ||
541 // -- pointer to member.
542 T->isMemberPointerType() ||
543 // If T is a dependent type, we can't do the check now, so we
544 // assume that it is well-formed.
545 T->isDependentType())
546 return T;
547 // C++ [temp.param]p8:
548 //
549 // A non-type template-parameter of type "array of T" or
550 // "function returning T" is adjusted to be of type "pointer to
551 // T" or "pointer to function returning T", respectively.
552 else if (T->isArrayType())
553 // FIXME: Keep the type prior to promotion?
554 return Context.getArrayDecayedType(T);
555 else if (T->isFunctionType())
556 // FIXME: Keep the type prior to promotion?
557 return Context.getPointerType(T);
558
559 Diag(Loc, diag::err_template_nontype_parm_bad_type)
560 << T;
561
562 return QualType();
563}
564
Douglas Gregor72c3f312008-12-05 18:15:24 +0000565/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
566/// template parameter (e.g., "int Size" in "template<int Size>
567/// class Array") has been parsed. S is the current scope and D is
568/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000569Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump1eb44332009-09-09 15:08:12 +0000570 unsigned Depth,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000571 unsigned Position) {
John McCalla93c9342009-12-07 02:54:59 +0000572 TypeSourceInfo *TInfo = 0;
573 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000574
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000575 assert(S->isTemplateParamScope() &&
576 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000577 bool Invalid = false;
578
579 IdentifierInfo *ParamName = D.getIdentifier();
580 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000581 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000582 LookupOrdinaryName,
583 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000584 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000585 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000586 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000587 }
588
Douglas Gregor2943aed2009-03-03 04:44:36 +0000589 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000590 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000591 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000592 Invalid = true;
593 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000594
Douglas Gregor72c3f312008-12-05 18:15:24 +0000595 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000596 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
597 D.getIdentifierLoc(),
John McCalla93c9342009-12-07 02:54:59 +0000598 Depth, Position, ParamName, T, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000599 if (Invalid)
600 Param->setInvalidDecl();
601
602 if (D.getIdentifier()) {
603 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000604 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000605 IdResolver.AddDecl(Param);
606 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000607 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000608}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000609
Douglas Gregord684b002009-02-10 19:49:53 +0000610/// \brief Adds a default argument to the given non-type template
611/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000612void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000613 SourceLocation EqualLoc,
614 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000615 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000616 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000617 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Douglas Gregord684b002009-02-10 19:49:53 +0000619 // C++ [temp.param]p14:
620 // A template-parameter shall not be used in its own default argument.
621 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Douglas Gregord684b002009-02-10 19:49:53 +0000623 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000624 TemplateArgument Converted;
625 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
626 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000627 TemplateParm->setInvalidDecl();
628 return;
629 }
630
Anders Carlssone9146f22009-05-01 19:49:17 +0000631 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000632}
633
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000634
635/// ActOnTemplateTemplateParameter - Called when a C++ template template
636/// parameter (e.g. T in template <template <typename> class T> class array)
637/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000638Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
639 SourceLocation TmpLoc,
640 TemplateParamsTy *Params,
641 IdentifierInfo *Name,
642 SourceLocation NameLoc,
643 unsigned Depth,
Mike Stump1eb44332009-09-09 15:08:12 +0000644 unsigned Position) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000645 assert(S->isTemplateParamScope() &&
646 "Template template parameter not in template parameter scope!");
647
648 // Construct the parameter object.
649 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000650 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
651 TmpLoc, Depth, Position, Name,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000652 (TemplateParameterList*)Params);
653
654 // Make sure the parameter is valid.
655 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
656 // do anything yet. However, if the template parameter list or (eventual)
657 // default value is ever invalidated, that will propagate here.
658 bool Invalid = false;
659 if (Invalid) {
660 Param->setInvalidDecl();
661 }
662
663 // If the tt-param has a name, then link the identifier into the scope
664 // and lookup mechanisms.
665 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000666 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000667 IdResolver.AddDecl(Param);
668 }
669
Chris Lattnerb28317a2009-03-28 19:18:32 +0000670 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000671}
672
Douglas Gregord684b002009-02-10 19:49:53 +0000673/// \brief Adds a default argument to the given template template
674/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000675void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000676 SourceLocation EqualLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +0000677 const ParsedTemplateArgument &Default) {
Mike Stump1eb44332009-09-09 15:08:12 +0000678 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000679 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor788cd062009-11-11 01:00:40 +0000680
Douglas Gregord684b002009-02-10 19:49:53 +0000681 // C++ [temp.param]p14:
682 // A template-parameter shall not be used in its own default argument.
683 // FIXME: Implement this check! Needs a recursive walk over the types.
684
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000685 // Check only that we have a template template argument. We don't want to
686 // try to check well-formedness now, because our template template parameter
687 // might have dependent types in its template parameters, which we wouldn't
688 // be able to match now.
689 //
690 // If none of the template template parameter's template arguments mention
691 // other template parameters, we could actually perform more checking here.
692 // However, it isn't worth doing.
Douglas Gregor788cd062009-11-11 01:00:40 +0000693 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000694 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
695 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
696 << DefaultArg.getSourceRange();
Douglas Gregord684b002009-02-10 19:49:53 +0000697 return;
698 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000699
Douglas Gregor788cd062009-11-11 01:00:40 +0000700 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregord684b002009-02-10 19:49:53 +0000701}
702
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000703/// ActOnTemplateParameterList - Builds a TemplateParameterList that
704/// contains the template parameters in Params/NumParams.
705Sema::TemplateParamsTy *
706Sema::ActOnTemplateParameterList(unsigned Depth,
707 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000708 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000709 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000710 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000711 SourceLocation RAngleLoc) {
712 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000713 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000714
Douglas Gregorddc29e12009-02-06 22:42:48 +0000715 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000716 (NamedDecl**)Params, NumParams,
717 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000718}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000719
John McCallb6217662010-03-15 10:12:16 +0000720static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
721 if (SS.isSet())
722 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
723 SS.getRange());
724}
725
Douglas Gregor212e81c2009-03-25 00:13:59 +0000726Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000727Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000728 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000729 IdentifierInfo *Name, SourceLocation NameLoc,
730 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000731 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000732 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000733 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000734 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000735 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000736 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000737
738 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000739 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000740 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000741
John McCall05b23ea2009-09-14 21:59:20 +0000742 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
743 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000744
745 // There is no such thing as an unnamed class template.
746 if (!Name) {
747 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000748 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000749 }
750
751 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000752 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000753 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000754 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000755 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregorf0510d42009-10-12 23:11:44 +0000756 if (RequireCompleteDeclContext(SS))
757 return true;
758
Douglas Gregor05396e22009-08-25 17:23:04 +0000759 SemanticContext = computeDeclContext(SS, true);
760 if (!SemanticContext) {
761 // FIXME: Produce a reasonable diagnostic here
762 return true;
763 }
Mike Stump1eb44332009-09-09 15:08:12 +0000764
John McCalla24dc2e2009-11-17 02:14:36 +0000765 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000766 } else {
767 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000768 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000769 }
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Douglas Gregor57265e32010-04-12 16:00:01 +0000771 if (Previous.isAmbiguous())
772 return true;
773
Douglas Gregorddc29e12009-02-06 22:42:48 +0000774 NamedDecl *PrevDecl = 0;
775 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000776 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000777
Douglas Gregorddc29e12009-02-06 22:42:48 +0000778 // If there is a previous declaration with the same name, check
779 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000780 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000781 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000782
783 // We may have found the injected-class-name of a class template,
784 // class template partial specialization, or class template specialization.
785 // In these cases, grab the template that is being defined or specialized.
786 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
787 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
788 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
789 PrevClassTemplate
790 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
791 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
792 PrevClassTemplate
793 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
794 ->getSpecializedTemplate();
795 }
796 }
797
John McCall65c49462009-12-18 11:25:59 +0000798 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000799 // C++ [namespace.memdef]p3:
800 // [...] When looking for a prior declaration of a class or a function
801 // declared as a friend, and when the name of the friend class or
802 // function is neither a qualified name nor a template-id, scopes outside
803 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000804 if (!SS.isSet()) {
805 DeclContext *OutermostContext = CurContext;
806 while (!OutermostContext->isFileContext())
807 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000808
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000809 if (PrevDecl &&
810 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
811 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
812 SemanticContext = PrevDecl->getDeclContext();
813 } else {
814 // Declarations in outer scopes don't matter. However, the outermost
815 // context we computed is the semantic context for our new
816 // declaration.
817 PrevDecl = PrevClassTemplate = 0;
818 SemanticContext = OutermostContext;
819 }
John McCalle129d442009-12-17 23:21:11 +0000820 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000821
John McCalle129d442009-12-17 23:21:11 +0000822 if (CurContext->isDependentContext()) {
823 // If this is a dependent context, we don't want to link the friend
824 // class template to the template in scope, because that would perform
825 // checking of the template parameter lists that can't be performed
826 // until the outer context is instantiated.
827 PrevDecl = PrevClassTemplate = 0;
828 }
829 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
830 PrevDecl = PrevClassTemplate = 0;
Douglas Gregor57265e32010-04-12 16:00:01 +0000831
Douglas Gregorddc29e12009-02-06 22:42:48 +0000832 if (PrevClassTemplate) {
833 // Ensure that the template parameter lists are compatible.
834 if (!TemplateParameterListsAreEqual(TemplateParams,
835 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000836 /*Complain=*/true,
837 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000838 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000839
840 // C++ [temp.class]p4:
841 // In a redeclaration, partial specialization, explicit
842 // specialization or explicit instantiation of a class template,
843 // the class-key shall agree in kind with the original class
844 // template declaration (7.1.5.3).
845 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000846 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000847 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000848 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000849 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000850 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000851 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000852 }
853
Douglas Gregorddc29e12009-02-06 22:42:48 +0000854 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000855 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000856 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000857 Diag(NameLoc, diag::err_redefinition) << Name;
858 Diag(Def->getLocation(), diag::note_previous_definition);
859 // FIXME: Would it make sense to try to "forget" the previous
860 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000861 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000862 }
863 }
864 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
865 // Maybe we will complain about the shadowed template parameter.
866 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
867 // Just pretend that we didn't see the previous declaration.
868 PrevDecl = 0;
869 } else if (PrevDecl) {
870 // C++ [temp]p5:
871 // A class template shall not have the same name as any other
872 // template, class, function, object, enumeration, enumerator,
873 // namespace, or type in the same scope (3.3), except as specified
874 // in (14.5.4).
875 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
876 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000877 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000878 }
879
Douglas Gregord684b002009-02-10 19:49:53 +0000880 // Check the template parameter list of this declaration, possibly
881 // merging in the template parameter list from the previous class
882 // template declaration.
883 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000884 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
885 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000886 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Douglas Gregor57265e32010-04-12 16:00:01 +0000888 if (SS.isSet()) {
889 // If the name of the template was qualified, we must be defining the
890 // template out-of-line.
891 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
892 !(TUK == TUK_Friend && CurContext->isDependentContext()))
893 Diag(NameLoc, diag::err_member_def_does_not_match)
894 << Name << SemanticContext << SS.getRange();
895 }
896
Mike Stump1eb44332009-09-09 15:08:12 +0000897 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000898 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000899 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000900 PrevClassTemplate->getTemplatedDecl() : 0,
901 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000902 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000903
904 ClassTemplateDecl *NewTemplate
905 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
906 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000907 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000908 NewClass->setDescribedClassTemplate(NewTemplate);
909
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000910 // Build the type for the class template declaration now.
John McCall3cb0ebd2010-03-10 03:28:59 +0000911 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
912 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000913 assert(T->isDependentType() && "Class template type is not dependent?");
914 (void)T;
915
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000916 // If we are providing an explicit specialization of a member that is a
917 // class template, make a note of that.
918 if (PrevClassTemplate &&
919 PrevClassTemplate->getInstantiatedFromMemberTemplate())
920 PrevClassTemplate->setMemberSpecialization();
921
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000922 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000923 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000924 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Douglas Gregorddc29e12009-02-06 22:42:48 +0000926 // Set the lexical context of these templates
927 NewClass->setLexicalDeclContext(CurContext);
928 NewTemplate->setLexicalDeclContext(CurContext);
929
John McCall0f434ec2009-07-31 02:45:11 +0000930 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000931 NewClass->startDefinition();
932
933 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000934 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000935
John McCall05b23ea2009-09-14 21:59:20 +0000936 if (TUK != TUK_Friend)
937 PushOnScopeChains(NewTemplate, S);
938 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000939 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000940 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000941 NewClass->setAccess(PrevClassTemplate->getAccess());
942 }
John McCall05b23ea2009-09-14 21:59:20 +0000943
Douglas Gregord85bea22009-09-26 06:47:28 +0000944 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
945 PrevClassTemplate != NULL);
946
John McCall05b23ea2009-09-14 21:59:20 +0000947 // Friend templates are visible in fairly strange ways.
948 if (!CurContext->isDependentContext()) {
949 DeclContext *DC = SemanticContext->getLookupContext();
950 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
951 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
952 PushOnScopeChains(NewTemplate, EnclosingScope,
953 /* AddToContext = */ false);
954 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000955
956 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
957 NewClass->getLocation(),
958 NewTemplate,
959 /*FIXME:*/NewClass->getLocation());
960 Friend->setAccess(AS_public);
961 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000962 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000963
Douglas Gregord684b002009-02-10 19:49:53 +0000964 if (Invalid) {
965 NewTemplate->setInvalidDecl();
966 NewClass->setInvalidDecl();
967 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000968 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000969}
970
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000971/// \brief Diagnose the presence of a default template argument on a
972/// template parameter, which is ill-formed in certain contexts.
973///
974/// \returns true if the default template argument should be dropped.
975static bool DiagnoseDefaultTemplateArgument(Sema &S,
976 Sema::TemplateParamListContext TPC,
977 SourceLocation ParamLoc,
978 SourceRange DefArgRange) {
979 switch (TPC) {
980 case Sema::TPC_ClassTemplate:
981 return false;
982
983 case Sema::TPC_FunctionTemplate:
984 // C++ [temp.param]p9:
985 // A default template-argument shall not be specified in a
986 // function template declaration or a function template
987 // definition [...]
988 // (This sentence is not in C++0x, per DR226).
989 if (!S.getLangOptions().CPlusPlus0x)
990 S.Diag(ParamLoc,
991 diag::err_template_parameter_default_in_function_template)
992 << DefArgRange;
993 return false;
994
995 case Sema::TPC_ClassTemplateMember:
996 // C++0x [temp.param]p9:
997 // A default template-argument shall not be specified in the
998 // template-parameter-lists of the definition of a member of a
999 // class template that appears outside of the member's class.
1000 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1001 << DefArgRange;
1002 return true;
1003
1004 case Sema::TPC_FriendFunctionTemplate:
1005 // C++ [temp.param]p9:
1006 // A default template-argument shall not be specified in a
1007 // friend template declaration.
1008 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1009 << DefArgRange;
1010 return true;
1011
1012 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1013 // for friend function templates if there is only a single
1014 // declaration (and it is a definition). Strange!
1015 }
1016
1017 return false;
1018}
1019
Douglas Gregord684b002009-02-10 19:49:53 +00001020/// \brief Checks the validity of a template parameter list, possibly
1021/// considering the template parameter list from a previous
1022/// declaration.
1023///
1024/// If an "old" template parameter list is provided, it must be
1025/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1026/// template parameter list.
1027///
1028/// \param NewParams Template parameter list for a new template
1029/// declaration. This template parameter list will be updated with any
1030/// default arguments that are carried through from the previous
1031/// template parameter list.
1032///
1033/// \param OldParams If provided, template parameter list from a
1034/// previous declaration of the same template. Default template
1035/// arguments will be merged from the old template parameter list to
1036/// the new template parameter list.
1037///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001038/// \param TPC Describes the context in which we are checking the given
1039/// template parameter list.
1040///
Douglas Gregord684b002009-02-10 19:49:53 +00001041/// \returns true if an error occurred, false otherwise.
1042bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001043 TemplateParameterList *OldParams,
1044 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001045 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001046
Douglas Gregord684b002009-02-10 19:49:53 +00001047 // C++ [temp.param]p10:
1048 // The set of default template-arguments available for use with a
1049 // template declaration or definition is obtained by merging the
1050 // default arguments from the definition (if in scope) and all
1051 // declarations in scope in the same way default function
1052 // arguments are (8.3.6).
1053 bool SawDefaultArgument = false;
1054 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001055
Anders Carlsson49d25572009-06-12 23:20:15 +00001056 bool SawParameterPack = false;
1057 SourceLocation ParameterPackLoc;
1058
Mike Stump1a35fde2009-02-11 23:03:27 +00001059 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001060 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001061 if (OldParams)
1062 OldParam = OldParams->begin();
1063
1064 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1065 NewParamEnd = NewParams->end();
1066 NewParam != NewParamEnd; ++NewParam) {
1067 // Variables used to diagnose redundant default arguments
1068 bool RedundantDefaultArg = false;
1069 SourceLocation OldDefaultLoc;
1070 SourceLocation NewDefaultLoc;
1071
1072 // Variables used to diagnose missing default arguments
1073 bool MissingDefaultArg = false;
1074
Anders Carlsson49d25572009-06-12 23:20:15 +00001075 // C++0x [temp.param]p11:
1076 // If a template parameter of a class template is a template parameter pack,
1077 // it must be the last template parameter.
1078 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001079 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001080 diag::err_template_param_pack_must_be_last_template_parameter);
1081 Invalid = true;
1082 }
1083
Douglas Gregord684b002009-02-10 19:49:53 +00001084 if (TemplateTypeParmDecl *NewTypeParm
1085 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001086 // Check the presence of a default argument here.
1087 if (NewTypeParm->hasDefaultArgument() &&
1088 DiagnoseDefaultTemplateArgument(*this, TPC,
1089 NewTypeParm->getLocation(),
1090 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1091 .getFullSourceRange()))
1092 NewTypeParm->removeDefaultArgument();
1093
1094 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001095 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001096 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Anders Carlsson49d25572009-06-12 23:20:15 +00001098 if (NewTypeParm->isParameterPack()) {
1099 assert(!NewTypeParm->hasDefaultArgument() &&
1100 "Parameter packs can't have a default argument!");
1101 SawParameterPack = true;
1102 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001103 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001104 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001105 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1106 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1107 SawDefaultArgument = true;
1108 RedundantDefaultArg = true;
1109 PreviousDefaultArgLoc = NewDefaultLoc;
1110 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1111 // Merge the default argument from the old declaration to the
1112 // new declaration.
1113 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001114 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001115 true);
1116 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1117 } else if (NewTypeParm->hasDefaultArgument()) {
1118 SawDefaultArgument = true;
1119 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1120 } else if (SawDefaultArgument)
1121 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001122 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001123 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001124 // Check the presence of a default argument here.
1125 if (NewNonTypeParm->hasDefaultArgument() &&
1126 DiagnoseDefaultTemplateArgument(*this, TPC,
1127 NewNonTypeParm->getLocation(),
1128 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1129 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1130 NewNonTypeParm->setDefaultArgument(0);
1131 }
1132
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001133 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001134 NonTypeTemplateParmDecl *OldNonTypeParm
1135 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001136 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001137 NewNonTypeParm->hasDefaultArgument()) {
1138 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1139 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1140 SawDefaultArgument = true;
1141 RedundantDefaultArg = true;
1142 PreviousDefaultArgLoc = NewDefaultLoc;
1143 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1144 // Merge the default argument from the old declaration to the
1145 // new declaration.
1146 SawDefaultArgument = true;
1147 // FIXME: We need to create a new kind of "default argument"
1148 // expression that points to a previous template template
1149 // parameter.
1150 NewNonTypeParm->setDefaultArgument(
1151 OldNonTypeParm->getDefaultArgument());
1152 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1153 } else if (NewNonTypeParm->hasDefaultArgument()) {
1154 SawDefaultArgument = true;
1155 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1156 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001157 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001158 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001159 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001160 TemplateTemplateParmDecl *NewTemplateParm
1161 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001162 if (NewTemplateParm->hasDefaultArgument() &&
1163 DiagnoseDefaultTemplateArgument(*this, TPC,
1164 NewTemplateParm->getLocation(),
1165 NewTemplateParm->getDefaultArgument().getSourceRange()))
1166 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1167
1168 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001169 TemplateTemplateParmDecl *OldTemplateParm
1170 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001171 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001172 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001173 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1174 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001175 SawDefaultArgument = true;
1176 RedundantDefaultArg = true;
1177 PreviousDefaultArgLoc = NewDefaultLoc;
1178 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1179 // Merge the default argument from the old declaration to the
1180 // new declaration.
1181 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001182 // FIXME: We need to create a new kind of "default argument" expression
1183 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001184 NewTemplateParm->setDefaultArgument(
1185 OldTemplateParm->getDefaultArgument());
Douglas Gregor788cd062009-11-11 01:00:40 +00001186 PreviousDefaultArgLoc
1187 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001188 } else if (NewTemplateParm->hasDefaultArgument()) {
1189 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001190 PreviousDefaultArgLoc
1191 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001192 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001193 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001194 }
1195
1196 if (RedundantDefaultArg) {
1197 // C++ [temp.param]p12:
1198 // A template-parameter shall not be given default arguments
1199 // by two different declarations in the same scope.
1200 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1201 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1202 Invalid = true;
1203 } else if (MissingDefaultArg) {
1204 // C++ [temp.param]p11:
1205 // If a template-parameter has a default template-argument,
1206 // all subsequent template-parameters shall have a default
1207 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001208 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001209 diag::err_template_param_default_arg_missing);
1210 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1211 Invalid = true;
1212 }
1213
1214 // If we have an old template parameter list that we're merging
1215 // in, move on to the next parameter.
1216 if (OldParams)
1217 ++OldParam;
1218 }
1219
1220 return Invalid;
1221}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001222
Mike Stump1eb44332009-09-09 15:08:12 +00001223/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001224/// specifier, returning the template parameter list that applies to the
1225/// name.
1226///
1227/// \param DeclStartLoc the start of the declaration that has a scope
1228/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001229///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001230/// \param SS the scope specifier that will be matched to the given template
1231/// parameter lists. This scope specifier precedes a qualified name that is
1232/// being declared.
1233///
1234/// \param ParamLists the template parameter lists, from the outermost to the
1235/// innermost template parameter lists.
1236///
1237/// \param NumParamLists the number of template parameter lists in ParamLists.
1238///
John McCall77e8b112010-04-13 20:37:33 +00001239/// \param IsFriend Whether to apply the slightly different rules for
1240/// matching template parameters to scope specifiers in friend
1241/// declarations.
1242///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001243/// \param IsExplicitSpecialization will be set true if the entity being
1244/// declared is an explicit specialization, false otherwise.
1245///
Mike Stump1eb44332009-09-09 15:08:12 +00001246/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001247/// name that is preceded by the scope specifier @p SS. This template
1248/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001249/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001250/// template specialization), or may be NULL (if we were's declaring isn't
1251/// itself a template).
1252TemplateParameterList *
1253Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1254 const CXXScopeSpec &SS,
1255 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001256 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001257 bool IsFriend,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001258 bool &IsExplicitSpecialization) {
1259 IsExplicitSpecialization = false;
1260
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001261 // Find the template-ids that occur within the nested-name-specifier. These
1262 // template-ids will match up with the template parameter lists.
1263 llvm::SmallVector<const TemplateSpecializationType *, 4>
1264 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001265 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1266 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001267 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1268 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001269 const Type *T = NNS->getAsType();
1270 if (!T) break;
1271
1272 // C++0x [temp.expl.spec]p17:
1273 // A member or a member template may be nested within many
1274 // enclosing class templates. In an explicit specialization for
1275 // such a member, the member declaration shall be preceded by a
1276 // template<> for each enclosing class template that is
1277 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001278 //
1279 // Following the existing practice of GNU and EDG, we allow a typedef of a
1280 // template specialization type.
1281 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1282 T = TT->LookThroughTypedefs().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001283
Mike Stump1eb44332009-09-09 15:08:12 +00001284 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001285 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001286 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1287 if (!Template)
1288 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Ted Kremenek6217b802009-07-29 21:53:49 +00001290 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001291 ClassTemplateSpecializationDecl *SpecDecl
1292 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1293 // If the nested name specifier refers to an explicit specialization,
1294 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001295 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1296 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001297 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001298 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001299 }
Mike Stump1eb44332009-09-09 15:08:12 +00001300
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001301 TemplateIdsInSpecifier.push_back(SpecType);
1302 }
1303 }
Mike Stump1eb44332009-09-09 15:08:12 +00001304
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001305 // Reverse the list of template-ids in the scope specifier, so that we can
1306 // more easily match up the template-ids and the template parameter lists.
1307 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001308
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001309 SourceLocation FirstTemplateLoc = DeclStartLoc;
1310 if (NumParamLists)
1311 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001313 // Match the template-ids found in the specifier to the template parameter
1314 // lists.
1315 unsigned Idx = 0;
1316 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1317 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001318 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1319 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001320 if (Idx >= NumParamLists) {
1321 // We have a template-id without a corresponding template parameter
1322 // list.
John McCall77e8b112010-04-13 20:37:33 +00001323
1324 // ...which is fine if this is a friend declaration.
1325 if (IsFriend) {
1326 IsExplicitSpecialization = true;
1327 break;
1328 }
1329
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001330 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001331 // FIXME: the location information here isn't great.
1332 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001333 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001334 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001335 << SS.getRange();
1336 } else {
1337 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1338 << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00001339 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001340 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001341 }
1342 return 0;
1343 }
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001345 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001346 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001347 TemplateDecl *Template
Douglas Gregorb88e8882009-07-30 17:40:51 +00001348 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1349
Mike Stump1eb44332009-09-09 15:08:12 +00001350 if (ClassTemplateDecl *ClassTemplate
Douglas Gregorb88e8882009-07-30 17:40:51 +00001351 = dyn_cast<ClassTemplateDecl>(Template)) {
1352 TemplateParameterList *ExpectedTemplateParams = 0;
1353 // Is this template-id naming the primary template?
1354 if (Context.hasSameType(TemplateId,
John McCall3cb0ebd2010-03-10 03:28:59 +00001355 ClassTemplate->getInjectedClassNameSpecialization(Context)))
Douglas Gregorb88e8882009-07-30 17:40:51 +00001356 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1357 // ... or a partial specialization?
1358 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1359 = ClassTemplate->findPartialSpecialization(TemplateId))
1360 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1361
1362 if (ExpectedTemplateParams)
Mike Stump1eb44332009-09-09 15:08:12 +00001363 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregorb88e8882009-07-30 17:40:51 +00001364 ExpectedTemplateParams,
Douglas Gregorfb898e12009-11-12 16:20:59 +00001365 true, TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00001366 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001367
1368 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;
1433
Douglas Gregorcaddba02009-11-12 18:38:13 +00001434 if (Name.isDependent() ||
1435 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001436 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001437 // This class template specialization is a dependent
1438 // type. Therefore, its canonical type is another class template
1439 // specialization type that contains all of the converted
1440 // arguments in canonical form. This ensures that, e.g., A<T> and
1441 // A<T, T> have identical types when A is declared as:
1442 //
1443 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001444 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001445 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001446 Converted.getFlatArguments(),
1447 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Douglas Gregor1275ae02009-07-28 23:00:59 +00001449 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001450 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001451 // In the future, we need to teach getTemplateSpecializationType to only
1452 // build the canonical type and return that to us.
1453 CanonType = Context.getCanonicalType(CanonType);
Mike Stump1eb44332009-09-09 15:08:12 +00001454 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001455 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001456 // Find the class template specialization declaration that
1457 // corresponds to these arguments.
1458 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001459 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001460 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001461 Converted.flatSize(),
1462 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001463 void *InsertPos = 0;
1464 ClassTemplateSpecializationDecl *Decl
1465 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1466 if (!Decl) {
1467 // This is the first time we have referenced this class template
1468 // specialization. Create the canonical declaration and add it to
1469 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001470 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001471 ClassTemplate->getDeclContext(),
John McCall9cc78072009-09-11 07:25:08 +00001472 ClassTemplate->getLocation(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001473 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00001474 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001475 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1476 Decl->setLexicalDeclContext(CurContext);
1477 }
1478
1479 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001480 assert(isa<RecordType>(CanonType) &&
1481 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001482 }
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Douglas Gregor40808ce2009-03-09 23:48:35 +00001484 // Build the fully-sugared type for this class template
1485 // specialization, which refers back to the class template
1486 // specialization we created or found.
John McCalld5532b62009-11-23 01:53:49 +00001487 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001488}
1489
Douglas Gregorcc636682009-02-17 23:15:12 +00001490Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001491Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001492 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001493 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001494 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001495 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001496
Douglas Gregor40808ce2009-03-09 23:48:35 +00001497 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001498 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001499 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001500
John McCalld5532b62009-11-23 01:53:49 +00001501 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001502 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001503
1504 if (Result.isNull())
1505 return true;
1506
John McCalla93c9342009-12-07 02:54:59 +00001507 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001508 TemplateSpecializationTypeLoc TL
1509 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1510 TL.setTemplateNameLoc(TemplateLoc);
1511 TL.setLAngleLoc(LAngleLoc);
1512 TL.setRAngleLoc(RAngleLoc);
1513 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1514 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1515
1516 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCall6b2becf2009-09-08 17:47:29 +00001517}
John McCallf1bbbb42009-09-04 01:14:41 +00001518
John McCall6b2becf2009-09-08 17:47:29 +00001519Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1520 TagUseKind TUK,
1521 DeclSpec::TST TagSpec,
1522 SourceLocation TagLoc) {
1523 if (TypeResult.isInvalid())
1524 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001525
John McCall833ca992009-10-29 08:12:44 +00001526 // FIXME: preserve source info, ideally without copying the DI.
John McCalla93c9342009-12-07 02:54:59 +00001527 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001528 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001529
John McCall6b2becf2009-09-08 17:47:29 +00001530 // Verify the tag specifier.
1531 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001532
John McCall6b2becf2009-09-08 17:47:29 +00001533 if (const RecordType *RT = Type->getAs<RecordType>()) {
1534 RecordDecl *D = RT->getDecl();
1535
1536 IdentifierInfo *Id = D->getIdentifier();
1537 assert(Id && "templated class must have an identifier");
1538
1539 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1540 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001541 << Type
Douglas Gregor849b2432010-03-31 17:46:05 +00001542 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001543 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001544 }
1545 }
1546
John McCall6b2becf2009-09-08 17:47:29 +00001547 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1548
1549 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001550}
1551
John McCallf7a1a742009-11-24 19:00:30 +00001552Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1553 LookupResult &R,
1554 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001555 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001556 // FIXME: Can we do any checking at this point? I guess we could check the
1557 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001558 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001559 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001560
1561 // These should be filtered out by our callers.
1562 assert(!R.empty() && "empty lookup results when building templateid");
1563 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1564
1565 NestedNameSpecifier *Qualifier = 0;
1566 SourceRange QualifierRange;
1567 if (SS.isSet()) {
1568 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1569 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001570 }
John McCallc373d482010-01-27 01:50:18 +00001571
1572 // We don't want lookup warnings at this point.
1573 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001574
John McCallf7a1a742009-11-24 19:00:30 +00001575 bool Dependent
1576 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1577 &TemplateArgs);
1578 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001579 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001580 Qualifier, QualifierRange,
1581 R.getLookupName(), R.getNameLoc(),
1582 RequiresADL, TemplateArgs);
John McCallc373d482010-01-27 01:50:18 +00001583 ULE->addDecls(R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001584
1585 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001586}
1587
John McCallf7a1a742009-11-24 19:00:30 +00001588// We actually only call this from template instantiation.
1589Sema::OwningExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001590Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001591 DeclarationName Name,
1592 SourceLocation NameLoc,
1593 const TemplateArgumentListInfo &TemplateArgs) {
1594 DeclContext *DC;
1595 if (!(DC = computeDeclContext(SS, false)) ||
1596 DC->isDependentContext() ||
1597 RequireCompleteDeclContext(SS))
1598 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001599
John McCallf7a1a742009-11-24 19:00:30 +00001600 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1601 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00001602
John McCallf7a1a742009-11-24 19:00:30 +00001603 if (R.isAmbiguous())
1604 return ExprError();
1605
1606 if (R.empty()) {
1607 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1608 << Name << SS.getRange();
1609 return ExprError();
1610 }
1611
1612 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1613 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1614 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1615 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1616 return ExprError();
1617 }
1618
1619 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001620}
1621
Douglas Gregorc45c2322009-03-31 00:43:58 +00001622/// \brief Form a dependent template name.
1623///
1624/// This action forms a dependent template name given the template
1625/// name and its (presumably dependent) scope specifier. For
1626/// example, given "MetaFun::template apply", the scope specifier \p
1627/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1628/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump1eb44332009-09-09 15:08:12 +00001629Sema::TemplateTy
Douglas Gregorc45c2322009-03-31 00:43:58 +00001630Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001631 CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +00001632 UnqualifiedId &Name,
Douglas Gregora481edb2009-11-20 23:39:24 +00001633 TypeTy *ObjectType,
1634 bool EnteringContext) {
Douglas Gregor0707bc52010-01-19 16:01:07 +00001635 DeclContext *LookupCtx = 0;
1636 if (SS.isSet())
1637 LookupCtx = computeDeclContext(SS, EnteringContext);
1638 if (!LookupCtx && ObjectType)
1639 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1640 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001641 // C++0x [temp.names]p5:
1642 // If a name prefixed by the keyword template is not the name of
1643 // a template, the program is ill-formed. [Note: the keyword
1644 // template may not be applied to non-template members of class
1645 // templates. -end note ] [ Note: as is the case with the
1646 // typename prefix, the template prefix is allowed in cases
1647 // where it is not strictly necessary; i.e., when the
1648 // nested-name-specifier or the expression on the left of the ->
1649 // or . is not dependent on a template-parameter, or the use
1650 // does not appear in the scope of a template. -end note]
1651 //
1652 // Note: C++03 was more strict here, because it banned the use of
1653 // the "template" keyword prior to a template-name that was not a
1654 // dependent name. C++ DR468 relaxed this requirement (the
1655 // "template" keyword is now permitted). We follow the C++0x
1656 // rules, even in C++03 mode, retroactively applying the DR.
1657 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001658 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregora481edb2009-11-20 23:39:24 +00001659 EnteringContext, Template);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001660 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1661 isa<CXXRecordDecl>(LookupCtx) &&
1662 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001663 // This is a dependent template.
1664 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001665 Diag(Name.getSourceRange().getBegin(),
1666 diag::err_template_kw_refers_to_non_template)
1667 << GetNameFromUnqualifiedId(Name)
1668 << Name.getSourceRange();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001669 return TemplateTy();
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001670 } else {
1671 // We found something; return it.
1672 return Template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001673 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001674 }
1675
Mike Stump1eb44332009-09-09 15:08:12 +00001676 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001677 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001678
1679 switch (Name.getKind()) {
1680 case UnqualifiedId::IK_Identifier:
1681 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1682 Name.Identifier));
1683
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001684 case UnqualifiedId::IK_OperatorFunctionId:
1685 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1686 Name.OperatorFunctionId.Operator));
Sean Hunte6252d12009-11-28 08:58:14 +00001687
1688 case UnqualifiedId::IK_LiteralOperatorId:
1689 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1690
Douglas Gregor014e88d2009-11-03 23:16:33 +00001691 default:
1692 break;
1693 }
1694
1695 Diag(Name.getSourceRange().getBegin(),
1696 diag::err_template_kw_refers_to_non_template)
1697 << GetNameFromUnqualifiedId(Name)
1698 << Name.getSourceRange();
1699 return TemplateTy();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001700}
1701
Mike Stump1eb44332009-09-09 15:08:12 +00001702bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001703 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001704 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001705 const TemplateArgument &Arg = AL.getArgument();
1706
Anders Carlsson436b1562009-06-13 00:33:33 +00001707 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001708 switch(Arg.getKind()) {
1709 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00001710 // C++ [temp.arg.type]p1:
1711 // A template-argument for a template-parameter which is a
1712 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001713 break;
1714 case TemplateArgument::Template: {
1715 // We have a template type parameter but the template argument
1716 // is a template without any arguments.
1717 SourceRange SR = AL.getSourceRange();
1718 TemplateName Name = Arg.getAsTemplate();
1719 Diag(SR.getBegin(), diag::err_template_missing_args)
1720 << Name << SR;
1721 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1722 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00001723
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001724 return true;
1725 }
1726 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00001727 // We have a template type parameter but the template argument
1728 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001729 SourceRange SR = AL.getSourceRange();
1730 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001731 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001732
Anders Carlsson436b1562009-06-13 00:33:33 +00001733 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001734 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001735 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001736
John McCalla93c9342009-12-07 02:54:59 +00001737 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001738 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001739
Anders Carlsson436b1562009-06-13 00:33:33 +00001740 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001741 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001742 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001743 return false;
1744}
1745
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001746/// \brief Substitute template arguments into the default template argument for
1747/// the given template type parameter.
1748///
1749/// \param SemaRef the semantic analysis object for which we are performing
1750/// the substitution.
1751///
1752/// \param Template the template that we are synthesizing template arguments
1753/// for.
1754///
1755/// \param TemplateLoc the location of the template name that started the
1756/// template-id we are checking.
1757///
1758/// \param RAngleLoc the location of the right angle bracket ('>') that
1759/// terminates the template-id.
1760///
1761/// \param Param the template template parameter whose default we are
1762/// substituting into.
1763///
1764/// \param Converted the list of template arguments provided for template
1765/// parameters that precede \p Param in the template parameter list.
1766///
1767/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001768static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001769SubstDefaultTemplateArgument(Sema &SemaRef,
1770 TemplateDecl *Template,
1771 SourceLocation TemplateLoc,
1772 SourceLocation RAngleLoc,
1773 TemplateTypeParmDecl *Param,
1774 TemplateArgumentListBuilder &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001775 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001776
1777 // If the argument type is dependent, instantiate it now based
1778 // on the previously-computed template arguments.
1779 if (ArgType->getType()->isDependentType()) {
1780 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1781 /*TakeArgs=*/false);
1782
1783 MultiLevelTemplateArgumentList AllTemplateArgs
1784 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1785
1786 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1787 Template, Converted.getFlatArguments(),
1788 Converted.flatSize(),
1789 SourceRange(TemplateLoc, RAngleLoc));
1790
1791 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1792 Param->getDefaultArgumentLoc(),
1793 Param->getDeclName());
1794 }
1795
1796 return ArgType;
1797}
1798
1799/// \brief Substitute template arguments into the default template argument for
1800/// the given non-type template parameter.
1801///
1802/// \param SemaRef the semantic analysis object for which we are performing
1803/// the substitution.
1804///
1805/// \param Template the template that we are synthesizing template arguments
1806/// for.
1807///
1808/// \param TemplateLoc the location of the template name that started the
1809/// template-id we are checking.
1810///
1811/// \param RAngleLoc the location of the right angle bracket ('>') that
1812/// terminates the template-id.
1813///
Douglas Gregor788cd062009-11-11 01:00:40 +00001814/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001815/// substituting into.
1816///
1817/// \param Converted the list of template arguments provided for template
1818/// parameters that precede \p Param in the template parameter list.
1819///
1820/// \returns the substituted template argument, or NULL if an error occurred.
1821static Sema::OwningExprResult
1822SubstDefaultTemplateArgument(Sema &SemaRef,
1823 TemplateDecl *Template,
1824 SourceLocation TemplateLoc,
1825 SourceLocation RAngleLoc,
1826 NonTypeTemplateParmDecl *Param,
1827 TemplateArgumentListBuilder &Converted) {
1828 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1829 /*TakeArgs=*/false);
1830
1831 MultiLevelTemplateArgumentList AllTemplateArgs
1832 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1833
1834 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1835 Template, Converted.getFlatArguments(),
1836 Converted.flatSize(),
1837 SourceRange(TemplateLoc, RAngleLoc));
1838
1839 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1840}
1841
Douglas Gregor788cd062009-11-11 01:00:40 +00001842/// \brief Substitute template arguments into the default template argument for
1843/// the given template template parameter.
1844///
1845/// \param SemaRef the semantic analysis object for which we are performing
1846/// the substitution.
1847///
1848/// \param Template the template that we are synthesizing template arguments
1849/// for.
1850///
1851/// \param TemplateLoc the location of the template name that started the
1852/// template-id we are checking.
1853///
1854/// \param RAngleLoc the location of the right angle bracket ('>') that
1855/// terminates the template-id.
1856///
1857/// \param Param the template template parameter whose default we are
1858/// substituting into.
1859///
1860/// \param Converted the list of template arguments provided for template
1861/// parameters that precede \p Param in the template parameter list.
1862///
1863/// \returns the substituted template argument, or NULL if an error occurred.
1864static TemplateName
1865SubstDefaultTemplateArgument(Sema &SemaRef,
1866 TemplateDecl *Template,
1867 SourceLocation TemplateLoc,
1868 SourceLocation RAngleLoc,
1869 TemplateTemplateParmDecl *Param,
1870 TemplateArgumentListBuilder &Converted) {
1871 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1872 /*TakeArgs=*/false);
1873
1874 MultiLevelTemplateArgumentList AllTemplateArgs
1875 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1876
1877 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1878 Template, Converted.getFlatArguments(),
1879 Converted.flatSize(),
1880 SourceRange(TemplateLoc, RAngleLoc));
1881
1882 return SemaRef.SubstTemplateName(
1883 Param->getDefaultArgument().getArgument().getAsTemplate(),
1884 Param->getDefaultArgument().getTemplateNameLoc(),
1885 AllTemplateArgs);
1886}
1887
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001888/// \brief If the given template parameter has a default template
1889/// argument, substitute into that default template argument and
1890/// return the corresponding template argument.
1891TemplateArgumentLoc
1892Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1893 SourceLocation TemplateLoc,
1894 SourceLocation RAngleLoc,
1895 Decl *Param,
1896 TemplateArgumentListBuilder &Converted) {
1897 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1898 if (!TypeParm->hasDefaultArgument())
1899 return TemplateArgumentLoc();
1900
John McCalla93c9342009-12-07 02:54:59 +00001901 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001902 TemplateLoc,
1903 RAngleLoc,
1904 TypeParm,
1905 Converted);
1906 if (DI)
1907 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1908
1909 return TemplateArgumentLoc();
1910 }
1911
1912 if (NonTypeTemplateParmDecl *NonTypeParm
1913 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1914 if (!NonTypeParm->hasDefaultArgument())
1915 return TemplateArgumentLoc();
1916
1917 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1918 TemplateLoc,
1919 RAngleLoc,
1920 NonTypeParm,
1921 Converted);
1922 if (Arg.isInvalid())
1923 return TemplateArgumentLoc();
1924
1925 Expr *ArgE = Arg.takeAs<Expr>();
1926 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1927 }
1928
1929 TemplateTemplateParmDecl *TempTempParm
1930 = cast<TemplateTemplateParmDecl>(Param);
1931 if (!TempTempParm->hasDefaultArgument())
1932 return TemplateArgumentLoc();
1933
1934 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1935 TemplateLoc,
1936 RAngleLoc,
1937 TempTempParm,
1938 Converted);
1939 if (TName.isNull())
1940 return TemplateArgumentLoc();
1941
1942 return TemplateArgumentLoc(TemplateArgument(TName),
1943 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1944 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1945}
1946
Douglas Gregore7526412009-11-11 19:31:23 +00001947/// \brief Check that the given template argument corresponds to the given
1948/// template parameter.
1949bool Sema::CheckTemplateArgument(NamedDecl *Param,
1950 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00001951 TemplateDecl *Template,
1952 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00001953 SourceLocation RAngleLoc,
Douglas Gregor02024a92010-03-28 02:42:43 +00001954 TemplateArgumentListBuilder &Converted,
1955 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00001956 // Check template type parameters.
1957 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00001958 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00001959
Douglas Gregord9e15302009-11-11 19:41:09 +00001960 // Check non-type template parameters.
1961 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00001962 // Do substitution on the type of the non-type template parameter
1963 // with the template arguments we've seen thus far.
1964 QualType NTTPType = NTTP->getType();
1965 if (NTTPType->isDependentType()) {
1966 // Do substitution on the type of the non-type template parameter.
1967 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1968 NTTP, Converted.getFlatArguments(),
1969 Converted.flatSize(),
1970 SourceRange(TemplateLoc, RAngleLoc));
1971
1972 TemplateArgumentList TemplateArgs(Context, Converted,
1973 /*TakeArgs=*/false);
1974 NTTPType = SubstType(NTTPType,
1975 MultiLevelTemplateArgumentList(TemplateArgs),
1976 NTTP->getLocation(),
1977 NTTP->getDeclName());
1978 // If that worked, check the non-type template parameter type
1979 // for validity.
1980 if (!NTTPType.isNull())
1981 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1982 NTTP->getLocation());
1983 if (NTTPType.isNull())
1984 return true;
1985 }
1986
1987 switch (Arg.getArgument().getKind()) {
1988 case TemplateArgument::Null:
1989 assert(false && "Should never see a NULL template argument here");
1990 return true;
1991
1992 case TemplateArgument::Expression: {
1993 Expr *E = Arg.getArgument().getAsExpr();
1994 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00001995 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00001996 return true;
1997
1998 Converted.Append(Result);
1999 break;
2000 }
2001
2002 case TemplateArgument::Declaration:
2003 case TemplateArgument::Integral:
2004 // We've already checked this template argument, so just copy
2005 // it to the list of converted arguments.
2006 Converted.Append(Arg.getArgument());
2007 break;
2008
2009 case TemplateArgument::Template:
2010 // We were given a template template argument. It may not be ill-formed;
2011 // see below.
2012 if (DependentTemplateName *DTN
2013 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2014 // We have a template argument such as \c T::template X, which we
2015 // parsed as a template template argument. However, since we now
2016 // know that we need a non-type template argument, convert this
2017 // template name into an expression.
John McCallf7a1a742009-11-24 19:00:30 +00002018 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2019 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002020 Arg.getTemplateQualifierRange(),
John McCallf7a1a742009-11-24 19:00:30 +00002021 DTN->getIdentifier(),
2022 Arg.getTemplateNameLoc());
Douglas Gregore7526412009-11-11 19:31:23 +00002023
2024 TemplateArgument Result;
2025 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2026 return true;
2027
2028 Converted.Append(Result);
2029 break;
2030 }
2031
2032 // We have a template argument that actually does refer to a class
2033 // template, template alias, or template template parameter, and
2034 // therefore cannot be a non-type template argument.
2035 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2036 << Arg.getSourceRange();
2037
2038 Diag(Param->getLocation(), diag::note_template_param_here);
2039 return true;
2040
2041 case TemplateArgument::Type: {
2042 // We have a non-type template parameter but the template
2043 // argument is a type.
2044
2045 // C++ [temp.arg]p2:
2046 // In a template-argument, an ambiguity between a type-id and
2047 // an expression is resolved to a type-id, regardless of the
2048 // form of the corresponding template-parameter.
2049 //
2050 // We warn specifically about this case, since it can be rather
2051 // confusing for users.
2052 QualType T = Arg.getArgument().getAsType();
2053 SourceRange SR = Arg.getSourceRange();
2054 if (T->isFunctionType())
2055 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2056 else
2057 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2058 Diag(Param->getLocation(), diag::note_template_param_here);
2059 return true;
2060 }
2061
2062 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002063 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002064 break;
2065 }
2066
2067 return false;
2068 }
2069
2070
2071 // Check template template parameters.
2072 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2073
2074 // Substitute into the template parameter list of the template
2075 // template parameter, since previously-supplied template arguments
2076 // may appear within the template template parameter.
2077 {
2078 // Set up a template instantiation context.
2079 LocalInstantiationScope Scope(*this);
2080 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2081 TempParm, Converted.getFlatArguments(),
2082 Converted.flatSize(),
2083 SourceRange(TemplateLoc, RAngleLoc));
2084
2085 TemplateArgumentList TemplateArgs(Context, Converted,
2086 /*TakeArgs=*/false);
2087 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2088 SubstDecl(TempParm, CurContext,
2089 MultiLevelTemplateArgumentList(TemplateArgs)));
2090 if (!TempParm)
2091 return true;
2092
2093 // FIXME: TempParam is leaked.
2094 }
2095
2096 switch (Arg.getArgument().getKind()) {
2097 case TemplateArgument::Null:
2098 assert(false && "Should never see a NULL template argument here");
2099 return true;
2100
2101 case TemplateArgument::Template:
2102 if (CheckTemplateArgument(TempParm, Arg))
2103 return true;
2104
2105 Converted.Append(Arg.getArgument());
2106 break;
2107
2108 case TemplateArgument::Expression:
2109 case TemplateArgument::Type:
2110 // We have a template template parameter but the template
2111 // argument does not refer to a template.
2112 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2113 return true;
2114
2115 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002116 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002117 "Declaration argument with template template parameter");
2118 break;
2119 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002120 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002121 "Integral argument with template template parameter");
2122 break;
2123
2124 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002125 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002126 break;
2127 }
2128
2129 return false;
2130}
2131
Douglas Gregorc15cb382009-02-09 23:23:08 +00002132/// \brief Check that the given template argument list is well-formed
2133/// for specializing the given template.
2134bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2135 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002136 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002137 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002138 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002139 TemplateParameterList *Params = Template->getTemplateParameters();
2140 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002141 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002142 bool Invalid = false;
2143
John McCalld5532b62009-11-23 01:53:49 +00002144 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2145
Mike Stump1eb44332009-09-09 15:08:12 +00002146 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002147 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002149 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002150 (NumArgs < Params->getMinRequiredArguments() &&
2151 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002152 // FIXME: point at either the first arg beyond what we can handle,
2153 // or the '>', depending on whether we have too many or too few
2154 // arguments.
2155 SourceRange Range;
2156 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002157 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002158 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2159 << (NumArgs > NumParams)
2160 << (isa<ClassTemplateDecl>(Template)? 0 :
2161 isa<FunctionTemplateDecl>(Template)? 1 :
2162 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2163 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002164 Diag(Template->getLocation(), diag::note_template_decl_here)
2165 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002166 Invalid = true;
2167 }
Mike Stump1eb44332009-09-09 15:08:12 +00002168
2169 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002170 // [...] The type and form of each template-argument specified in
2171 // a template-id shall match the type and form specified for the
2172 // corresponding parameter declared by the template in its
2173 // template-parameter-list.
2174 unsigned ArgIdx = 0;
2175 for (TemplateParameterList::iterator Param = Params->begin(),
2176 ParamEnd = Params->end();
2177 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002178 if (ArgIdx > NumArgs && PartialTemplateArgs)
2179 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002180
Douglas Gregord9e15302009-11-11 19:41:09 +00002181 // If we have a template parameter pack, check every remaining template
2182 // argument against that template parameter pack.
2183 if ((*Param)->isTemplateParameterPack()) {
2184 Converted.BeginPack();
2185 for (; ArgIdx < NumArgs; ++ArgIdx) {
2186 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2187 TemplateLoc, RAngleLoc, Converted)) {
2188 Invalid = true;
2189 break;
2190 }
2191 }
2192 Converted.EndPack();
2193 continue;
2194 }
2195
Douglas Gregorf35f8282009-11-11 21:54:23 +00002196 if (ArgIdx < NumArgs) {
2197 // Check the template argument we were given.
2198 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2199 TemplateLoc, RAngleLoc, Converted))
2200 return true;
2201
2202 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002203 }
Douglas Gregore7526412009-11-11 19:31:23 +00002204
Douglas Gregorf35f8282009-11-11 21:54:23 +00002205 // We have a default template argument that we will use.
2206 TemplateArgumentLoc Arg;
2207
2208 // Retrieve the default template argument from the template
2209 // parameter. For each kind of template parameter, we substitute the
2210 // template arguments provided thus far and any "outer" template arguments
2211 // (when the template parameter was part of a nested template) into
2212 // the default argument.
2213 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2214 if (!TTP->hasDefaultArgument()) {
2215 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2216 break;
2217 }
2218
John McCalla93c9342009-12-07 02:54:59 +00002219 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002220 Template,
2221 TemplateLoc,
2222 RAngleLoc,
2223 TTP,
2224 Converted);
2225 if (!ArgType)
2226 return true;
2227
2228 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2229 ArgType);
2230 } else if (NonTypeTemplateParmDecl *NTTP
2231 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2232 if (!NTTP->hasDefaultArgument()) {
2233 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2234 break;
2235 }
2236
2237 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2238 TemplateLoc,
2239 RAngleLoc,
2240 NTTP,
2241 Converted);
2242 if (E.isInvalid())
2243 return true;
2244
2245 Expr *Ex = E.takeAs<Expr>();
2246 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2247 } else {
2248 TemplateTemplateParmDecl *TempParm
2249 = cast<TemplateTemplateParmDecl>(*Param);
2250
2251 if (!TempParm->hasDefaultArgument()) {
2252 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2253 break;
2254 }
2255
2256 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2257 TemplateLoc,
2258 RAngleLoc,
2259 TempParm,
2260 Converted);
2261 if (Name.isNull())
2262 return true;
2263
2264 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2265 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2266 TempParm->getDefaultArgument().getTemplateNameLoc());
2267 }
2268
2269 // Introduce an instantiation record that describes where we are using
2270 // the default template argument.
2271 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2272 Converted.getFlatArguments(),
2273 Converted.flatSize(),
2274 SourceRange(TemplateLoc, RAngleLoc));
2275
2276 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002277 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002278 RAngleLoc, Converted))
2279 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002280 }
2281
2282 return Invalid;
2283}
2284
2285/// \brief Check a template argument against its corresponding
2286/// template type parameter.
2287///
2288/// This routine implements the semantics of C++ [temp.arg.type]. It
2289/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002290bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002291 TypeSourceInfo *ArgInfo) {
2292 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002293 QualType Arg = ArgInfo->getType();
2294
Douglas Gregorc15cb382009-02-09 23:23:08 +00002295 // C++ [temp.arg.type]p2:
2296 // A local type, a type with no linkage, an unnamed type or a type
2297 // compounded from any of these types shall not be used as a
2298 // template-argument for a template type-parameter.
2299 //
2300 // FIXME: Perform the recursive and no-linkage type checks.
2301 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00002302 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002303 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00002304 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002305 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00002306 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2307 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2308 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2309 << QualType(Tag, 0) << SR;
2310 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00002311 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall833ca992009-10-29 08:12:44 +00002312 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2313 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002314 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2315 return true;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002316 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2317 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2318 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002319 }
2320
2321 return false;
2322}
2323
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002324/// \brief Checks whether the given template argument is the address
2325/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002326static bool
2327CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2328 NonTypeTemplateParmDecl *Param,
2329 QualType ParamType,
2330 Expr *ArgIn,
2331 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002332 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002333 Expr *Arg = ArgIn;
2334 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002335
2336 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002337 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002338 Arg = Cast->getSubExpr();
2339
2340 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002341 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002342 // A template-argument for a non-type, non-template
2343 // template-parameter shall be one of: [...]
2344 //
2345 // -- the address of an object or function with external
2346 // linkage, including function templates and function
2347 // template-ids but excluding non-static class members,
2348 // expressed as & id-expression where the & is optional if
2349 // the name refers to a function or array, or if the
2350 // corresponding template-parameter is a reference; or
2351 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002352
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002353 // Ignore (and complain about) any excess parentheses.
2354 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2355 if (!Invalid) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002356 S.Diag(Arg->getSourceRange().getBegin(),
2357 diag::err_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002358 << Arg->getSourceRange();
2359 Invalid = true;
2360 }
2361
2362 Arg = Parens->getSubExpr();
2363 }
2364
Douglas Gregorb7a09262010-04-01 18:32:35 +00002365 bool AddressTaken = false;
2366 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002367 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002368 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002369 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb7a09262010-04-01 18:32:35 +00002370 AddressTaken = true;
2371 AddrOpLoc = UnOp->getOperatorLoc();
2372 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002373 } else
2374 DRE = dyn_cast<DeclRefExpr>(Arg);
2375
Douglas Gregorb7a09262010-04-01 18:32:35 +00002376 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002377 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2378 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002379 S.Diag(Param->getLocation(), diag::note_template_param_here);
2380 return true;
2381 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002382
2383 // Stop checking the precise nature of the argument if it is value dependent,
2384 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002385 if (Arg->isValueDependent()) {
2386 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth038cc392010-01-31 10:01:20 +00002387 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002388 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002389
Douglas Gregorb7a09262010-04-01 18:32:35 +00002390 if (!isa<ValueDecl>(DRE->getDecl())) {
2391 S.Diag(Arg->getSourceRange().getBegin(),
2392 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002393 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002394 S.Diag(Param->getLocation(), diag::note_template_param_here);
2395 return true;
2396 }
2397
2398 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002399
2400 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00002401 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2402 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002403 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002404 S.Diag(Param->getLocation(), diag::note_template_param_here);
2405 return true;
2406 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002407
2408 // Cannot refer to non-static member functions
2409 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00002410 if (!Method->isStatic()) {
2411 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002412 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002413 S.Diag(Param->getLocation(), diag::note_template_param_here);
2414 return true;
2415 }
Mike Stump1eb44332009-09-09 15:08:12 +00002416
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002417 // Functions must have external linkage.
2418 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002419 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002420 S.Diag(Arg->getSourceRange().getBegin(),
2421 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002422 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002423 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002424 << true;
2425 return true;
2426 }
2427
2428 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002429 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002430
Douglas Gregorb7a09262010-04-01 18:32:35 +00002431 // If the template parameter has pointer type, the function decays.
2432 if (ParamType->isPointerType() && !AddressTaken)
2433 ArgType = S.Context.getPointerType(Func->getType());
2434 else if (AddressTaken && ParamType->isReferenceType()) {
2435 // If we originally had an address-of operator, but the
2436 // parameter has reference type, complain and (if things look
2437 // like they will work) drop the address-of operator.
2438 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2439 ParamType.getNonReferenceType())) {
2440 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2441 << ParamType;
2442 S.Diag(Param->getLocation(), diag::note_template_param_here);
2443 return true;
2444 }
2445
2446 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2447 << ParamType
2448 << FixItHint::CreateRemoval(AddrOpLoc);
2449 S.Diag(Param->getLocation(), diag::note_template_param_here);
2450
2451 ArgType = Func->getType();
2452 }
2453 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002454 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002455 S.Diag(Arg->getSourceRange().getBegin(),
2456 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002457 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002458 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002459 << true;
2460 return true;
2461 }
2462
Douglas Gregorb7a09262010-04-01 18:32:35 +00002463 // A value of reference type is not an object.
2464 if (Var->getType()->isReferenceType()) {
2465 S.Diag(Arg->getSourceRange().getBegin(),
2466 diag::err_template_arg_reference_var)
2467 << Var->getType() << Arg->getSourceRange();
2468 S.Diag(Param->getLocation(), diag::note_template_param_here);
2469 return true;
2470 }
2471
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002472 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002473 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002474
2475 // If the template parameter has pointer type, we must have taken
2476 // the address of this object.
2477 if (ParamType->isReferenceType()) {
2478 if (AddressTaken) {
2479 // If we originally had an address-of operator, but the
2480 // parameter has reference type, complain and (if things look
2481 // like they will work) drop the address-of operator.
2482 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2483 ParamType.getNonReferenceType())) {
2484 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2485 << ParamType;
2486 S.Diag(Param->getLocation(), diag::note_template_param_here);
2487 return true;
2488 }
2489
2490 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2491 << ParamType
2492 << FixItHint::CreateRemoval(AddrOpLoc);
2493 S.Diag(Param->getLocation(), diag::note_template_param_here);
2494
2495 ArgType = Var->getType();
2496 }
2497 } else if (!AddressTaken && ParamType->isPointerType()) {
2498 if (Var->getType()->isArrayType()) {
2499 // Array-to-pointer decay.
2500 ArgType = S.Context.getArrayDecayedType(Var->getType());
2501 } else {
2502 // If the template parameter has pointer type but the address of
2503 // this object was not taken, complain and (possibly) recover by
2504 // taking the address of the entity.
2505 ArgType = S.Context.getPointerType(Var->getType());
2506 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2507 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2508 << ParamType;
2509 S.Diag(Param->getLocation(), diag::note_template_param_here);
2510 return true;
2511 }
2512
2513 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2514 << ParamType
2515 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2516
2517 S.Diag(Param->getLocation(), diag::note_template_param_here);
2518 }
2519 }
2520 } else {
2521 // We found something else, but we don't know specifically what it is.
2522 S.Diag(Arg->getSourceRange().getBegin(),
2523 diag::err_template_arg_not_object_or_func)
2524 << Arg->getSourceRange();
2525 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2526 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002527 }
Mike Stump1eb44332009-09-09 15:08:12 +00002528
Douglas Gregorb7a09262010-04-01 18:32:35 +00002529 if (ParamType->isPointerType() &&
2530 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2531 S.IsQualificationConversion(ArgType, ParamType)) {
2532 // For pointer-to-object types, qualification conversions are
2533 // permitted.
2534 } else {
2535 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2536 if (!ParamRef->getPointeeType()->isFunctionType()) {
2537 // C++ [temp.arg.nontype]p5b3:
2538 // For a non-type template-parameter of type reference to
2539 // object, no conversions apply. The type referred to by the
2540 // reference may be more cv-qualified than the (otherwise
2541 // identical) type of the template- argument. The
2542 // template-parameter is bound directly to the
2543 // template-argument, which shall be an lvalue.
2544
2545 // FIXME: Other qualifiers?
2546 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2547 unsigned ArgQuals = ArgType.getCVRQualifiers();
2548
2549 if ((ParamQuals | ArgQuals) != ParamQuals) {
2550 S.Diag(Arg->getSourceRange().getBegin(),
2551 diag::err_template_arg_ref_bind_ignores_quals)
2552 << ParamType << Arg->getType()
2553 << Arg->getSourceRange();
2554 S.Diag(Param->getLocation(), diag::note_template_param_here);
2555 return true;
2556 }
2557 }
2558 }
2559
2560 // At this point, the template argument refers to an object or
2561 // function with external linkage. We now need to check whether the
2562 // argument and parameter types are compatible.
2563 if (!S.Context.hasSameUnqualifiedType(ArgType,
2564 ParamType.getNonReferenceType())) {
2565 // We can't perform this conversion or binding.
2566 if (ParamType->isReferenceType())
2567 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2568 << ParamType << Arg->getType() << Arg->getSourceRange();
2569 else
2570 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2571 << Arg->getType() << ParamType << Arg->getSourceRange();
2572 S.Diag(Param->getLocation(), diag::note_template_param_here);
2573 return true;
2574 }
2575 }
2576
2577 // Create the template argument.
2578 Converted = TemplateArgument(Entity->getCanonicalDecl());
2579 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002580}
2581
2582/// \brief Checks whether the given template argument is a pointer to
2583/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002584bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2585 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002586 bool Invalid = false;
2587
2588 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002589 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002590 Arg = Cast->getSubExpr();
2591
2592 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002593 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002594 // A template-argument for a non-type, non-template
2595 // template-parameter shall be one of: [...]
2596 //
2597 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002598 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002599
2600 // Ignore (and complain about) any excess parentheses.
2601 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2602 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002603 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002604 diag::err_template_arg_extra_parens)
2605 << Arg->getSourceRange();
2606 Invalid = true;
2607 }
2608
2609 Arg = Parens->getSubExpr();
2610 }
2611
Douglas Gregorcaddba02009-11-12 18:38:13 +00002612 // A pointer-to-member constant written &Class::member.
2613 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002614 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2615 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2616 if (DRE && !DRE->getQualifier())
2617 DRE = 0;
2618 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002619 }
2620 // A constant of pointer-to-member type.
2621 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2622 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2623 if (VD->getType()->isMemberPointerType()) {
2624 if (isa<NonTypeTemplateParmDecl>(VD) ||
2625 (isa<VarDecl>(VD) &&
2626 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2627 if (Arg->isTypeDependent() || Arg->isValueDependent())
2628 Converted = TemplateArgument(Arg->Retain());
2629 else
2630 Converted = TemplateArgument(VD->getCanonicalDecl());
2631 return Invalid;
2632 }
2633 }
2634 }
2635
2636 DRE = 0;
2637 }
2638
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002639 if (!DRE)
2640 return Diag(Arg->getSourceRange().getBegin(),
2641 diag::err_template_arg_not_pointer_to_member_form)
2642 << Arg->getSourceRange();
2643
2644 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2645 assert((isa<FieldDecl>(DRE->getDecl()) ||
2646 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2647 "Only non-static member pointers can make it here");
2648
2649 // Okay: this is the address of a non-static member, and therefore
2650 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002651 if (Arg->isTypeDependent() || Arg->isValueDependent())
2652 Converted = TemplateArgument(Arg->Retain());
2653 else
2654 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002655 return Invalid;
2656 }
2657
2658 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002659 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002660 diag::err_template_arg_not_pointer_to_member_form)
2661 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002662 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002663 diag::note_template_arg_refers_here);
2664 return true;
2665}
2666
Douglas Gregorc15cb382009-02-09 23:23:08 +00002667/// \brief Check a template argument against its corresponding
2668/// non-type template parameter.
2669///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002670/// This routine implements the semantics of C++ [temp.arg.nontype].
2671/// It returns true if an error occurred, and false otherwise. \p
2672/// InstantiatedParamType is the type of the non-type template
2673/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002674///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002675/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002676bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002677 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00002678 TemplateArgument &Converted,
2679 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002680 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2681
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002682 // If either the parameter has a dependent type or the argument is
2683 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00002684 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2685 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002686 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002687 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002688 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002689
2690 // C++ [temp.arg.nontype]p5:
2691 // The following conversions are performed on each expression used
2692 // as a non-type template-argument. If a non-type
2693 // template-argument cannot be converted to the type of the
2694 // corresponding template-parameter then the program is
2695 // ill-formed.
2696 //
2697 // -- for a non-type template-parameter of integral or
2698 // enumeration type, integral promotions (4.5) and integral
2699 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002700 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002701 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002702 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002703 // C++ [temp.arg.nontype]p1:
2704 // A template-argument for a non-type, non-template
2705 // template-parameter shall be one of:
2706 //
2707 // -- an integral constant-expression of integral or enumeration
2708 // type; or
2709 // -- the name of a non-type template-parameter; or
2710 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002711 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002712 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002713 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002714 diag::err_template_arg_not_integral_or_enumeral)
2715 << ArgType << Arg->getSourceRange();
2716 Diag(Param->getLocation(), diag::note_template_param_here);
2717 return true;
2718 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002719 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002720 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2721 << ArgType << Arg->getSourceRange();
2722 return true;
2723 }
2724
Douglas Gregor02024a92010-03-28 02:42:43 +00002725 // From here on out, all we care about are the unqualified forms
2726 // of the parameter and argument types.
2727 ParamType = ParamType.getUnqualifiedType();
2728 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002729
2730 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002731 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002732 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00002733 } else if (CTAK == CTAK_Deduced) {
2734 // C++ [temp.deduct.type]p17:
2735 // If, in the declaration of a function template with a non-type
2736 // template-parameter, the non-type template- parameter is used
2737 // in an expression in the function parameter-list and, if the
2738 // corresponding template-argument is deduced, the
2739 // template-argument type shall match the type of the
2740 // template-parameter exactly, except that a template-argument
2741 // deduced from an array bound may be of any integral type.
2742 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2743 << ArgType << ParamType;
2744 Diag(Param->getLocation(), diag::note_template_param_here);
2745 return true;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002746 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2747 !ParamType->isEnumeralType()) {
2748 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002749 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002750 } else {
2751 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002752 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002753 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002754 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002755 Diag(Param->getLocation(), diag::note_template_param_here);
2756 return true;
2757 }
2758
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002759 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002760 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002761 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002762
2763 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002764 llvm::APSInt OldValue = Value;
2765
2766 // Coerce the template argument's value to the value it will have
2767 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002768 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002769 if (Value.getBitWidth() != AllowedBits)
2770 Value.extOrTrunc(AllowedBits);
2771 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002772
2773 // Complain if an unsigned parameter received a negative value.
2774 if (IntegerType->isUnsignedIntegerType()
2775 && (OldValue.isSigned() && OldValue.isNegative())) {
2776 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2777 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2778 << Arg->getSourceRange();
2779 Diag(Param->getLocation(), diag::note_template_param_here);
2780 }
2781
2782 // Complain if we overflowed the template parameter's type.
2783 unsigned RequiredBits;
2784 if (IntegerType->isUnsignedIntegerType())
2785 RequiredBits = OldValue.getActiveBits();
2786 else if (OldValue.isUnsigned())
2787 RequiredBits = OldValue.getActiveBits() + 1;
2788 else
2789 RequiredBits = OldValue.getMinSignedBits();
2790 if (RequiredBits > AllowedBits) {
2791 Diag(Arg->getSourceRange().getBegin(),
2792 diag::warn_template_arg_too_large)
2793 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2794 << Arg->getSourceRange();
2795 Diag(Param->getLocation(), diag::note_template_param_here);
2796 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002797 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002798
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002799 // Add the value of this argument to the list of converted
2800 // arguments. We use the bitwidth and signedness of the template
2801 // parameter.
2802 if (Arg->isValueDependent()) {
2803 // The argument is value-dependent. Create a new
2804 // TemplateArgument with the converted expression.
2805 Converted = TemplateArgument(Arg);
2806 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002807 }
2808
John McCall833ca992009-10-29 08:12:44 +00002809 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002810 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002811 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002812 return false;
2813 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002814
John McCall6bb80172010-03-30 21:47:33 +00002815 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2816
Douglas Gregorb7a09262010-04-01 18:32:35 +00002817 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2818 // from a template argument of type std::nullptr_t to a non-type
2819 // template parameter of type pointer to object, pointer to
2820 // function, or pointer-to-member, respectively.
2821 if (ArgType->isNullPtrType() &&
2822 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2823 Converted = TemplateArgument((NamedDecl *)0);
2824 return false;
2825 }
2826
Douglas Gregorb86b0572009-02-11 01:18:59 +00002827 // Handle pointer-to-function, reference-to-function, and
2828 // pointer-to-member-function all in (roughly) the same way.
2829 if (// -- For a non-type template-parameter of type pointer to
2830 // function, only the function-to-pointer conversion (4.3) is
2831 // applied. If the template-argument represents a set of
2832 // overloaded functions (or a pointer to such), the matching
2833 // function is selected from the set (13.4).
2834 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002835 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002836 // -- For a non-type template-parameter of type reference to
2837 // function, no conversions apply. If the template-argument
2838 // represents a set of overloaded functions, the matching
2839 // function is selected from the set (13.4).
2840 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002841 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002842 // -- For a non-type template-parameter of type pointer to
2843 // member function, no conversions apply. If the
2844 // template-argument represents a set of overloaded member
2845 // functions, the matching member function is selected from
2846 // the set (13.4).
2847 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002848 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002849 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002850
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002851 if (Arg->getType() == Context.OverloadTy) {
2852 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2853 true,
2854 FoundResult)) {
2855 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2856 return true;
2857
2858 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2859 ArgType = Arg->getType();
2860 } else
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002861 return true;
Douglas Gregora35284b2009-02-11 00:19:33 +00002862 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002863
Douglas Gregorb7a09262010-04-01 18:32:35 +00002864 if (!ParamType->isMemberPointerType())
2865 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2866 ParamType,
2867 Arg, Converted);
2868
2869 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
2870 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
Anders Carlsson88465d32010-04-23 22:18:37 +00002871 /*InheritancePath=*/0,
Douglas Gregorb7a09262010-04-01 18:32:35 +00002872 Arg->isLvalue(Context) == Expr::LV_Valid);
2873 } else if (!Context.hasSameUnqualifiedType(ArgType,
2874 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002875 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002876 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002877 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002878 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002879 Diag(Param->getLocation(), diag::note_template_param_here);
2880 return true;
2881 }
Mike Stump1eb44332009-09-09 15:08:12 +00002882
Douglas Gregorb7a09262010-04-01 18:32:35 +00002883 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregora35284b2009-02-11 00:19:33 +00002884 }
2885
Chris Lattnerfe90de72009-02-20 21:37:53 +00002886 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002887 // -- for a non-type template-parameter of type pointer to
2888 // object, qualification conversions (4.4) and the
2889 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002890 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002891 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002892 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002893
Douglas Gregorb7a09262010-04-01 18:32:35 +00002894 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2895 ParamType,
2896 Arg, Converted);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002897 }
Mike Stump1eb44332009-09-09 15:08:12 +00002898
Ted Kremenek6217b802009-07-29 21:53:49 +00002899 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002900 // -- For a non-type template-parameter of type reference to
2901 // object, no conversions apply. The type referred to by the
2902 // reference may be more cv-qualified than the (otherwise
2903 // identical) type of the template-argument. The
2904 // template-parameter is bound directly to the
2905 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002906 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002907 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002908
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002909 if (Arg->getType() == Context.OverloadTy) {
2910 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2911 ParamRefType->getPointeeType(),
2912 true,
2913 FoundResult)) {
2914 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2915 return true;
2916
2917 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2918 ArgType = Arg->getType();
2919 } else
Douglas Gregorb7a09262010-04-01 18:32:35 +00002920 return true;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002921 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002922
Douglas Gregorb7a09262010-04-01 18:32:35 +00002923 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2924 ParamType,
2925 Arg, Converted);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002926 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002927
2928 // -- For a non-type template-parameter of type pointer to data
2929 // member, qualification conversions (4.4) are applied.
2930 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2931
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002932 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002933 // Types match exactly: nothing more to do here.
2934 } else if (IsQualificationConversion(ArgType, ParamType)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002935 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
Anders Carlsson88465d32010-04-23 22:18:37 +00002936 /*InheritancePath=*/0,
Douglas Gregorb7a09262010-04-01 18:32:35 +00002937 Arg->isLvalue(Context) == Expr::LV_Valid);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002938 } else {
2939 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002940 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00002941 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002942 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00002943 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002944 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00002945 }
2946
Douglas Gregorcaddba02009-11-12 18:38:13 +00002947 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002948}
2949
2950/// \brief Check a template argument against its corresponding
2951/// template template parameter.
2952///
2953/// This routine implements the semantics of C++ [temp.arg.template].
2954/// It returns true if an error occurred, and false otherwise.
2955bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00002956 const TemplateArgumentLoc &Arg) {
2957 TemplateName Name = Arg.getArgument().getAsTemplate();
2958 TemplateDecl *Template = Name.getAsTemplateDecl();
2959 if (!Template) {
2960 // Any dependent template name is fine.
2961 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2962 return false;
2963 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002964
2965 // C++ [temp.arg.template]p1:
2966 // A template-argument for a template template-parameter shall be
2967 // the name of a class template, expressed as id-expression. Only
2968 // primary class templates are considered when matching the
2969 // template template argument with the corresponding parameter;
2970 // partial specializations are not considered even if their
2971 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002972 //
2973 // Note that we also allow template template parameters here, which
2974 // will happen when we are dealing with, e.g., class template
2975 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00002976 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002977 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002978 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00002979 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00002980 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00002981 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002982 << Template;
2983 }
2984
2985 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2986 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00002987 true,
2988 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00002989 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00002990}
2991
Douglas Gregor02024a92010-03-28 02:42:43 +00002992/// \brief Given a non-type template argument that refers to a
2993/// declaration and the type of its corresponding non-type template
2994/// parameter, produce an expression that properly refers to that
2995/// declaration.
2996Sema::OwningExprResult
2997Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
2998 QualType ParamType,
2999 SourceLocation Loc) {
3000 assert(Arg.getKind() == TemplateArgument::Declaration &&
3001 "Only declaration template arguments permitted here");
3002 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3003
3004 if (VD->getDeclContext()->isRecord() &&
3005 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3006 // If the value is a class member, we might have a pointer-to-member.
3007 // Determine whether the non-type template template parameter is of
3008 // pointer-to-member type. If so, we need to build an appropriate
3009 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3010 // would refer to the member itself.
3011 if (ParamType->isMemberPointerType()) {
3012 QualType ClassType
3013 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3014 NestedNameSpecifier *Qualifier
3015 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
3016 CXXScopeSpec SS;
3017 SS.setScopeRep(Qualifier);
3018 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
3019 VD->getType().getNonReferenceType(),
3020 Loc,
3021 &SS);
3022 if (RefExpr.isInvalid())
3023 return ExprError();
3024
3025 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
3026 assert(!RefExpr.isInvalid() &&
3027 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
3028 ParamType));
3029 return move(RefExpr);
3030 }
3031 }
3032
3033 QualType T = VD->getType().getNonReferenceType();
3034 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003035 // When the non-type template parameter is a pointer, take the
3036 // address of the declaration.
Douglas Gregor02024a92010-03-28 02:42:43 +00003037 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3038 if (RefExpr.isInvalid())
3039 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003040
3041 if (T->isFunctionType() || T->isArrayType()) {
3042 // Decay functions and arrays.
3043 Expr *RefE = (Expr *)RefExpr.get();
3044 DefaultFunctionArrayConversion(RefE);
3045 if (RefE != RefExpr.get()) {
3046 RefExpr.release();
3047 RefExpr = Owned(RefE);
3048 }
3049
3050 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00003051 }
3052
Douglas Gregorb7a09262010-04-01 18:32:35 +00003053 // Take the address of everything else
3054 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregor02024a92010-03-28 02:42:43 +00003055 }
3056
3057 // If the non-type template parameter has reference type, qualify the
3058 // resulting declaration reference with the extra qualifiers on the
3059 // type that the reference refers to.
3060 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3061 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3062
3063 return BuildDeclRefExpr(VD, T, Loc);
3064}
3065
3066/// \brief Construct a new expression that refers to the given
3067/// integral template argument with the given source-location
3068/// information.
3069///
3070/// This routine takes care of the mapping from an integral template
3071/// argument (which may have any integral type) to the appropriate
3072/// literal value.
3073Sema::OwningExprResult
3074Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3075 SourceLocation Loc) {
3076 assert(Arg.getKind() == TemplateArgument::Integral &&
3077 "Operation is only value for integral template arguments");
3078 QualType T = Arg.getIntegralType();
3079 if (T->isCharType() || T->isWideCharType())
3080 return Owned(new (Context) CharacterLiteral(
3081 Arg.getAsIntegral()->getZExtValue(),
3082 T->isWideCharType(),
3083 T,
3084 Loc));
3085 if (T->isBooleanType())
3086 return Owned(new (Context) CXXBoolLiteralExpr(
3087 Arg.getAsIntegral()->getBoolValue(),
3088 T,
3089 Loc));
3090
3091 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3092}
3093
3094
Douglas Gregorddc29e12009-02-06 22:42:48 +00003095/// \brief Determine whether the given template parameter lists are
3096/// equivalent.
3097///
Mike Stump1eb44332009-09-09 15:08:12 +00003098/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00003099/// source code as part of a new template declaration.
3100///
3101/// \param Old The old template parameter list, typically found via
3102/// name lookup of the template declared with this template parameter
3103/// list.
3104///
3105/// \param Complain If true, this routine will produce a diagnostic if
3106/// the template parameter lists are not equivalent.
3107///
Douglas Gregorfb898e12009-11-12 16:20:59 +00003108/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00003109///
3110/// \param TemplateArgLoc If this source location is valid, then we
3111/// are actually checking the template parameter list of a template
3112/// argument (New) against the template parameter list of its
3113/// corresponding template template parameter (Old). We produce
3114/// slightly different diagnostics in this scenario.
3115///
Douglas Gregorddc29e12009-02-06 22:42:48 +00003116/// \returns True if the template parameter lists are equal, false
3117/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003118bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00003119Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3120 TemplateParameterList *Old,
3121 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003122 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003123 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003124 if (Old->size() != New->size()) {
3125 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003126 unsigned NextDiag = diag::err_template_param_list_different_arity;
3127 if (TemplateArgLoc.isValid()) {
3128 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3129 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00003130 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003131 Diag(New->getTemplateLoc(), NextDiag)
3132 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00003133 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003134 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00003135 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003136 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003137 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3138 }
3139
3140 return false;
3141 }
3142
3143 for (TemplateParameterList::iterator OldParm = Old->begin(),
3144 OldParmEnd = Old->end(), NewParm = New->begin();
3145 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3146 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003147 if (Complain) {
3148 unsigned NextDiag = diag::err_template_param_different_kind;
3149 if (TemplateArgLoc.isValid()) {
3150 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3151 NextDiag = diag::note_template_param_different_kind;
3152 }
3153 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003154 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003155 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003156 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00003157 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003158 return false;
3159 }
3160
3161 if (isa<TemplateTypeParmDecl>(*OldParm)) {
3162 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00003163 // know we're at the same index).
Mike Stump1eb44332009-09-09 15:08:12 +00003164 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003165 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3166 // The types of non-type template parameters must agree.
3167 NonTypeTemplateParmDecl *NewNTTP
3168 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00003169
3170 // If we are matching a template template argument to a template
3171 // template parameter and one of the non-type template parameter types
3172 // is dependent, then we must wait until template instantiation time
3173 // to actually compare the arguments.
3174 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3175 (OldNTTP->getType()->isDependentType() ||
3176 NewNTTP->getType()->isDependentType()))
3177 continue;
3178
Douglas Gregorddc29e12009-02-06 22:42:48 +00003179 if (Context.getCanonicalType(OldNTTP->getType()) !=
3180 Context.getCanonicalType(NewNTTP->getType())) {
3181 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003182 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3183 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003184 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003185 diag::err_template_arg_template_params_mismatch);
3186 NextDiag = diag::note_template_nontype_parm_different_type;
3187 }
3188 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003189 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00003190 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00003191 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00003192 diag::note_template_nontype_parm_prev_declaration)
3193 << OldNTTP->getType();
3194 }
3195 return false;
3196 }
3197 } else {
3198 // The template parameter lists of template template
3199 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00003200 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00003201 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00003202 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003203 = cast<TemplateTemplateParmDecl>(*OldParm);
3204 TemplateTemplateParmDecl *NewTTP
3205 = cast<TemplateTemplateParmDecl>(*NewParm);
3206 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3207 OldTTP->getTemplateParameters(),
3208 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003209 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00003210 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003211 return false;
3212 }
3213 }
3214
3215 return true;
3216}
3217
3218/// \brief Check whether a template can be declared within this scope.
3219///
3220/// If the template declaration is valid in this scope, returns
3221/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003222bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003223Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003224 // Find the nearest enclosing declaration scope.
3225 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3226 (S->getFlags() & Scope::TemplateParamScope) != 0)
3227 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003228
Douglas Gregorddc29e12009-02-06 22:42:48 +00003229 // C++ [temp]p2:
3230 // A template-declaration can appear only as a namespace scope or
3231 // class scope declaration.
3232 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003233 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3234 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003235 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003236 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003237
Eli Friedman1503f772009-07-31 01:43:05 +00003238 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003239 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003240
3241 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3242 return false;
3243
Mike Stump1eb44332009-09-09 15:08:12 +00003244 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003245 diag::err_template_outside_namespace_or_class_scope)
3246 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003247}
Douglas Gregorcc636682009-02-17 23:15:12 +00003248
Douglas Gregord5cb8762009-10-07 00:13:32 +00003249/// \brief Determine what kind of template specialization the given declaration
3250/// is.
3251static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3252 if (!D)
3253 return TSK_Undeclared;
3254
Douglas Gregorf6b11852009-10-08 15:14:33 +00003255 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3256 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003257 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3258 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003259 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3260 return Var->getTemplateSpecializationKind();
3261
Douglas Gregord5cb8762009-10-07 00:13:32 +00003262 return TSK_Undeclared;
3263}
3264
Douglas Gregor9302da62009-10-14 23:50:59 +00003265/// \brief Check whether a specialization is well-formed in the current
3266/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003267///
Douglas Gregor9302da62009-10-14 23:50:59 +00003268/// This routine determines whether a template specialization can be declared
3269/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003270///
3271/// \param S the semantic analysis object for which this check is being
3272/// performed.
3273///
3274/// \param Specialized the entity being specialized or instantiated, which
3275/// may be a kind of template (class template, function template, etc.) or
3276/// a member of a class template (member function, static data member,
3277/// member class).
3278///
3279/// \param PrevDecl the previous declaration of this entity, if any.
3280///
3281/// \param Loc the location of the explicit specialization or instantiation of
3282/// this entity.
3283///
3284/// \param IsPartialSpecialization whether this is a partial specialization of
3285/// a class template.
3286///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003287/// \returns true if there was an error that we cannot recover from, false
3288/// otherwise.
3289static bool CheckTemplateSpecializationScope(Sema &S,
3290 NamedDecl *Specialized,
3291 NamedDecl *PrevDecl,
3292 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003293 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003294 // Keep these "kind" numbers in sync with the %select statements in the
3295 // various diagnostics emitted by this routine.
3296 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003297 bool isTemplateSpecialization = false;
3298 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003299 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003300 isTemplateSpecialization = true;
3301 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003302 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003303 isTemplateSpecialization = true;
3304 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003305 EntityKind = 3;
3306 else if (isa<VarDecl>(Specialized))
3307 EntityKind = 4;
3308 else if (isa<RecordDecl>(Specialized))
3309 EntityKind = 5;
3310 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003311 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3312 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003313 return true;
3314 }
3315
Douglas Gregor88b70942009-02-25 22:02:03 +00003316 // C++ [temp.expl.spec]p2:
3317 // An explicit specialization shall be declared in the namespace
3318 // of which the template is a member, or, for member templates, in
3319 // the namespace of which the enclosing class or enclosing class
3320 // template is a member. An explicit specialization of a member
3321 // function, member class or static data member of a class
3322 // template shall be declared in the namespace of which the class
3323 // template is a member. Such a declaration may also be a
3324 // definition. If the declaration is not a definition, the
3325 // specialization may be defined later in the name- space in which
3326 // the explicit specialization was declared, or in a namespace
3327 // that encloses the one in which the explicit specialization was
3328 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003329 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3330 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003331 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003332 return true;
3333 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003334
Douglas Gregor0a407472009-10-07 17:30:37 +00003335 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3336 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003337 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003338 return true;
3339 }
3340
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003341 // C++ [temp.class.spec]p6:
3342 // A class template partial specialization may be declared or redeclared
3343 // in any namespace scope in which its definition may be defined (14.5.1
3344 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003345 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003346 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003347 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003348 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003349 if ((!PrevDecl ||
3350 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3351 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3352 // There is no prior declaration of this entity, so this
3353 // specialization must be in the same context as the template
3354 // itself.
3355 if (!DC->Equals(SpecializedContext)) {
3356 if (isa<TranslationUnitDecl>(SpecializedContext))
3357 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3358 << EntityKind << Specialized;
3359 else if (isa<NamespaceDecl>(SpecializedContext))
3360 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3361 << EntityKind << Specialized
3362 << cast<NamedDecl>(SpecializedContext);
3363
3364 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3365 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003366 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003367 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003368
3369 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003370 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003371 // Note that HandleDeclarator() performs this check for explicit
3372 // specializations of function templates, static data members, and member
3373 // functions, so we skip the check here for those kinds of entities.
3374 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003375 // Should we refactor that check, so that it occurs later?
3376 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003377 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3378 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003379 if (isa<TranslationUnitDecl>(SpecializedContext))
3380 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3381 << EntityKind << Specialized;
3382 else if (isa<NamespaceDecl>(SpecializedContext))
3383 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3384 << EntityKind << Specialized
3385 << cast<NamedDecl>(SpecializedContext);
3386
Douglas Gregor9302da62009-10-14 23:50:59 +00003387 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003388 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003389
3390 // FIXME: check for specialization-after-instantiation errors and such.
3391
Douglas Gregor88b70942009-02-25 22:02:03 +00003392 return false;
3393}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003394
Douglas Gregore94866f2009-06-12 21:21:02 +00003395/// \brief Check the non-type template arguments of a class template
3396/// partial specialization according to C++ [temp.class.spec]p9.
3397///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003398/// \param TemplateParams the template parameters of the primary class
3399/// template.
3400///
3401/// \param TemplateArg the template arguments of the class template
3402/// partial specialization.
3403///
3404/// \param MirrorsPrimaryTemplate will be set true if the class
3405/// template partial specialization arguments are identical to the
3406/// implicit template arguments of the primary template. This is not
3407/// necessarily an error (C++0x), and it is left to the caller to diagnose
3408/// this condition when it is an error.
3409///
Douglas Gregore94866f2009-06-12 21:21:02 +00003410/// \returns true if there was an error, false otherwise.
3411bool Sema::CheckClassTemplatePartialSpecializationArgs(
3412 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00003413 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003414 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003415 // FIXME: the interface to this function will have to change to
3416 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003417 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003418
Anders Carlssonfb250522009-06-23 01:26:57 +00003419 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00003420
Douglas Gregore94866f2009-06-12 21:21:02 +00003421 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003422 // Determine whether the template argument list of the partial
3423 // specialization is identical to the implicit argument list of
3424 // the primary template. The caller may need to diagnostic this as
3425 // an error per C++ [temp.class.spec]p9b3.
3426 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003427 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003428 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3429 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003430 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003431 MirrorsPrimaryTemplate = false;
3432 } else if (TemplateTemplateParmDecl *TTP
3433 = dyn_cast<TemplateTemplateParmDecl>(
3434 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003435 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003436 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003437 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003438 if (!ArgDecl ||
3439 ArgDecl->getIndex() != TTP->getIndex() ||
3440 ArgDecl->getDepth() != TTP->getDepth())
3441 MirrorsPrimaryTemplate = false;
3442 }
3443 }
3444
Mike Stump1eb44332009-09-09 15:08:12 +00003445 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003446 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003447 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003448 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003449 }
3450
Anders Carlsson6360be72009-06-13 18:20:51 +00003451 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003452 if (!ArgExpr) {
3453 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003454 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003455 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003456
3457 // C++ [temp.class.spec]p8:
3458 // A non-type argument is non-specialized if it is the name of a
3459 // non-type parameter. All other non-type arguments are
3460 // specialized.
3461 //
3462 // Below, we check the two conditions that only apply to
3463 // specialized non-type arguments, so skip any non-specialized
3464 // arguments.
3465 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003466 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003467 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003468 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003469 (Param->getIndex() != NTTP->getIndex() ||
3470 Param->getDepth() != NTTP->getDepth()))
3471 MirrorsPrimaryTemplate = false;
3472
Douglas Gregore94866f2009-06-12 21:21:02 +00003473 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003474 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003475
3476 // C++ [temp.class.spec]p9:
3477 // Within the argument list of a class template partial
3478 // specialization, the following restrictions apply:
3479 // -- A partially specialized non-type argument expression
3480 // shall not involve a template parameter of the partial
3481 // specialization except when the argument expression is a
3482 // simple identifier.
3483 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003484 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003485 diag::err_dependent_non_type_arg_in_partial_spec)
3486 << ArgExpr->getSourceRange();
3487 return true;
3488 }
3489
3490 // -- The type of a template parameter corresponding to a
3491 // specialized non-type argument shall not be dependent on a
3492 // parameter of the specialization.
3493 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003494 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003495 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3496 << Param->getType()
3497 << ArgExpr->getSourceRange();
3498 Diag(Param->getLocation(), diag::note_template_param_here);
3499 return true;
3500 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003501
3502 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003503 }
3504
3505 return false;
3506}
3507
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003508/// \brief Retrieve the previous declaration of the given declaration.
3509static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3510 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3511 return VD->getPreviousDeclaration();
3512 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3513 return FD->getPreviousDeclaration();
3514 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3515 return TD->getPreviousDeclaration();
3516 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3517 return TD->getPreviousDeclaration();
3518 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3519 return FTD->getPreviousDeclaration();
3520 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3521 return CTD->getPreviousDeclaration();
3522 return 0;
3523}
3524
Douglas Gregor212e81c2009-03-25 00:13:59 +00003525Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003526Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3527 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00003528 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003529 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003530 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00003531 SourceLocation TemplateNameLoc,
3532 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00003533 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00003534 SourceLocation RAngleLoc,
3535 AttributeList *Attr,
3536 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003537 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00003538
Douglas Gregorcc636682009-02-17 23:15:12 +00003539 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00003540 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003541 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00003542 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3543
3544 if (!ClassTemplate) {
3545 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3546 << (Name.getAsTemplateDecl() &&
3547 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3548 return true;
3549 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003550
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003551 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003552 bool isPartialSpecialization = false;
3553
Douglas Gregor88b70942009-02-25 22:02:03 +00003554 // Check the validity of the template headers that introduce this
3555 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003556 // FIXME: We probably shouldn't complain about these headers for
3557 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00003558 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00003559 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3560 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003561 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00003562 TUK == TUK_Friend,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003563 isExplicitSpecialization);
Douglas Gregor05396e22009-08-25 17:23:04 +00003564 if (TemplateParams && TemplateParams->size() > 0) {
3565 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003566
Douglas Gregor05396e22009-08-25 17:23:04 +00003567 // C++ [temp.class.spec]p10:
3568 // The template parameter list of a specialization shall not
3569 // contain default template argument values.
3570 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3571 Decl *Param = TemplateParams->getParam(I);
3572 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3573 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003574 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003575 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00003576 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003577 }
3578 } else if (NonTypeTemplateParmDecl *NTTP
3579 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3580 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003581 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003582 diag::err_default_arg_in_partial_spec)
3583 << DefArg->getSourceRange();
3584 NTTP->setDefaultArgument(0);
3585 DefArg->Destroy(Context);
3586 }
3587 } else {
3588 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003589 if (TTP->hasDefaultArgument()) {
3590 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003591 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003592 << TTP->getDefaultArgument().getSourceRange();
3593 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003594 }
3595 }
3596 }
Douglas Gregora735b202009-10-13 14:39:41 +00003597 } else if (TemplateParams) {
3598 if (TUK == TUK_Friend)
3599 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00003600 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00003601 SourceRange(TemplateParams->getTemplateLoc(),
3602 TemplateParams->getRAngleLoc()))
3603 << SourceRange(LAngleLoc, RAngleLoc);
3604 else
3605 isExplicitSpecialization = true;
3606 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003607 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00003608 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003609 isExplicitSpecialization = true;
3610 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003611
Douglas Gregorcc636682009-02-17 23:15:12 +00003612 // Check that the specialization uses the same tag kind as the
3613 // original template.
3614 TagDecl::TagKind Kind;
3615 switch (TagSpec) {
3616 default: assert(0 && "Unknown tag type!");
3617 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3618 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3619 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3620 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003621 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003622 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003623 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003624 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003625 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00003626 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003627 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003628 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003629 diag::note_previous_use);
3630 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3631 }
3632
Douglas Gregor40808ce2009-03-09 23:48:35 +00003633 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00003634 TemplateArgumentListInfo TemplateArgs;
3635 TemplateArgs.setLAngleLoc(LAngleLoc);
3636 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00003637 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003638
Douglas Gregorcc636682009-02-17 23:15:12 +00003639 // Check that the template argument list is well-formed for this
3640 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003641 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3642 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00003643 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3644 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003645 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003646
Mike Stump1eb44332009-09-09 15:08:12 +00003647 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003648 ClassTemplate->getTemplateParameters()->size()) &&
3649 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003650
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003651 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003652 // corresponds to these arguments.
3653 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003654 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003655 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003656 if (CheckClassTemplatePartialSpecializationArgs(
3657 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003658 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003659 return true;
3660
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003661 if (MirrorsPrimaryTemplate) {
3662 // C++ [temp.class.spec]p9b3:
3663 //
Mike Stump1eb44332009-09-09 15:08:12 +00003664 // -- The argument list of the specialization shall not be identical
3665 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003666 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003667 << (TUK == TUK_Definition)
Douglas Gregor849b2432010-03-31 17:46:05 +00003668 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003669 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003670 ClassTemplate->getIdentifier(),
3671 TemplateNameLoc,
3672 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003673 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003674 AS_none);
3675 }
3676
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003677 // FIXME: Diagnose friend partial specializations
3678
Douglas Gregorde090962010-02-09 00:37:32 +00003679 if (!Name.isDependent() &&
3680 !TemplateSpecializationType::anyDependentTemplateArguments(
3681 TemplateArgs.getArgumentArray(),
3682 TemplateArgs.size())) {
3683 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3684 << ClassTemplate->getDeclName();
3685 isPartialSpecialization = false;
3686 } else {
3687 // FIXME: Template parameter list matters, too
3688 ClassTemplatePartialSpecializationDecl::Profile(ID,
3689 Converted.getFlatArguments(),
3690 Converted.flatSize(),
3691 Context);
3692 }
3693 }
3694
3695 if (!isPartialSpecialization)
Anders Carlsson1c5976e2009-06-05 03:43:12 +00003696 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003697 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003698 Converted.flatSize(),
3699 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00003700 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003701 ClassTemplateSpecializationDecl *PrevDecl = 0;
3702
3703 if (isPartialSpecialization)
3704 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00003705 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003706 InsertPos);
3707 else
3708 PrevDecl
3709 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003710
3711 ClassTemplateSpecializationDecl *Specialization = 0;
3712
Douglas Gregor88b70942009-02-25 22:02:03 +00003713 // Check whether we can declare a class template specialization in
3714 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003715 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003716 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003717 TemplateNameLoc,
3718 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003719 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003720
Douglas Gregorb88e8882009-07-30 17:40:51 +00003721 // The canonical type
3722 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003723 if (PrevDecl &&
3724 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00003725 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003726 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003727 // arguments was referenced but not declared, or we're only
3728 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003729 // declaration node as our own, updating its source location to
3730 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003731 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003732 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003733 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003734 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003735 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003736 // Build the canonical type that describes the converted template
3737 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00003738 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3739 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb88e8882009-07-30 17:40:51 +00003740 Converted.getFlatArguments(),
3741 Converted.flatSize());
3742
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003743 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003744 ClassTemplatePartialSpecializationDecl *PrevPartial
3745 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00003746 ClassTemplatePartialSpecializationDecl *Partial
3747 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003748 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003749 TemplateNameLoc,
3750 TemplateParams,
3751 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003752 Converted,
John McCalld5532b62009-11-23 01:53:49 +00003753 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00003754 CanonType,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003755 PrevPartial);
John McCallb6217662010-03-15 10:12:16 +00003756 SetNestedNameSpecifier(Partial, SS);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003757
3758 if (PrevPartial) {
3759 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3760 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3761 } else {
3762 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3763 }
3764 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003765
Douglas Gregored9c0f92009-10-29 00:04:11 +00003766 // If we are providing an explicit specialization of a member class
3767 // template specialization, make a note of that.
3768 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3769 PrevPartial->setMemberSpecialization();
3770
Douglas Gregor031a5882009-06-13 00:26:55 +00003771 // Check that all of the template parameters of the class template
3772 // partial specialization are deducible from the template
3773 // arguments. If not, this class template partial specialization
3774 // will never be used.
3775 llvm::SmallVector<bool, 8> DeducibleParams;
3776 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003777 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003778 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003779 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003780 unsigned NumNonDeducible = 0;
3781 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3782 if (!DeducibleParams[I])
3783 ++NumNonDeducible;
3784
3785 if (NumNonDeducible) {
3786 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3787 << (NumNonDeducible > 1)
3788 << SourceRange(TemplateNameLoc, RAngleLoc);
3789 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3790 if (!DeducibleParams[I]) {
3791 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3792 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003793 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003794 diag::note_partial_spec_unused_parameter)
3795 << Param->getDeclName();
3796 else
Mike Stump1eb44332009-09-09 15:08:12 +00003797 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003798 diag::note_partial_spec_unused_parameter)
3799 << std::string("<anonymous>");
3800 }
3801 }
3802 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003803 } else {
3804 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003805 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003806 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00003807 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorcc636682009-02-17 23:15:12 +00003808 ClassTemplate->getDeclContext(),
3809 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003810 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003811 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003812 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00003813 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregorcc636682009-02-17 23:15:12 +00003814
3815 if (PrevDecl) {
3816 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3817 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3818 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003819 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00003820 InsertPos);
3821 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00003822
3823 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003824 }
3825
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003826 // C++ [temp.expl.spec]p6:
3827 // If a template, a member template or the member of a class template is
3828 // explicitly specialized then that specialization shall be declared
3829 // before the first use of that specialization that would cause an implicit
3830 // instantiation to take place, in every translation unit in which such a
3831 // use occurs; no diagnostic is required.
3832 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003833 bool Okay = false;
3834 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3835 // Is there any previous explicit specialization declaration?
3836 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3837 Okay = true;
3838 break;
3839 }
3840 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003841
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003842 if (!Okay) {
3843 SourceRange Range(TemplateNameLoc, RAngleLoc);
3844 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3845 << Context.getTypeDeclType(Specialization) << Range;
3846
3847 Diag(PrevDecl->getPointOfInstantiation(),
3848 diag::note_instantiation_required_here)
3849 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003850 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003851 return true;
3852 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003853 }
3854
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003855 // If this is not a friend, note that this is an explicit specialization.
3856 if (TUK != TUK_Friend)
3857 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003858
3859 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003860 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00003861 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003862 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003863 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003864 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003865 Diag(Def->getLocation(), diag::note_previous_definition);
3866 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003867 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003868 }
3869 }
3870
Douglas Gregorfc705b82009-02-26 22:19:44 +00003871 // Build the fully-sugared type for this class template
3872 // specialization as the user wrote in the specialization
3873 // itself. This means that we'll pretty-print the type retrieved
3874 // from the specialization's declaration the way that the user
3875 // actually wrote the specialization, rather than formatting the
3876 // name based on the "canonical" representation used to store the
3877 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00003878 TypeSourceInfo *WrittenTy
3879 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3880 TemplateArgs, CanonType);
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003881 if (TUK != TUK_Friend)
3882 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003883 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00003884
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003885 // C++ [temp.expl.spec]p9:
3886 // A template explicit specialization is in the scope of the
3887 // namespace in which the template was defined.
3888 //
3889 // We actually implement this paragraph where we set the semantic
3890 // context (in the creation of the ClassTemplateSpecializationDecl),
3891 // but we also maintain the lexical context where the actual
3892 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00003893 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003894
Douglas Gregorcc636682009-02-17 23:15:12 +00003895 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003896 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00003897 Specialization->startDefinition();
3898
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003899 if (TUK == TUK_Friend) {
3900 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3901 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00003902 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003903 /*FIXME:*/KWLoc);
3904 Friend->setAccess(AS_public);
3905 CurContext->addDecl(Friend);
3906 } else {
3907 // Add the specialization into its lexical context, so that it can
3908 // be seen when iterating through the list of declarations in that
3909 // context. However, specializations are not found by name lookup.
3910 CurContext->addDecl(Specialization);
3911 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003912 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003913}
Douglas Gregord57959a2009-03-27 23:10:48 +00003914
Mike Stump1eb44332009-09-09 15:08:12 +00003915Sema::DeclPtrTy
3916Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00003917 MultiTemplateParamsArg TemplateParameterLists,
3918 Declarator &D) {
3919 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3920}
3921
Mike Stump1eb44332009-09-09 15:08:12 +00003922Sema::DeclPtrTy
3923Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003924 MultiTemplateParamsArg TemplateParameterLists,
3925 Declarator &D) {
3926 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3927 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3928 "Not a function declarator!");
3929 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00003930
Douglas Gregor52591bf2009-06-24 00:54:41 +00003931 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00003932 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00003933 }
Mike Stump1eb44332009-09-09 15:08:12 +00003934
Douglas Gregor52591bf2009-06-24 00:54:41 +00003935 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003936
3937 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003938 move(TemplateParameterLists),
3939 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003940 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003941 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00003942 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00003943 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003944 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3945 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00003946 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00003947}
3948
John McCall75042392010-02-11 01:33:53 +00003949/// \brief Strips various properties off an implicit instantiation
3950/// that has just been explicitly specialized.
3951static void StripImplicitInstantiation(NamedDecl *D) {
3952 D->invalidateAttrs();
3953
3954 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3955 FD->setInlineSpecified(false);
3956 }
3957}
3958
Douglas Gregor454885e2009-10-15 15:54:05 +00003959/// \brief Diagnose cases where we have an explicit template specialization
3960/// before/after an explicit template instantiation, producing diagnostics
3961/// for those cases where they are required and determining whether the
3962/// new specialization/instantiation will have any effect.
3963///
Douglas Gregor454885e2009-10-15 15:54:05 +00003964/// \param NewLoc the location of the new explicit specialization or
3965/// instantiation.
3966///
3967/// \param NewTSK the kind of the new explicit specialization or instantiation.
3968///
3969/// \param PrevDecl the previous declaration of the entity.
3970///
3971/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3972///
3973/// \param PrevPointOfInstantiation if valid, indicates where the previus
3974/// declaration was instantiated (either implicitly or explicitly).
3975///
3976/// \param SuppressNew will be set to true to indicate that the new
3977/// specialization or instantiation has no effect and should be ignored.
3978///
3979/// \returns true if there was an error that should prevent the introduction of
3980/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00003981bool
3982Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3983 TemplateSpecializationKind NewTSK,
3984 NamedDecl *PrevDecl,
3985 TemplateSpecializationKind PrevTSK,
3986 SourceLocation PrevPointOfInstantiation,
3987 bool &SuppressNew) {
Douglas Gregor454885e2009-10-15 15:54:05 +00003988 SuppressNew = false;
3989
3990 switch (NewTSK) {
3991 case TSK_Undeclared:
3992 case TSK_ImplicitInstantiation:
3993 assert(false && "Don't check implicit instantiations here");
3994 return false;
3995
3996 case TSK_ExplicitSpecialization:
3997 switch (PrevTSK) {
3998 case TSK_Undeclared:
3999 case TSK_ExplicitSpecialization:
4000 // Okay, we're just specializing something that is either already
4001 // explicitly specialized or has merely been mentioned without any
4002 // instantiation.
4003 return false;
4004
4005 case TSK_ImplicitInstantiation:
4006 if (PrevPointOfInstantiation.isInvalid()) {
4007 // The declaration itself has not actually been instantiated, so it is
4008 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00004009 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00004010 return false;
4011 }
4012 // Fall through
4013
4014 case TSK_ExplicitInstantiationDeclaration:
4015 case TSK_ExplicitInstantiationDefinition:
4016 assert((PrevTSK == TSK_ImplicitInstantiation ||
4017 PrevPointOfInstantiation.isValid()) &&
4018 "Explicit instantiation without point of instantiation?");
4019
4020 // C++ [temp.expl.spec]p6:
4021 // If a template, a member template or the member of a class template
4022 // is explicitly specialized then that specialization shall be declared
4023 // before the first use of that specialization that would cause an
4024 // implicit instantiation to take place, in every translation unit in
4025 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004026 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4027 // Is there any previous explicit specialization declaration?
4028 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4029 return false;
4030 }
4031
Douglas Gregor0d035142009-10-27 18:42:08 +00004032 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00004033 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004034 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00004035 << (PrevTSK != TSK_ImplicitInstantiation);
4036
4037 return true;
4038 }
4039 break;
4040
4041 case TSK_ExplicitInstantiationDeclaration:
4042 switch (PrevTSK) {
4043 case TSK_ExplicitInstantiationDeclaration:
4044 // This explicit instantiation declaration is redundant (that's okay).
4045 SuppressNew = true;
4046 return false;
4047
4048 case TSK_Undeclared:
4049 case TSK_ImplicitInstantiation:
4050 // We're explicitly instantiating something that may have already been
4051 // implicitly instantiated; that's fine.
4052 return false;
4053
4054 case TSK_ExplicitSpecialization:
4055 // C++0x [temp.explicit]p4:
4056 // For a given set of template parameters, if an explicit instantiation
4057 // of a template appears after a declaration of an explicit
4058 // specialization for that template, the explicit instantiation has no
4059 // effect.
John McCalle97c32f2010-03-02 23:09:38 +00004060 SuppressNew = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004061 return false;
4062
4063 case TSK_ExplicitInstantiationDefinition:
4064 // C++0x [temp.explicit]p10:
4065 // If an entity is the subject of both an explicit instantiation
4066 // declaration and an explicit instantiation definition in the same
4067 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00004068 Diag(NewLoc,
4069 diag::err_explicit_instantiation_declaration_after_definition);
4070 Diag(PrevPointOfInstantiation,
4071 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00004072 assert(PrevPointOfInstantiation.isValid() &&
4073 "Explicit instantiation without point of instantiation?");
4074 SuppressNew = true;
4075 return false;
4076 }
4077 break;
4078
4079 case TSK_ExplicitInstantiationDefinition:
4080 switch (PrevTSK) {
4081 case TSK_Undeclared:
4082 case TSK_ImplicitInstantiation:
4083 // We're explicitly instantiating something that may have already been
4084 // implicitly instantiated; that's fine.
4085 return false;
4086
4087 case TSK_ExplicitSpecialization:
4088 // C++ DR 259, C++0x [temp.explicit]p4:
4089 // For a given set of template parameters, if an explicit
4090 // instantiation of a template appears after a declaration of
4091 // an explicit specialization for that template, the explicit
4092 // instantiation has no effect.
4093 //
4094 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00004095 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00004096 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00004097 if (!getLangOptions().CPlusPlus0x) {
4098 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00004099 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004100 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00004101 diag::note_previous_template_specialization);
4102 }
4103 SuppressNew = true;
4104 return false;
4105
4106 case TSK_ExplicitInstantiationDeclaration:
4107 // We're explicity instantiating a definition for something for which we
4108 // were previously asked to suppress instantiations. That's fine.
4109 return false;
4110
4111 case TSK_ExplicitInstantiationDefinition:
4112 // C++0x [temp.spec]p5:
4113 // For a given template and a given set of template-arguments,
4114 // - an explicit instantiation definition shall appear at most once
4115 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00004116 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00004117 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004118 Diag(PrevPointOfInstantiation,
4119 diag::note_previous_explicit_instantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00004120 SuppressNew = true;
4121 return false;
4122 }
4123 break;
4124 }
4125
4126 assert(false && "Missing specialization/instantiation case?");
4127
4128 return false;
4129}
4130
John McCallaf2094e2010-04-08 09:05:18 +00004131/// \brief Perform semantic analysis for the given dependent function
4132/// template specialization. The only possible way to get a dependent
4133/// function template specialization is with a friend declaration,
4134/// like so:
4135///
4136/// template <class T> void foo(T);
4137/// template <class T> class A {
4138/// friend void foo<>(T);
4139/// };
4140///
4141/// There really isn't any useful analysis we can do here, so we
4142/// just store the information.
4143bool
4144Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4145 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4146 LookupResult &Previous) {
4147 // Remove anything from Previous that isn't a function template in
4148 // the correct context.
4149 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4150 LookupResult::Filter F = Previous.makeFilter();
4151 while (F.hasNext()) {
4152 NamedDecl *D = F.next()->getUnderlyingDecl();
4153 if (!isa<FunctionTemplateDecl>(D) ||
4154 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4155 F.erase();
4156 }
4157 F.done();
4158
4159 // Should this be diagnosed here?
4160 if (Previous.empty()) return true;
4161
4162 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4163 ExplicitTemplateArgs);
4164 return false;
4165}
4166
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004167/// \brief Perform semantic analysis for the given function template
4168/// specialization.
4169///
4170/// This routine performs all of the semantic analysis required for an
4171/// explicit function template specialization. On successful completion,
4172/// the function declaration \p FD will become a function template
4173/// specialization.
4174///
4175/// \param FD the function declaration, which will be updated to become a
4176/// function template specialization.
4177///
4178/// \param HasExplicitTemplateArgs whether any template arguments were
4179/// explicitly provided.
4180///
4181/// \param LAngleLoc the location of the left angle bracket ('<'), if
4182/// template arguments were explicitly provided.
4183///
4184/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4185/// if any.
4186///
4187/// \param NumExplicitTemplateArgs the number of explicitly-provided template
4188/// arguments. This number may be zero even when HasExplicitTemplateArgs is
4189/// true as in, e.g., \c void sort<>(char*, char*);
4190///
4191/// \param RAngleLoc the location of the right angle bracket ('>'), if
4192/// template arguments were explicitly provided.
4193///
4194/// \param PrevDecl the set of declarations that
4195bool
4196Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004197 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004198 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004199 // The set of function template specializations that could match this
4200 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004201 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004202
4203 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall68263142009-11-18 22:49:29 +00004204 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4205 I != E; ++I) {
4206 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4207 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004208 // Only consider templates found within the same semantic lookup scope as
4209 // FD.
4210 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4211 continue;
4212
4213 // C++ [temp.expl.spec]p11:
4214 // A trailing template-argument can be left unspecified in the
4215 // template-id naming an explicit function template specialization
4216 // provided it can be deduced from the function argument type.
4217 // Perform template argument deduction to determine whether we may be
4218 // specializing this template.
4219 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004220 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004221 FunctionDecl *Specialization = 0;
4222 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004223 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004224 FD->getType(),
4225 Specialization,
4226 Info)) {
4227 // FIXME: Template argument deduction failed; record why it failed, so
4228 // that we can provide nifty diagnostics.
4229 (void)TDK;
4230 continue;
4231 }
4232
4233 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004234 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004235 }
4236 }
4237
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004238 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004239 UnresolvedSetIterator Result
4240 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4241 TPOC_Other, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004242 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004243 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004244 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004245 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004246 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004247 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004248 return true;
John McCallc373d482010-01-27 01:50:18 +00004249
4250 // Ignore access information; it doesn't figure into redeclaration checking.
4251 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorc42b6522010-04-09 21:02:29 +00004252 Specialization->setLocation(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004253
4254 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004255 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004256
4257 // If this is a friend declaration, then we're not really declaring
4258 // an explicit specialization.
4259 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004260
Douglas Gregord5cb8762009-10-07 00:13:32 +00004261 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004262 if (!isFriend &&
4263 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004264 Specialization->getPrimaryTemplate(),
4265 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004266 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004267 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004268
4269 // C++ [temp.expl.spec]p6:
4270 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004271 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004272 // before the first use of that specialization that would cause an implicit
4273 // instantiation to take place, in every translation unit in which such a
4274 // use occurs; no diagnostic is required.
4275 FunctionTemplateSpecializationInfo *SpecInfo
4276 = Specialization->getTemplateSpecializationInfo();
4277 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004278
4279 bool SuppressNew = false;
John McCall7ad650f2010-03-24 07:46:06 +00004280 if (!isFriend &&
4281 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004282 TSK_ExplicitSpecialization,
4283 Specialization,
4284 SpecInfo->getTemplateSpecializationKind(),
4285 SpecInfo->getPointOfInstantiation(),
4286 SuppressNew))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004287 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004288
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004289 // Mark the prior declaration as an explicit specialization, so that later
4290 // clients know that this is an explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004291 if (!isFriend)
4292 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004293
4294 // Turn the given function declaration into a function template
4295 // specialization, with the template arguments from the previous
4296 // specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00004297 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004298 new (Context) TemplateArgumentList(
4299 *Specialization->getTemplateSpecializationArgs()),
4300 /*InsertPos=*/0,
John McCall7ad650f2010-03-24 07:46:06 +00004301 SpecInfo->getTemplateSpecializationKind());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004302
4303 // The "previous declaration" for this function template specialization is
4304 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004305 Previous.clear();
4306 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004307 return false;
4308}
4309
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004310/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004311/// specialization.
4312///
4313/// This routine performs all of the semantic analysis required for an
4314/// explicit member function specialization. On successful completion,
4315/// the function declaration \p FD will become a member function
4316/// specialization.
4317///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004318/// \param Member the member declaration, which will be updated to become a
4319/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004320///
John McCall68263142009-11-18 22:49:29 +00004321/// \param Previous the set of declarations, one of which may be specialized
4322/// by this function specialization; the set will be modified to contain the
4323/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004324bool
John McCall68263142009-11-18 22:49:29 +00004325Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004326 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00004327
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004328 // Try to find the member we are instantiating.
4329 NamedDecl *Instantiation = 0;
4330 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004331 MemberSpecializationInfo *MSInfo = 0;
4332
John McCall68263142009-11-18 22:49:29 +00004333 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004334 // Nowhere to look anyway.
4335 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004336 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4337 I != E; ++I) {
4338 NamedDecl *D = (*I)->getUnderlyingDecl();
4339 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004340 if (Context.hasSameType(Function->getType(), Method->getType())) {
4341 Instantiation = Method;
4342 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004343 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004344 break;
4345 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004346 }
4347 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004348 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004349 VarDecl *PrevVar;
4350 if (Previous.isSingleResult() &&
4351 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004352 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004353 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004354 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004355 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004356 }
4357 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004358 CXXRecordDecl *PrevRecord;
4359 if (Previous.isSingleResult() &&
4360 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4361 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004362 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004363 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004364 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004365 }
4366
4367 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004368 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004369 // specializations are always out-of-line, the caller will complain about
4370 // this mismatch later.
4371 return false;
4372 }
John McCall77e8b112010-04-13 20:37:33 +00004373
4374 // If this is a friend, just bail out here before we start turning
4375 // things into explicit specializations.
4376 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4377 // Preserve instantiation information.
4378 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4379 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4380 cast<CXXMethodDecl>(InstantiatedFrom),
4381 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4382 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4383 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4384 cast<CXXRecordDecl>(InstantiatedFrom),
4385 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4386 }
4387
4388 Previous.clear();
4389 Previous.addDecl(Instantiation);
4390 return false;
4391 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004392
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004393 // Make sure that this is a specialization of a member.
4394 if (!InstantiatedFrom) {
4395 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4396 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004397 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4398 return true;
4399 }
4400
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004401 // C++ [temp.expl.spec]p6:
4402 // If a template, a member template or the member of a class template is
4403 // explicitly specialized then that spe- cialization shall be declared
4404 // before the first use of that specialization that would cause an implicit
4405 // instantiation to take place, in every translation unit in which such a
4406 // use occurs; no diagnostic is required.
4407 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004408
4409 bool SuppressNew = false;
4410 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4411 TSK_ExplicitSpecialization,
4412 Instantiation,
4413 MSInfo->getTemplateSpecializationKind(),
4414 MSInfo->getPointOfInstantiation(),
4415 SuppressNew))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004416 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004417
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004418 // Check the scope of this explicit specialization.
4419 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004420 InstantiatedFrom,
4421 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004422 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004423 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004424
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004425 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004426 // the original declaration to note that it is an explicit specialization
4427 // (if it was previously an implicit instantiation). This latter step
4428 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004429 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004430 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4431 if (InstantiationFunction->getTemplateSpecializationKind() ==
4432 TSK_ImplicitInstantiation) {
4433 InstantiationFunction->setTemplateSpecializationKind(
4434 TSK_ExplicitSpecialization);
4435 InstantiationFunction->setLocation(Member->getLocation());
4436 }
4437
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004438 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4439 cast<CXXMethodDecl>(InstantiatedFrom),
4440 TSK_ExplicitSpecialization);
4441 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004442 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4443 if (InstantiationVar->getTemplateSpecializationKind() ==
4444 TSK_ImplicitInstantiation) {
4445 InstantiationVar->setTemplateSpecializationKind(
4446 TSK_ExplicitSpecialization);
4447 InstantiationVar->setLocation(Member->getLocation());
4448 }
4449
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004450 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4451 cast<VarDecl>(InstantiatedFrom),
4452 TSK_ExplicitSpecialization);
4453 } else {
4454 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004455 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4456 if (InstantiationClass->getTemplateSpecializationKind() ==
4457 TSK_ImplicitInstantiation) {
4458 InstantiationClass->setTemplateSpecializationKind(
4459 TSK_ExplicitSpecialization);
4460 InstantiationClass->setLocation(Member->getLocation());
4461 }
4462
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004463 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004464 cast<CXXRecordDecl>(InstantiatedFrom),
4465 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004466 }
4467
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004468 // Save the caller the trouble of having to figure out which declaration
4469 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004470 Previous.clear();
4471 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004472 return false;
4473}
4474
Douglas Gregor558c0322009-10-14 23:41:34 +00004475/// \brief Check the scope of an explicit instantiation.
4476static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4477 SourceLocation InstLoc,
4478 bool WasQualifiedName) {
4479 DeclContext *ExpectedContext
4480 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4481 DeclContext *CurContext = S.CurContext->getLookupContext();
4482
4483 // C++0x [temp.explicit]p2:
4484 // An explicit instantiation shall appear in an enclosing namespace of its
4485 // template.
4486 //
4487 // This is DR275, which we do not retroactively apply to C++98/03.
4488 if (S.getLangOptions().CPlusPlus0x &&
4489 !CurContext->Encloses(ExpectedContext)) {
4490 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4491 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4492 << D << NS;
4493 else
4494 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4495 << D;
4496 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4497 return;
4498 }
4499
4500 // C++0x [temp.explicit]p2:
4501 // If the name declared in the explicit instantiation is an unqualified
4502 // name, the explicit instantiation shall appear in the namespace where
4503 // its template is declared or, if that namespace is inline (7.3.1), any
4504 // namespace from its enclosing namespace set.
4505 if (WasQualifiedName)
4506 return;
4507
4508 if (CurContext->Equals(ExpectedContext))
4509 return;
4510
4511 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4512 << D << ExpectedContext;
4513 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4514}
4515
4516/// \brief Determine whether the given scope specifier has a template-id in it.
4517static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4518 if (!SS.isSet())
4519 return false;
4520
4521 // C++0x [temp.explicit]p2:
4522 // If the explicit instantiation is for a member function, a member class
4523 // or a static data member of a class template specialization, the name of
4524 // the class template specialization in the qualified-id for the member
4525 // name shall be a simple-template-id.
4526 //
4527 // C++98 has the same restriction, just worded differently.
4528 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4529 NNS; NNS = NNS->getPrefix())
4530 if (Type *T = NNS->getAsType())
4531 if (isa<TemplateSpecializationType>(T))
4532 return true;
4533
4534 return false;
4535}
4536
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004537// Explicit instantiation of a class template specialization
Douglas Gregor45f96552009-09-04 06:33:52 +00004538// FIXME: Implement extern template semantics
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004539Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004540Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004541 SourceLocation ExternLoc,
4542 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004543 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004544 SourceLocation KWLoc,
4545 const CXXScopeSpec &SS,
4546 TemplateTy TemplateD,
4547 SourceLocation TemplateNameLoc,
4548 SourceLocation LAngleLoc,
4549 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004550 SourceLocation RAngleLoc,
4551 AttributeList *Attr) {
4552 // Find the class template we're specializing
4553 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004554 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004555 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4556
4557 // Check that the specialization uses the same tag kind as the
4558 // original template.
4559 TagDecl::TagKind Kind;
4560 switch (TagSpec) {
4561 default: assert(0 && "Unknown tag type!");
4562 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4563 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4564 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4565 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004566 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004567 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004568 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004569 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004570 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004571 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004572 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004573 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004574 diag::note_previous_use);
4575 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4576 }
4577
Douglas Gregor558c0322009-10-14 23:41:34 +00004578 // C++0x [temp.explicit]p2:
4579 // There are two forms of explicit instantiation: an explicit instantiation
4580 // definition and an explicit instantiation declaration. An explicit
4581 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00004582 TemplateSpecializationKind TSK
4583 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4584 : TSK_ExplicitInstantiationDeclaration;
4585
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004586 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004587 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004588 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004589
4590 // Check that the template argument list is well-formed for this
4591 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00004592 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4593 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00004594 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4595 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004596 return true;
4597
Mike Stump1eb44332009-09-09 15:08:12 +00004598 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004599 ClassTemplate->getTemplateParameters()->size()) &&
4600 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004601
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004602 // Find the class template specialization declaration that
4603 // corresponds to these arguments.
4604 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00004605 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00004606 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00004607 Converted.flatSize(),
4608 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004609 void *InsertPos = 0;
4610 ClassTemplateSpecializationDecl *PrevDecl
4611 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4612
Douglas Gregord5cb8762009-10-07 00:13:32 +00004613 // C++0x [temp.explicit]p2:
4614 // [...] An explicit instantiation shall appear in an enclosing
4615 // namespace of its template. [...]
4616 //
4617 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004618 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4619 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00004620
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004621 ClassTemplateSpecializationDecl *Specialization = 0;
4622
Douglas Gregord78f5982009-11-25 06:01:46 +00004623 bool ReusedDecl = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004624 if (PrevDecl) {
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004625 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004626 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004627 PrevDecl,
4628 PrevDecl->getSpecializationKind(),
4629 PrevDecl->getPointOfInstantiation(),
4630 SuppressNew))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004631 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004632
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004633 if (SuppressNew)
Douglas Gregor52604ab2009-09-11 21:19:12 +00004634 return DeclPtrTy::make(PrevDecl);
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004635
Douglas Gregor52604ab2009-09-11 21:19:12 +00004636 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4637 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4638 // Since the only prior class template specialization with these
4639 // arguments was referenced but not declared, reuse that
4640 // declaration node as our own, updating its source location to
4641 // reflect our new declaration.
4642 Specialization = PrevDecl;
4643 Specialization->setLocation(TemplateNameLoc);
4644 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00004645 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00004646 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004647 }
Douglas Gregor52604ab2009-09-11 21:19:12 +00004648
4649 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004650 // Create a new class template specialization declaration node for
4651 // this explicit specialization.
4652 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00004653 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004654 ClassTemplate->getDeclContext(),
4655 TemplateNameLoc,
4656 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00004657 Converted, PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004658 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004659
Douglas Gregor52604ab2009-09-11 21:19:12 +00004660 if (PrevDecl) {
4661 // Remove the previous declaration from the folding set, since we want
4662 // to introduce a new declaration.
4663 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4664 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4665 }
4666
4667 // Insert the new specialization.
4668 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004669 }
4670
4671 // Build the fully-sugared type for this explicit instantiation as
4672 // the user wrote in the explicit instantiation itself. This means
4673 // that we'll pretty-print the type retrieved from the
4674 // specialization's declaration the way that the user actually wrote
4675 // the explicit instantiation, rather than formatting the name based
4676 // on the "canonical" representation used to store the template
4677 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004678 TypeSourceInfo *WrittenTy
4679 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4680 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004681 Context.getTypeDeclType(Specialization));
4682 Specialization->setTypeAsWritten(WrittenTy);
4683 TemplateArgsIn.release();
4684
Douglas Gregord78f5982009-11-25 06:01:46 +00004685 if (!ReusedDecl) {
4686 // Add the explicit instantiation into its lexical context. However,
4687 // since explicit instantiations are never found by name lookup, we
4688 // just put it into the declaration context directly.
4689 Specialization->setLexicalDeclContext(CurContext);
4690 CurContext->addDecl(Specialization);
4691 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004692
4693 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004694 // A definition of a class template or class member template
4695 // shall be in scope at the point of the explicit instantiation of
4696 // the class template or class member template.
4697 //
4698 // This check comes when we actually try to perform the
4699 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004700 ClassTemplateSpecializationDecl *Def
4701 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004702 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004703 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004704 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor0d035142009-10-27 18:42:08 +00004705
4706 // Instantiate the members of this class template specialization.
4707 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004708 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004709 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00004710 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4711
4712 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4713 // TSK_ExplicitInstantiationDefinition
4714 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4715 TSK == TSK_ExplicitInstantiationDefinition)
4716 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004717
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004718 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004719 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004720
4721 return DeclPtrTy::make(Specialization);
4722}
4723
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004724// Explicit instantiation of a member class of a class template.
4725Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004726Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004727 SourceLocation ExternLoc,
4728 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004729 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004730 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004731 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004732 IdentifierInfo *Name,
4733 SourceLocation NameLoc,
4734 AttributeList *Attr) {
4735
Douglas Gregor402abb52009-05-28 23:31:59 +00004736 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004737 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00004738 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004739 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00004740 MultiTemplateParamsArg(*this, 0, 0),
4741 Owned, IsDependent);
4742 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4743
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004744 if (!TagD)
4745 return true;
4746
4747 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4748 if (Tag->isEnum()) {
4749 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4750 << Context.getTypeDeclType(Tag);
4751 return true;
4752 }
4753
Douglas Gregord0c87372009-05-27 17:30:49 +00004754 if (Tag->isInvalidDecl())
4755 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004756
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004757 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4758 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4759 if (!Pattern) {
4760 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4761 << Context.getTypeDeclType(Record);
4762 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4763 return true;
4764 }
4765
Douglas Gregor558c0322009-10-14 23:41:34 +00004766 // C++0x [temp.explicit]p2:
4767 // If the explicit instantiation is for a class or member class, the
4768 // elaborated-type-specifier in the declaration shall include a
4769 // simple-template-id.
4770 //
4771 // C++98 has the same restriction, just worded differently.
4772 if (!ScopeSpecifierHasTemplateId(SS))
4773 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4774 << Record << SS.getRange();
4775
4776 // C++0x [temp.explicit]p2:
4777 // There are two forms of explicit instantiation: an explicit instantiation
4778 // definition and an explicit instantiation declaration. An explicit
4779 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004780 TemplateSpecializationKind TSK
4781 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4782 : TSK_ExplicitInstantiationDeclaration;
4783
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004784 // C++0x [temp.explicit]p2:
4785 // [...] An explicit instantiation shall appear in an enclosing
4786 // namespace of its template. [...]
4787 //
4788 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004789 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004790
4791 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004792 CXXRecordDecl *PrevDecl
4793 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00004794 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00004795 PrevDecl = Record;
4796 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004797 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4798 bool SuppressNew = false;
4799 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004800 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004801 PrevDecl,
4802 MSInfo->getTemplateSpecializationKind(),
4803 MSInfo->getPointOfInstantiation(),
4804 SuppressNew))
4805 return true;
4806 if (SuppressNew)
4807 return TagD;
4808 }
4809
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004810 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00004811 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004812 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004813 // C++ [temp.explicit]p3:
4814 // A definition of a member class of a class template shall be in scope
4815 // at the point of an explicit instantiation of the member class.
4816 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00004817 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004818 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004819 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4820 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004821 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4822 << Pattern;
4823 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004824 } else {
4825 if (InstantiateClass(NameLoc, Record, Def,
4826 getTemplateInstantiationArgs(Record),
4827 TSK))
4828 return true;
4829
Douglas Gregor952b0172010-02-11 01:04:33 +00004830 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00004831 if (!RecordDef)
4832 return true;
4833 }
4834 }
4835
4836 // Instantiate all of the members of the class.
4837 InstantiateClassMembers(NameLoc, RecordDef,
4838 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004839
Mike Stump390b4cc2009-05-16 07:39:55 +00004840 // FIXME: We don't have any representation for explicit instantiations of
4841 // member classes. Such a representation is not needed for compilation, but it
4842 // should be available for clients that want to see all of the declarations in
4843 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004844 return TagD;
4845}
4846
Douglas Gregord5a423b2009-09-25 18:43:00 +00004847Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4848 SourceLocation ExternLoc,
4849 SourceLocation TemplateLoc,
4850 Declarator &D) {
4851 // Explicit instantiations always require a name.
4852 DeclarationName Name = GetNameForDeclarator(D);
4853 if (!Name) {
4854 if (!D.isInvalidType())
4855 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4856 diag::err_explicit_instantiation_requires_name)
4857 << D.getDeclSpec().getSourceRange()
4858 << D.getSourceRange();
4859
4860 return true;
4861 }
4862
4863 // The scope passed in may not be a decl scope. Zip up the scope tree until
4864 // we find one that is.
4865 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4866 (S->getFlags() & Scope::TemplateParamScope) != 0)
4867 S = S->getParent();
4868
4869 // Determine the type of the declaration.
4870 QualType R = GetTypeForDeclarator(D, S, 0);
4871 if (R.isNull())
4872 return true;
4873
4874 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4875 // Cannot explicitly instantiate a typedef.
4876 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4877 << Name;
4878 return true;
4879 }
4880
Douglas Gregor663b5a02009-10-14 20:14:33 +00004881 // C++0x [temp.explicit]p1:
4882 // [...] An explicit instantiation of a function template shall not use the
4883 // inline or constexpr specifiers.
4884 // Presumably, this also applies to member functions of class templates as
4885 // well.
4886 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4887 Diag(D.getDeclSpec().getInlineSpecLoc(),
4888 diag::err_explicit_instantiation_inline)
Douglas Gregor849b2432010-03-31 17:46:05 +00004889 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00004890
4891 // FIXME: check for constexpr specifier.
4892
Douglas Gregor558c0322009-10-14 23:41:34 +00004893 // C++0x [temp.explicit]p2:
4894 // There are two forms of explicit instantiation: an explicit instantiation
4895 // definition and an explicit instantiation declaration. An explicit
4896 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00004897 TemplateSpecializationKind TSK
4898 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4899 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00004900
John McCalla24dc2e2009-11-17 02:14:36 +00004901 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4902 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004903
4904 if (!R->isFunctionType()) {
4905 // C++ [temp.explicit]p1:
4906 // A [...] static data member of a class template can be explicitly
4907 // instantiated from the member definition associated with its class
4908 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00004909 if (Previous.isAmbiguous())
4910 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004911
John McCall1bcee0a2009-12-02 08:25:40 +00004912 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004913 if (!Prev || !Prev->isStaticDataMember()) {
4914 // We expect to see a data data member here.
4915 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4916 << Name;
4917 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4918 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00004919 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004920 return true;
4921 }
4922
4923 if (!Prev->getInstantiatedFromStaticDataMember()) {
4924 // FIXME: Check for explicit specialization?
4925 Diag(D.getIdentifierLoc(),
4926 diag::err_explicit_instantiation_data_member_not_instantiated)
4927 << Prev;
4928 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4929 // FIXME: Can we provide a note showing where this was declared?
4930 return true;
4931 }
4932
Douglas Gregor558c0322009-10-14 23:41:34 +00004933 // C++0x [temp.explicit]p2:
4934 // If the explicit instantiation is for a member function, a member class
4935 // or a static data member of a class template specialization, the name of
4936 // the class template specialization in the qualified-id for the member
4937 // name shall be a simple-template-id.
4938 //
4939 // C++98 has the same restriction, just worded differently.
4940 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4941 Diag(D.getIdentifierLoc(),
4942 diag::err_explicit_instantiation_without_qualified_id)
4943 << Prev << D.getCXXScopeSpec().getRange();
4944
4945 // Check the scope of this explicit instantiation.
4946 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4947
Douglas Gregor454885e2009-10-15 15:54:05 +00004948 // Verify that it is okay to explicitly instantiate here.
4949 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4950 assert(MSInfo && "Missing static data member specialization info?");
4951 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004952 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00004953 MSInfo->getTemplateSpecializationKind(),
4954 MSInfo->getPointOfInstantiation(),
4955 SuppressNew))
4956 return true;
4957 if (SuppressNew)
4958 return DeclPtrTy();
4959
Douglas Gregord5a423b2009-09-25 18:43:00 +00004960 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004961 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004962 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004963 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4964 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004965
4966 // FIXME: Create an ExplicitInstantiation node?
4967 return DeclPtrTy();
4968 }
4969
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004970 // If the declarator is a template-id, translate the parser's template
4971 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00004972 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00004973 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004974 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4975 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00004976 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4977 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00004978 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4979 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00004980 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00004981 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00004982 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00004983 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00004984 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004985
Douglas Gregord5a423b2009-09-25 18:43:00 +00004986 // C++ [temp.explicit]p1:
4987 // A [...] function [...] can be explicitly instantiated from its template.
4988 // A member function [...] of a class template can be explicitly
4989 // instantiated from the member definition associated with its class
4990 // template.
John McCallc373d482010-01-27 01:50:18 +00004991 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004992 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4993 P != PEnd; ++P) {
4994 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00004995 if (!HasExplicitTemplateArgs) {
4996 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4997 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4998 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00004999
John McCallc373d482010-01-27 01:50:18 +00005000 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00005001 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5002 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00005003 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00005004 }
5005 }
5006
5007 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5008 if (!FunTmpl)
5009 continue;
5010
John McCall5769d612010-02-08 23:07:23 +00005011 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005012 FunctionDecl *Specialization = 0;
5013 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00005014 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00005015 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00005016 R, Specialization, Info)) {
5017 // FIXME: Keep track of almost-matches?
5018 (void)TDK;
5019 continue;
5020 }
5021
John McCallc373d482010-01-27 01:50:18 +00005022 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005023 }
5024
5025 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005026 UnresolvedSetIterator Result
5027 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregord5a423b2009-09-25 18:43:00 +00005028 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005029 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5030 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5031 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00005032
John McCallc373d482010-01-27 01:50:18 +00005033 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00005034 return true;
John McCallc373d482010-01-27 01:50:18 +00005035
5036 // Ignore access control bits, we don't need them for redeclaration checking.
5037 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005038
Douglas Gregor0a897e32009-10-15 17:21:20 +00005039 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005040 Diag(D.getIdentifierLoc(),
5041 diag::err_explicit_instantiation_member_function_not_instantiated)
5042 << Specialization
5043 << (Specialization->getTemplateSpecializationKind() ==
5044 TSK_ExplicitSpecialization);
5045 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5046 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005047 }
Douglas Gregor558c0322009-10-14 23:41:34 +00005048
Douglas Gregor0a897e32009-10-15 17:21:20 +00005049 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00005050 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5051 PrevDecl = Specialization;
5052
Douglas Gregor0a897e32009-10-15 17:21:20 +00005053 if (PrevDecl) {
5054 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005055 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00005056 PrevDecl,
5057 PrevDecl->getTemplateSpecializationKind(),
5058 PrevDecl->getPointOfInstantiation(),
5059 SuppressNew))
5060 return true;
5061
5062 // FIXME: We may still want to build some representation of this
5063 // explicit specialization.
5064 if (SuppressNew)
5065 return DeclPtrTy();
5066 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00005067
5068 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00005069
5070 if (TSK == TSK_ExplicitInstantiationDefinition)
5071 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5072 false, /*DefinitionRequired=*/true);
Douglas Gregor0a897e32009-10-15 17:21:20 +00005073
Douglas Gregor558c0322009-10-14 23:41:34 +00005074 // C++0x [temp.explicit]p2:
5075 // If the explicit instantiation is for a member function, a member class
5076 // or a static data member of a class template specialization, the name of
5077 // the class template specialization in the qualified-id for the member
5078 // name shall be a simple-template-id.
5079 //
5080 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005081 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005082 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00005083 D.getCXXScopeSpec().isSet() &&
5084 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5085 Diag(D.getIdentifierLoc(),
5086 diag::err_explicit_instantiation_without_qualified_id)
5087 << Specialization << D.getCXXScopeSpec().getRange();
5088
5089 CheckExplicitInstantiationScope(*this,
5090 FunTmpl? (NamedDecl *)FunTmpl
5091 : Specialization->getInstantiatedFromMemberFunction(),
5092 D.getIdentifierLoc(),
5093 D.getCXXScopeSpec().isSet());
5094
Douglas Gregord5a423b2009-09-25 18:43:00 +00005095 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5096 return DeclPtrTy();
5097}
5098
Douglas Gregord57959a2009-03-27 23:10:48 +00005099Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00005100Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5101 const CXXScopeSpec &SS, IdentifierInfo *Name,
5102 SourceLocation TagLoc, SourceLocation NameLoc) {
5103 // This has to hold, because SS is expected to be defined.
5104 assert(Name && "Expected a name in a dependent tag");
5105
5106 NestedNameSpecifier *NNS
5107 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5108 if (!NNS)
5109 return true;
5110
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005111 ElaboratedTypeKeyword Keyword = ETK_None;
Douglas Gregor40336422010-03-31 22:19:08 +00005112 switch (TagDecl::getTagKindForTypeSpec(TagSpec)) {
5113 case TagDecl::TK_struct: Keyword = ETK_Struct; break;
5114 case TagDecl::TK_class: Keyword = ETK_Class; break;
5115 case TagDecl::TK_union: Keyword = ETK_Union; break;
5116 case TagDecl::TK_enum: Keyword = ETK_Enum; break;
5117 }
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005118 assert(Keyword != ETK_None && "Invalid tag kind!");
5119
Douglas Gregor40336422010-03-31 22:19:08 +00005120 return Context.getDependentNameType(Keyword, NNS, Name).getAsOpaquePtr();
John McCallc4e70192009-09-11 04:59:25 +00005121}
5122
5123Sema::TypeResult
Douglas Gregord57959a2009-03-27 23:10:48 +00005124Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5125 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005126 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00005127 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5128 if (!NNS)
5129 return true;
5130
5131 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00005132 if (T.isNull())
5133 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00005134 return T.getAsOpaquePtr();
5135}
5136
Douglas Gregor17343172009-04-01 00:28:59 +00005137Sema::TypeResult
5138Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5139 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005140 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005141 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00005142 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +00005143 const TemplateSpecializationType *TemplateId
John McCall183700f2009-09-21 23:43:11 +00005144 = T->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00005145 assert(TemplateId && "Expected a template specialization type");
5146
Douglas Gregor6946baf2009-09-02 13:05:45 +00005147 if (computeDeclContext(SS, false)) {
5148 // If we can compute a declaration context, then the "typename"
5149 // keyword was superfluous. Just build a QualifiedNameType to keep
5150 // track of the nested-name-specifier.
Mike Stump1eb44332009-09-09 15:08:12 +00005151
Douglas Gregor6946baf2009-09-02 13:05:45 +00005152 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
5153 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
5154 }
Mike Stump1eb44332009-09-09 15:08:12 +00005155
Douglas Gregor4a2023f2010-03-31 20:19:30 +00005156 return Context.getDependentNameType(ETK_Typename, NNS, TemplateId)
5157 .getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00005158}
5159
Douglas Gregord57959a2009-03-27 23:10:48 +00005160/// \brief Build the type that describes a C++ typename specifier,
5161/// e.g., "typename T::type".
5162QualType
5163Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
5164 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00005165 CXXRecordDecl *CurrentInstantiation = 0;
5166 if (NNS->isDependent()) {
5167 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00005168
Douglas Gregor42af25f2009-05-11 19:58:34 +00005169 // If the nested-name-specifier does not refer to the current
5170 // instantiation, then build a typename type.
5171 if (!CurrentInstantiation)
Douglas Gregor4a2023f2010-03-31 20:19:30 +00005172 return Context.getDependentNameType(ETK_Typename, NNS, &II);
Mike Stump1eb44332009-09-09 15:08:12 +00005173
Douglas Gregorde18d122009-09-02 13:12:51 +00005174 // The nested-name-specifier refers to the current instantiation, so the
5175 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump1eb44332009-09-09 15:08:12 +00005176 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorde18d122009-09-02 13:12:51 +00005177 // extraneous "typename" keywords, and we retroactively apply this DR to
5178 // C++03 code.
Douglas Gregor42af25f2009-05-11 19:58:34 +00005179 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005180
Douglas Gregor42af25f2009-05-11 19:58:34 +00005181 DeclContext *Ctx = 0;
5182
5183 if (CurrentInstantiation)
5184 Ctx = CurrentInstantiation;
5185 else {
5186 CXXScopeSpec SS;
5187 SS.setScopeRep(NNS);
5188 SS.setRange(Range);
5189 if (RequireCompleteDeclContext(SS))
5190 return QualType();
5191
5192 Ctx = computeDeclContext(SS);
5193 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005194 assert(Ctx && "No declaration context?");
5195
5196 DeclarationName Name(&II);
John McCalla24dc2e2009-11-17 02:14:36 +00005197 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
5198 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005199 unsigned DiagID = 0;
5200 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005201 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005202 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005203 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005204 break;
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005205
5206 case LookupResult::NotFoundInCurrentInstantiation:
5207 // Okay, it's a member of an unknown instantiation.
Douglas Gregor4a2023f2010-03-31 20:19:30 +00005208 return Context.getDependentNameType(ETK_Typename, NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00005209
5210 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +00005211 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005212 // We found a type. Build a QualifiedNameType, since the
5213 // typename-specifier was just sugar. FIXME: Tell
5214 // QualifiedNameType that it has a "typename" prefix.
5215 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
5216 }
5217
5218 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00005219 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00005220 break;
5221
John McCall7ba107a2009-11-18 02:36:19 +00005222 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005223 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00005224 return QualType();
5225
Douglas Gregord57959a2009-03-27 23:10:48 +00005226 case LookupResult::FoundOverloaded:
5227 DiagID = diag::err_typename_nested_not_type;
5228 Referenced = *Result.begin();
5229 break;
5230
John McCall6e247262009-10-10 05:48:19 +00005231 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00005232 return QualType();
5233 }
5234
5235 // If we get here, it's because name lookup did not find a
5236 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor3f093272009-10-13 21:16:44 +00005237 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00005238 if (Referenced)
5239 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5240 << Name;
5241 return QualType();
5242}
Douglas Gregor4a959d82009-08-06 16:20:37 +00005243
5244namespace {
5245 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00005246 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00005247 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00005248 SourceLocation Loc;
5249 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00005250
Douglas Gregor4a959d82009-08-06 16:20:37 +00005251 public:
Mike Stump1eb44332009-09-09 15:08:12 +00005252 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005253 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005254 DeclarationName Entity)
5255 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00005256 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00005257
5258 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00005259 /// transformed.
5260 ///
5261 /// For the purposes of type reconstruction, a type has already been
5262 /// transformed if it is NULL or if it is not dependent.
5263 bool AlreadyTransformed(QualType T) {
5264 return T.isNull() || !T->isDependentType();
5265 }
Mike Stump1eb44332009-09-09 15:08:12 +00005266
5267 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00005268 /// rebuilt.
5269 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00005270
Douglas Gregor4a959d82009-08-06 16:20:37 +00005271 /// \brief Returns the name of the entity whose type is being rebuilt.
5272 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00005273
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005274 /// \brief Sets the "base" location and entity when that
5275 /// information is known based on another transformation.
5276 void setBase(SourceLocation Loc, DeclarationName Entity) {
5277 this->Loc = Loc;
5278 this->Entity = Entity;
5279 }
5280
Douglas Gregor4a959d82009-08-06 16:20:37 +00005281 /// \brief Transforms an expression by returning the expression itself
5282 /// (an identity function).
5283 ///
5284 /// FIXME: This is completely unsafe; we will need to actually clone the
5285 /// expressions.
5286 Sema::OwningExprResult TransformExpr(Expr *E) {
5287 return getSema().Owned(E);
5288 }
Mike Stump1eb44332009-09-09 15:08:12 +00005289
Douglas Gregor4a959d82009-08-06 16:20:37 +00005290 /// \brief Transforms a typename type by determining whether the type now
5291 /// refers to a member of the current instantiation, and then
5292 /// type-checking and building a QualifiedNameType (when possible).
Douglas Gregor4714c122010-03-31 17:34:00 +00005293 QualType TransformDependentNameType(TypeLocBuilder &TLB, DependentNameTypeLoc TL,
Douglas Gregor124b8782010-02-16 19:09:40 +00005294 QualType ObjectType);
Douglas Gregor4a959d82009-08-06 16:20:37 +00005295 };
5296}
5297
Mike Stump1eb44332009-09-09 15:08:12 +00005298QualType
Douglas Gregor4714c122010-03-31 17:34:00 +00005299CurrentInstantiationRebuilder::TransformDependentNameType(TypeLocBuilder &TLB,
5300 DependentNameTypeLoc TL,
Douglas Gregor124b8782010-02-16 19:09:40 +00005301 QualType ObjectType) {
Douglas Gregor4714c122010-03-31 17:34:00 +00005302 DependentNameType *T = TL.getTypePtr();
John McCalla2becad2009-10-21 00:40:46 +00005303
Douglas Gregor4a959d82009-08-06 16:20:37 +00005304 NestedNameSpecifier *NNS
5305 = TransformNestedNameSpecifier(T->getQualifier(),
Douglas Gregor124b8782010-02-16 19:09:40 +00005306 /*FIXME:*/SourceRange(getBaseLocation()),
5307 ObjectType);
Douglas Gregor4a959d82009-08-06 16:20:37 +00005308 if (!NNS)
5309 return QualType();
5310
5311 // If the nested-name-specifier did not change, and we cannot compute the
5312 // context corresponding to the nested-name-specifier, then this
5313 // typename type will not change; exit early.
5314 CXXScopeSpec SS;
5315 SS.setRange(SourceRange(getBaseLocation()));
5316 SS.setScopeRep(NNS);
John McCall833ca992009-10-29 08:12:44 +00005317
5318 QualType Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00005319 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall833ca992009-10-29 08:12:44 +00005320 Result = QualType(T, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00005321
5322 // Rebuild the typename type, which will probably turn into a
Douglas Gregor4a959d82009-08-06 16:20:37 +00005323 // QualifiedNameType.
John McCall833ca992009-10-29 08:12:44 +00005324 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005325 QualType NewTemplateId
Douglas Gregor4a959d82009-08-06 16:20:37 +00005326 = TransformType(QualType(TemplateId, 0));
5327 if (NewTemplateId.isNull())
5328 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005329
Douglas Gregor4a959d82009-08-06 16:20:37 +00005330 if (NNS == T->getQualifier() &&
5331 NewTemplateId == QualType(TemplateId, 0))
John McCall833ca992009-10-29 08:12:44 +00005332 Result = QualType(T, 0);
5333 else
Douglas Gregor4a2023f2010-03-31 20:19:30 +00005334 Result = getDerived().RebuildDependentNameType(T->getKeyword(),
5335 NNS, NewTemplateId);
John McCall833ca992009-10-29 08:12:44 +00005336 } else
Douglas Gregor4a2023f2010-03-31 20:19:30 +00005337 Result = getDerived().RebuildDependentNameType(T->getKeyword(),
5338 NNS, T->getIdentifier(),
5339 SourceRange(TL.getNameLoc()));
Mike Stump1eb44332009-09-09 15:08:12 +00005340
Douglas Gregora50ce322010-03-07 23:26:22 +00005341 if (Result.isNull())
5342 return QualType();
5343
Douglas Gregor4714c122010-03-31 17:34:00 +00005344 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
John McCall833ca992009-10-29 08:12:44 +00005345 NewTL.setNameLoc(TL.getNameLoc());
5346 return Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00005347}
5348
5349/// \brief Rebuilds a type within the context of the current instantiation.
5350///
Mike Stump1eb44332009-09-09 15:08:12 +00005351/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00005352/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00005353/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00005354/// partial specialization thereof). This routine will rebuild that type now
5355/// that we have entered the declarator's scope, which may produce different
5356/// canonical types, e.g.,
5357///
5358/// \code
5359/// template<typename T>
5360/// struct X {
5361/// typedef T* pointer;
5362/// pointer data();
5363/// };
5364///
5365/// template<typename T>
5366/// typename X<T>::pointer X<T>::data() { ... }
5367/// \endcode
5368///
Douglas Gregor4714c122010-03-31 17:34:00 +00005369/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005370/// since we do not know that we can look into X<T> when we parsed the type.
5371/// This function will rebuild the type, performing the lookup of "pointer"
5372/// in X<T> and returning a QualifiedNameType whose canonical type is the same
5373/// as the canonical type of T*, allowing the return types of the out-of-line
5374/// definition and the declaration to match.
5375QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
5376 DeclarationName Name) {
5377 if (T.isNull() || !T->isDependentType())
5378 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00005379
Douglas Gregor4a959d82009-08-06 16:20:37 +00005380 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5381 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00005382}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005383
5384/// \brief Produces a formatted string that describes the binding of
5385/// template parameters to template arguments.
5386std::string
5387Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5388 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005389 // FIXME: For variadic templates, we'll need to get the structured list.
5390 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5391 Args.flat_size());
5392}
5393
5394std::string
5395Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5396 const TemplateArgument *Args,
5397 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005398 std::string Result;
5399
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005400 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005401 return Result;
5402
5403 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005404 if (I >= NumArgs)
5405 break;
5406
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005407 if (I == 0)
5408 Result += "[with ";
5409 else
5410 Result += ", ";
5411
5412 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5413 Result += Id->getName();
5414 } else {
5415 Result += '$';
5416 Result += llvm::utostr(I);
5417 }
5418
5419 Result += " = ";
5420
5421 switch (Args[I].getKind()) {
5422 case TemplateArgument::Null:
5423 Result += "<no value>";
5424 break;
5425
5426 case TemplateArgument::Type: {
5427 std::string TypeStr;
5428 Args[I].getAsType().getAsStringInternal(TypeStr,
5429 Context.PrintingPolicy);
5430 Result += TypeStr;
5431 break;
5432 }
5433
5434 case TemplateArgument::Declaration: {
5435 bool Unnamed = true;
5436 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5437 if (ND->getDeclName()) {
5438 Unnamed = false;
5439 Result += ND->getNameAsString();
5440 }
5441 }
5442
5443 if (Unnamed) {
5444 Result += "<anonymous>";
5445 }
5446 break;
5447 }
5448
Douglas Gregor788cd062009-11-11 01:00:40 +00005449 case TemplateArgument::Template: {
5450 std::string Str;
5451 llvm::raw_string_ostream OS(Str);
5452 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5453 Result += OS.str();
5454 break;
5455 }
5456
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005457 case TemplateArgument::Integral: {
5458 Result += Args[I].getAsIntegral()->toString(10);
5459 break;
5460 }
5461
5462 case TemplateArgument::Expression: {
5463 assert(false && "No expressions in deduced template arguments!");
5464 Result += "<expression>";
5465 break;
5466 }
5467
5468 case TemplateArgument::Pack:
5469 // FIXME: Format template argument packs
5470 Result += "<template argument pack>";
5471 break;
5472 }
5473 }
5474
5475 Result += ']';
5476 return Result;
5477}