blob: 65e0e5e95e894b3c3cc0a57d3a2ad0660f4ebbc0 [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) {
John McCallf36e02d2009-10-09 21:13:30 +0000458 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000459 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000460 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000461 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000462 }
463
Douglas Gregorddc29e12009-02-06 22:42:48 +0000464 SourceLocation Loc = ParamNameLoc;
465 if (!ParamName)
466 Loc = KeyLoc;
467
Douglas Gregor72c3f312008-12-05 18:15:24 +0000468 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000469 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
470 Loc, Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000471 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000472 if (Invalid)
473 Param->setInvalidDecl();
474
475 if (ParamName) {
476 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000477 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000478 IdResolver.AddDecl(Param);
479 }
480
Chris Lattnerb28317a2009-03-28 19:18:32 +0000481 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000482}
483
Douglas Gregord684b002009-02-10 19:49:53 +0000484/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump1eb44332009-09-09 15:08:12 +0000485/// Default) to the given template type parameter (TypeParam).
486void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000487 SourceLocation EqualLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000488 SourceLocation DefaultLoc,
Douglas Gregord684b002009-02-10 19:49:53 +0000489 TypeTy *DefaultT) {
Mike Stump1eb44332009-09-09 15:08:12 +0000490 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000491 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall833ca992009-10-29 08:12:44 +0000492
John McCalla93c9342009-12-07 02:54:59 +0000493 TypeSourceInfo *DefaultTInfo;
494 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall833ca992009-10-29 08:12:44 +0000495
John McCalla93c9342009-12-07 02:54:59 +0000496 assert(DefaultTInfo && "expected source information for type");
Douglas Gregord684b002009-02-10 19:49:53 +0000497
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000498 // C++0x [temp.param]p9:
499 // A default template-argument may be specified for any kind of
Mike Stump1eb44332009-09-09 15:08:12 +0000500 // template-parameter that is not a template parameter pack.
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000501 if (Parm->isParameterPack()) {
502 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000503 return;
504 }
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Douglas Gregord684b002009-02-10 19:49:53 +0000506 // C++ [temp.param]p14:
507 // A template-parameter shall not be used in its own default argument.
508 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Douglas Gregord684b002009-02-10 19:49:53 +0000510 // Check the template argument itself.
John McCalla93c9342009-12-07 02:54:59 +0000511 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000512 Parm->setInvalidDecl();
513 return;
514 }
515
John McCalla93c9342009-12-07 02:54:59 +0000516 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000517}
518
Douglas Gregor2943aed2009-03-03 04:44:36 +0000519/// \brief Check that the type of a non-type template parameter is
520/// well-formed.
521///
522/// \returns the (possibly-promoted) parameter type if valid;
523/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000524QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000525Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
526 // C++ [temp.param]p4:
527 //
528 // A non-type template-parameter shall have one of the following
529 // (optionally cv-qualified) types:
530 //
531 // -- integral or enumeration type,
532 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000533 // -- pointer to object or pointer to function,
534 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000535 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
536 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000537 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000538 T->isReferenceType() ||
539 // -- pointer to member.
540 T->isMemberPointerType() ||
541 // If T is a dependent type, we can't do the check now, so we
542 // assume that it is well-formed.
543 T->isDependentType())
544 return T;
545 // C++ [temp.param]p8:
546 //
547 // A non-type template-parameter of type "array of T" or
548 // "function returning T" is adjusted to be of type "pointer to
549 // T" or "pointer to function returning T", respectively.
550 else if (T->isArrayType())
551 // FIXME: Keep the type prior to promotion?
552 return Context.getArrayDecayedType(T);
553 else if (T->isFunctionType())
554 // FIXME: Keep the type prior to promotion?
555 return Context.getPointerType(T);
556
557 Diag(Loc, diag::err_template_nontype_parm_bad_type)
558 << T;
559
560 return QualType();
561}
562
Douglas Gregor72c3f312008-12-05 18:15:24 +0000563/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
564/// template parameter (e.g., "int Size" in "template<int Size>
565/// class Array") has been parsed. S is the current scope and D is
566/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000567Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump1eb44332009-09-09 15:08:12 +0000568 unsigned Depth,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000569 unsigned Position) {
John McCalla93c9342009-12-07 02:54:59 +0000570 TypeSourceInfo *TInfo = 0;
571 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000572
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000573 assert(S->isTemplateParamScope() &&
574 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000575 bool Invalid = false;
576
577 IdentifierInfo *ParamName = D.getIdentifier();
578 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000579 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000580 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000581 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000582 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000583 }
584
Douglas Gregor2943aed2009-03-03 04:44:36 +0000585 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000586 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000587 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000588 Invalid = true;
589 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000590
Douglas Gregor72c3f312008-12-05 18:15:24 +0000591 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000592 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
593 D.getIdentifierLoc(),
John McCalla93c9342009-12-07 02:54:59 +0000594 Depth, Position, ParamName, T, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000595 if (Invalid)
596 Param->setInvalidDecl();
597
598 if (D.getIdentifier()) {
599 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000600 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000601 IdResolver.AddDecl(Param);
602 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000603 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000604}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000605
Douglas Gregord684b002009-02-10 19:49:53 +0000606/// \brief Adds a default argument to the given non-type template
607/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000608void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000609 SourceLocation EqualLoc,
610 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000611 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000612 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000613 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Douglas Gregord684b002009-02-10 19:49:53 +0000615 // C++ [temp.param]p14:
616 // A template-parameter shall not be used in its own default argument.
617 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Douglas Gregord684b002009-02-10 19:49:53 +0000619 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000620 TemplateArgument Converted;
621 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
622 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000623 TemplateParm->setInvalidDecl();
624 return;
625 }
626
Anders Carlssone9146f22009-05-01 19:49:17 +0000627 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000628}
629
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000630
631/// ActOnTemplateTemplateParameter - Called when a C++ template template
632/// parameter (e.g. T in template <template <typename> class T> class array)
633/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000634Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
635 SourceLocation TmpLoc,
636 TemplateParamsTy *Params,
637 IdentifierInfo *Name,
638 SourceLocation NameLoc,
639 unsigned Depth,
Mike Stump1eb44332009-09-09 15:08:12 +0000640 unsigned Position) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000641 assert(S->isTemplateParamScope() &&
642 "Template template parameter not in template parameter scope!");
643
644 // Construct the parameter object.
645 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000646 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
647 TmpLoc, Depth, Position, Name,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000648 (TemplateParameterList*)Params);
649
650 // Make sure the parameter is valid.
651 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
652 // do anything yet. However, if the template parameter list or (eventual)
653 // default value is ever invalidated, that will propagate here.
654 bool Invalid = false;
655 if (Invalid) {
656 Param->setInvalidDecl();
657 }
658
659 // If the tt-param has a name, then link the identifier into the scope
660 // and lookup mechanisms.
661 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000662 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000663 IdResolver.AddDecl(Param);
664 }
665
Chris Lattnerb28317a2009-03-28 19:18:32 +0000666 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000667}
668
Douglas Gregord684b002009-02-10 19:49:53 +0000669/// \brief Adds a default argument to the given template template
670/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000671void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000672 SourceLocation EqualLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +0000673 const ParsedTemplateArgument &Default) {
Mike Stump1eb44332009-09-09 15:08:12 +0000674 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000675 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor788cd062009-11-11 01:00:40 +0000676
Douglas Gregord684b002009-02-10 19:49:53 +0000677 // C++ [temp.param]p14:
678 // A template-parameter shall not be used in its own default argument.
679 // FIXME: Implement this check! Needs a recursive walk over the types.
680
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000681 // Check only that we have a template template argument. We don't want to
682 // try to check well-formedness now, because our template template parameter
683 // might have dependent types in its template parameters, which we wouldn't
684 // be able to match now.
685 //
686 // If none of the template template parameter's template arguments mention
687 // other template parameters, we could actually perform more checking here.
688 // However, it isn't worth doing.
Douglas Gregor788cd062009-11-11 01:00:40 +0000689 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000690 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
691 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
692 << DefaultArg.getSourceRange();
Douglas Gregord684b002009-02-10 19:49:53 +0000693 return;
694 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000695
Douglas Gregor788cd062009-11-11 01:00:40 +0000696 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregord684b002009-02-10 19:49:53 +0000697}
698
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000699/// ActOnTemplateParameterList - Builds a TemplateParameterList that
700/// contains the template parameters in Params/NumParams.
701Sema::TemplateParamsTy *
702Sema::ActOnTemplateParameterList(unsigned Depth,
703 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000704 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000705 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000706 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000707 SourceLocation RAngleLoc) {
708 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000709 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000710
Douglas Gregorddc29e12009-02-06 22:42:48 +0000711 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000712 (NamedDecl**)Params, NumParams,
713 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000714}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000715
John McCallb6217662010-03-15 10:12:16 +0000716static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
717 if (SS.isSet())
718 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
719 SS.getRange());
720}
721
Douglas Gregor212e81c2009-03-25 00:13:59 +0000722Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000723Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000724 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000725 IdentifierInfo *Name, SourceLocation NameLoc,
726 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000727 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000728 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000729 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000730 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000731 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000732 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000733
734 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000735 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000736 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000737
John McCall05b23ea2009-09-14 21:59:20 +0000738 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
739 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000740
741 // There is no such thing as an unnamed class template.
742 if (!Name) {
743 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000744 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000745 }
746
747 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000748 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000749 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000750 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000751 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregorf0510d42009-10-12 23:11:44 +0000752 if (RequireCompleteDeclContext(SS))
753 return true;
754
Douglas Gregor05396e22009-08-25 17:23:04 +0000755 SemanticContext = computeDeclContext(SS, true);
756 if (!SemanticContext) {
757 // FIXME: Produce a reasonable diagnostic here
758 return true;
759 }
Mike Stump1eb44332009-09-09 15:08:12 +0000760
John McCalla24dc2e2009-11-17 02:14:36 +0000761 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000762 } else {
763 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000764 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000765 }
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Douglas Gregor57265e32010-04-12 16:00:01 +0000767 if (Previous.isAmbiguous())
768 return true;
769
Douglas Gregorddc29e12009-02-06 22:42:48 +0000770 NamedDecl *PrevDecl = 0;
771 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000772 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000773
Douglas Gregorddc29e12009-02-06 22:42:48 +0000774 // If there is a previous declaration with the same name, check
775 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000776 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000777 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000778
779 // We may have found the injected-class-name of a class template,
780 // class template partial specialization, or class template specialization.
781 // In these cases, grab the template that is being defined or specialized.
782 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
783 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
784 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
785 PrevClassTemplate
786 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
787 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
788 PrevClassTemplate
789 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
790 ->getSpecializedTemplate();
791 }
792 }
793
John McCall65c49462009-12-18 11:25:59 +0000794 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000795 // C++ [namespace.memdef]p3:
796 // [...] When looking for a prior declaration of a class or a function
797 // declared as a friend, and when the name of the friend class or
798 // function is neither a qualified name nor a template-id, scopes outside
799 // the innermost enclosing namespace scope are not considered.
800 DeclContext *OutermostContext = CurContext;
801 while (!OutermostContext->isFileContext())
802 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000803
804 if (PrevDecl &&
805 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
806 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
John McCalle129d442009-12-17 23:21:11 +0000807 SemanticContext = PrevDecl->getDeclContext();
808 } else {
809 // Declarations in outer scopes don't matter. However, the outermost
810 // context we computed is the semantic context for our new
811 // declaration.
812 PrevDecl = PrevClassTemplate = 0;
813 SemanticContext = OutermostContext;
814 }
815
816 if (CurContext->isDependentContext()) {
817 // If this is a dependent context, we don't want to link the friend
818 // class template to the template in scope, because that would perform
819 // checking of the template parameter lists that can't be performed
820 // until the outer context is instantiated.
821 PrevDecl = PrevClassTemplate = 0;
822 }
823 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
824 PrevDecl = PrevClassTemplate = 0;
Douglas Gregor57265e32010-04-12 16:00:01 +0000825
Douglas Gregorddc29e12009-02-06 22:42:48 +0000826 if (PrevClassTemplate) {
827 // Ensure that the template parameter lists are compatible.
828 if (!TemplateParameterListsAreEqual(TemplateParams,
829 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000830 /*Complain=*/true,
831 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000832 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000833
834 // C++ [temp.class]p4:
835 // In a redeclaration, partial specialization, explicit
836 // specialization or explicit instantiation of a class template,
837 // the class-key shall agree in kind with the original class
838 // template declaration (7.1.5.3).
839 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000840 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000841 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000842 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000843 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000844 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000845 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000846 }
847
Douglas Gregorddc29e12009-02-06 22:42:48 +0000848 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000849 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000850 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000851 Diag(NameLoc, diag::err_redefinition) << Name;
852 Diag(Def->getLocation(), diag::note_previous_definition);
853 // FIXME: Would it make sense to try to "forget" the previous
854 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000855 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000856 }
857 }
858 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
859 // Maybe we will complain about the shadowed template parameter.
860 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
861 // Just pretend that we didn't see the previous declaration.
862 PrevDecl = 0;
863 } else if (PrevDecl) {
864 // C++ [temp]p5:
865 // A class template shall not have the same name as any other
866 // template, class, function, object, enumeration, enumerator,
867 // namespace, or type in the same scope (3.3), except as specified
868 // in (14.5.4).
869 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
870 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000871 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000872 }
873
Douglas Gregord684b002009-02-10 19:49:53 +0000874 // Check the template parameter list of this declaration, possibly
875 // merging in the template parameter list from the previous class
876 // template declaration.
877 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000878 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
879 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000880 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000881
Douglas Gregor57265e32010-04-12 16:00:01 +0000882 if (SS.isSet()) {
883 // If the name of the template was qualified, we must be defining the
884 // template out-of-line.
885 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
886 !(TUK == TUK_Friend && CurContext->isDependentContext()))
887 Diag(NameLoc, diag::err_member_def_does_not_match)
888 << Name << SemanticContext << SS.getRange();
889 }
890
Mike Stump1eb44332009-09-09 15:08:12 +0000891 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000892 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000893 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000894 PrevClassTemplate->getTemplatedDecl() : 0,
895 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000896 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000897
898 ClassTemplateDecl *NewTemplate
899 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
900 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000901 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000902 NewClass->setDescribedClassTemplate(NewTemplate);
903
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000904 // Build the type for the class template declaration now.
John McCall3cb0ebd2010-03-10 03:28:59 +0000905 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
906 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000907 assert(T->isDependentType() && "Class template type is not dependent?");
908 (void)T;
909
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000910 // If we are providing an explicit specialization of a member that is a
911 // class template, make a note of that.
912 if (PrevClassTemplate &&
913 PrevClassTemplate->getInstantiatedFromMemberTemplate())
914 PrevClassTemplate->setMemberSpecialization();
915
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000916 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000917 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000918 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000919
Douglas Gregorddc29e12009-02-06 22:42:48 +0000920 // Set the lexical context of these templates
921 NewClass->setLexicalDeclContext(CurContext);
922 NewTemplate->setLexicalDeclContext(CurContext);
923
John McCall0f434ec2009-07-31 02:45:11 +0000924 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000925 NewClass->startDefinition();
926
927 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000928 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000929
John McCall05b23ea2009-09-14 21:59:20 +0000930 if (TUK != TUK_Friend)
931 PushOnScopeChains(NewTemplate, S);
932 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000933 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000934 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000935 NewClass->setAccess(PrevClassTemplate->getAccess());
936 }
John McCall05b23ea2009-09-14 21:59:20 +0000937
Douglas Gregord85bea22009-09-26 06:47:28 +0000938 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
939 PrevClassTemplate != NULL);
940
John McCall05b23ea2009-09-14 21:59:20 +0000941 // Friend templates are visible in fairly strange ways.
942 if (!CurContext->isDependentContext()) {
943 DeclContext *DC = SemanticContext->getLookupContext();
944 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
945 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
946 PushOnScopeChains(NewTemplate, EnclosingScope,
947 /* AddToContext = */ false);
948 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000949
950 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
951 NewClass->getLocation(),
952 NewTemplate,
953 /*FIXME:*/NewClass->getLocation());
954 Friend->setAccess(AS_public);
955 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000956 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000957
Douglas Gregord684b002009-02-10 19:49:53 +0000958 if (Invalid) {
959 NewTemplate->setInvalidDecl();
960 NewClass->setInvalidDecl();
961 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000962 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000963}
964
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000965/// \brief Diagnose the presence of a default template argument on a
966/// template parameter, which is ill-formed in certain contexts.
967///
968/// \returns true if the default template argument should be dropped.
969static bool DiagnoseDefaultTemplateArgument(Sema &S,
970 Sema::TemplateParamListContext TPC,
971 SourceLocation ParamLoc,
972 SourceRange DefArgRange) {
973 switch (TPC) {
974 case Sema::TPC_ClassTemplate:
975 return false;
976
977 case Sema::TPC_FunctionTemplate:
978 // C++ [temp.param]p9:
979 // A default template-argument shall not be specified in a
980 // function template declaration or a function template
981 // definition [...]
982 // (This sentence is not in C++0x, per DR226).
983 if (!S.getLangOptions().CPlusPlus0x)
984 S.Diag(ParamLoc,
985 diag::err_template_parameter_default_in_function_template)
986 << DefArgRange;
987 return false;
988
989 case Sema::TPC_ClassTemplateMember:
990 // C++0x [temp.param]p9:
991 // A default template-argument shall not be specified in the
992 // template-parameter-lists of the definition of a member of a
993 // class template that appears outside of the member's class.
994 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
995 << DefArgRange;
996 return true;
997
998 case Sema::TPC_FriendFunctionTemplate:
999 // C++ [temp.param]p9:
1000 // A default template-argument shall not be specified in a
1001 // friend template declaration.
1002 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1003 << DefArgRange;
1004 return true;
1005
1006 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1007 // for friend function templates if there is only a single
1008 // declaration (and it is a definition). Strange!
1009 }
1010
1011 return false;
1012}
1013
Douglas Gregord684b002009-02-10 19:49:53 +00001014/// \brief Checks the validity of a template parameter list, possibly
1015/// considering the template parameter list from a previous
1016/// declaration.
1017///
1018/// If an "old" template parameter list is provided, it must be
1019/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1020/// template parameter list.
1021///
1022/// \param NewParams Template parameter list for a new template
1023/// declaration. This template parameter list will be updated with any
1024/// default arguments that are carried through from the previous
1025/// template parameter list.
1026///
1027/// \param OldParams If provided, template parameter list from a
1028/// previous declaration of the same template. Default template
1029/// arguments will be merged from the old template parameter list to
1030/// the new template parameter list.
1031///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001032/// \param TPC Describes the context in which we are checking the given
1033/// template parameter list.
1034///
Douglas Gregord684b002009-02-10 19:49:53 +00001035/// \returns true if an error occurred, false otherwise.
1036bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001037 TemplateParameterList *OldParams,
1038 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001039 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Douglas Gregord684b002009-02-10 19:49:53 +00001041 // C++ [temp.param]p10:
1042 // The set of default template-arguments available for use with a
1043 // template declaration or definition is obtained by merging the
1044 // default arguments from the definition (if in scope) and all
1045 // declarations in scope in the same way default function
1046 // arguments are (8.3.6).
1047 bool SawDefaultArgument = false;
1048 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001049
Anders Carlsson49d25572009-06-12 23:20:15 +00001050 bool SawParameterPack = false;
1051 SourceLocation ParameterPackLoc;
1052
Mike Stump1a35fde2009-02-11 23:03:27 +00001053 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001054 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001055 if (OldParams)
1056 OldParam = OldParams->begin();
1057
1058 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1059 NewParamEnd = NewParams->end();
1060 NewParam != NewParamEnd; ++NewParam) {
1061 // Variables used to diagnose redundant default arguments
1062 bool RedundantDefaultArg = false;
1063 SourceLocation OldDefaultLoc;
1064 SourceLocation NewDefaultLoc;
1065
1066 // Variables used to diagnose missing default arguments
1067 bool MissingDefaultArg = false;
1068
Anders Carlsson49d25572009-06-12 23:20:15 +00001069 // C++0x [temp.param]p11:
1070 // If a template parameter of a class template is a template parameter pack,
1071 // it must be the last template parameter.
1072 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001073 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001074 diag::err_template_param_pack_must_be_last_template_parameter);
1075 Invalid = true;
1076 }
1077
Douglas Gregord684b002009-02-10 19:49:53 +00001078 if (TemplateTypeParmDecl *NewTypeParm
1079 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001080 // Check the presence of a default argument here.
1081 if (NewTypeParm->hasDefaultArgument() &&
1082 DiagnoseDefaultTemplateArgument(*this, TPC,
1083 NewTypeParm->getLocation(),
1084 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1085 .getFullSourceRange()))
1086 NewTypeParm->removeDefaultArgument();
1087
1088 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001089 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001090 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Anders Carlsson49d25572009-06-12 23:20:15 +00001092 if (NewTypeParm->isParameterPack()) {
1093 assert(!NewTypeParm->hasDefaultArgument() &&
1094 "Parameter packs can't have a default argument!");
1095 SawParameterPack = true;
1096 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001097 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001098 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001099 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1100 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1101 SawDefaultArgument = true;
1102 RedundantDefaultArg = true;
1103 PreviousDefaultArgLoc = NewDefaultLoc;
1104 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1105 // Merge the default argument from the old declaration to the
1106 // new declaration.
1107 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001108 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001109 true);
1110 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1111 } else if (NewTypeParm->hasDefaultArgument()) {
1112 SawDefaultArgument = true;
1113 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1114 } else if (SawDefaultArgument)
1115 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001116 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001117 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001118 // Check the presence of a default argument here.
1119 if (NewNonTypeParm->hasDefaultArgument() &&
1120 DiagnoseDefaultTemplateArgument(*this, TPC,
1121 NewNonTypeParm->getLocation(),
1122 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1123 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1124 NewNonTypeParm->setDefaultArgument(0);
1125 }
1126
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001127 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001128 NonTypeTemplateParmDecl *OldNonTypeParm
1129 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001130 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001131 NewNonTypeParm->hasDefaultArgument()) {
1132 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1133 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1134 SawDefaultArgument = true;
1135 RedundantDefaultArg = true;
1136 PreviousDefaultArgLoc = NewDefaultLoc;
1137 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1138 // Merge the default argument from the old declaration to the
1139 // new declaration.
1140 SawDefaultArgument = true;
1141 // FIXME: We need to create a new kind of "default argument"
1142 // expression that points to a previous template template
1143 // parameter.
1144 NewNonTypeParm->setDefaultArgument(
1145 OldNonTypeParm->getDefaultArgument());
1146 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1147 } else if (NewNonTypeParm->hasDefaultArgument()) {
1148 SawDefaultArgument = true;
1149 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1150 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001151 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001152 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001153 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001154 TemplateTemplateParmDecl *NewTemplateParm
1155 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001156 if (NewTemplateParm->hasDefaultArgument() &&
1157 DiagnoseDefaultTemplateArgument(*this, TPC,
1158 NewTemplateParm->getLocation(),
1159 NewTemplateParm->getDefaultArgument().getSourceRange()))
1160 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1161
1162 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001163 TemplateTemplateParmDecl *OldTemplateParm
1164 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001165 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001166 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001167 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1168 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001169 SawDefaultArgument = true;
1170 RedundantDefaultArg = true;
1171 PreviousDefaultArgLoc = NewDefaultLoc;
1172 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1173 // Merge the default argument from the old declaration to the
1174 // new declaration.
1175 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001176 // FIXME: We need to create a new kind of "default argument" expression
1177 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001178 NewTemplateParm->setDefaultArgument(
1179 OldTemplateParm->getDefaultArgument());
Douglas Gregor788cd062009-11-11 01:00:40 +00001180 PreviousDefaultArgLoc
1181 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001182 } else if (NewTemplateParm->hasDefaultArgument()) {
1183 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001184 PreviousDefaultArgLoc
1185 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001186 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001187 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001188 }
1189
1190 if (RedundantDefaultArg) {
1191 // C++ [temp.param]p12:
1192 // A template-parameter shall not be given default arguments
1193 // by two different declarations in the same scope.
1194 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1195 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1196 Invalid = true;
1197 } else if (MissingDefaultArg) {
1198 // C++ [temp.param]p11:
1199 // If a template-parameter has a default template-argument,
1200 // all subsequent template-parameters shall have a default
1201 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001202 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001203 diag::err_template_param_default_arg_missing);
1204 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1205 Invalid = true;
1206 }
1207
1208 // If we have an old template parameter list that we're merging
1209 // in, move on to the next parameter.
1210 if (OldParams)
1211 ++OldParam;
1212 }
1213
1214 return Invalid;
1215}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001216
Mike Stump1eb44332009-09-09 15:08:12 +00001217/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001218/// specifier, returning the template parameter list that applies to the
1219/// name.
1220///
1221/// \param DeclStartLoc the start of the declaration that has a scope
1222/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001223///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001224/// \param SS the scope specifier that will be matched to the given template
1225/// parameter lists. This scope specifier precedes a qualified name that is
1226/// being declared.
1227///
1228/// \param ParamLists the template parameter lists, from the outermost to the
1229/// innermost template parameter lists.
1230///
1231/// \param NumParamLists the number of template parameter lists in ParamLists.
1232///
John McCall77e8b112010-04-13 20:37:33 +00001233/// \param IsFriend Whether to apply the slightly different rules for
1234/// matching template parameters to scope specifiers in friend
1235/// declarations.
1236///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001237/// \param IsExplicitSpecialization will be set true if the entity being
1238/// declared is an explicit specialization, false otherwise.
1239///
Mike Stump1eb44332009-09-09 15:08:12 +00001240/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001241/// name that is preceded by the scope specifier @p SS. This template
1242/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001243/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001244/// template specialization), or may be NULL (if we were's declaring isn't
1245/// itself a template).
1246TemplateParameterList *
1247Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1248 const CXXScopeSpec &SS,
1249 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001250 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001251 bool IsFriend,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001252 bool &IsExplicitSpecialization) {
1253 IsExplicitSpecialization = false;
1254
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001255 // Find the template-ids that occur within the nested-name-specifier. These
1256 // template-ids will match up with the template parameter lists.
1257 llvm::SmallVector<const TemplateSpecializationType *, 4>
1258 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001259 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1260 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001261 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1262 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001263 const Type *T = NNS->getAsType();
1264 if (!T) break;
1265
1266 // C++0x [temp.expl.spec]p17:
1267 // A member or a member template may be nested within many
1268 // enclosing class templates. In an explicit specialization for
1269 // such a member, the member declaration shall be preceded by a
1270 // template<> for each enclosing class template that is
1271 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001272 //
1273 // Following the existing practice of GNU and EDG, we allow a typedef of a
1274 // template specialization type.
1275 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1276 T = TT->LookThroughTypedefs().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001277
Mike Stump1eb44332009-09-09 15:08:12 +00001278 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001279 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001280 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1281 if (!Template)
1282 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001283
Ted Kremenek6217b802009-07-29 21:53:49 +00001284 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001285 ClassTemplateSpecializationDecl *SpecDecl
1286 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1287 // If the nested name specifier refers to an explicit specialization,
1288 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001289 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1290 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001291 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001292 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001293 }
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001295 TemplateIdsInSpecifier.push_back(SpecType);
1296 }
1297 }
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001299 // Reverse the list of template-ids in the scope specifier, so that we can
1300 // more easily match up the template-ids and the template parameter lists.
1301 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001302
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001303 SourceLocation FirstTemplateLoc = DeclStartLoc;
1304 if (NumParamLists)
1305 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001306
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001307 // Match the template-ids found in the specifier to the template parameter
1308 // lists.
1309 unsigned Idx = 0;
1310 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1311 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001312 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1313 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001314 if (Idx >= NumParamLists) {
1315 // We have a template-id without a corresponding template parameter
1316 // list.
John McCall77e8b112010-04-13 20:37:33 +00001317
1318 // ...which is fine if this is a friend declaration.
1319 if (IsFriend) {
1320 IsExplicitSpecialization = true;
1321 break;
1322 }
1323
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001324 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001325 // FIXME: the location information here isn't great.
1326 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001327 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001328 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001329 << SS.getRange();
1330 } else {
1331 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1332 << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00001333 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001334 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001335 }
1336 return 0;
1337 }
Mike Stump1eb44332009-09-09 15:08:12 +00001338
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001339 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001340 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001341 TemplateDecl *Template
Douglas Gregorb88e8882009-07-30 17:40:51 +00001342 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1343
Mike Stump1eb44332009-09-09 15:08:12 +00001344 if (ClassTemplateDecl *ClassTemplate
Douglas Gregorb88e8882009-07-30 17:40:51 +00001345 = dyn_cast<ClassTemplateDecl>(Template)) {
1346 TemplateParameterList *ExpectedTemplateParams = 0;
1347 // Is this template-id naming the primary template?
1348 if (Context.hasSameType(TemplateId,
John McCall3cb0ebd2010-03-10 03:28:59 +00001349 ClassTemplate->getInjectedClassNameSpecialization(Context)))
Douglas Gregorb88e8882009-07-30 17:40:51 +00001350 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1351 // ... or a partial specialization?
1352 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1353 = ClassTemplate->findPartialSpecialization(TemplateId))
1354 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1355
1356 if (ExpectedTemplateParams)
Mike Stump1eb44332009-09-09 15:08:12 +00001357 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregorb88e8882009-07-30 17:40:51 +00001358 ExpectedTemplateParams,
Douglas Gregorfb898e12009-11-12 16:20:59 +00001359 true, TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00001360 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001361
1362 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregorb88e8882009-07-30 17:40:51 +00001363 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001364 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001365 diag::err_template_param_list_matches_nontemplate)
1366 << TemplateId
1367 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001368 else
1369 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001370 }
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001372 // If there were at least as many template-ids as there were template
1373 // parameter lists, then there are no template parameter lists remaining for
1374 // the declaration itself.
1375 if (Idx >= NumParamLists)
1376 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001377
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001378 // If there were too many template parameter lists, complain about that now.
1379 if (Idx != NumParamLists - 1) {
1380 while (Idx < NumParamLists - 1) {
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001381 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001382 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001383 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1384 : diag::err_template_spec_extra_headers)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001385 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1386 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001387
1388 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1389 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1390 diag::note_explicit_template_spec_does_not_need_header)
1391 << ExplicitSpecializationsInSpecifier.back();
1392 ExplicitSpecializationsInSpecifier.pop_back();
1393 }
1394
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001395 ++Idx;
1396 }
1397 }
Mike Stump1eb44332009-09-09 15:08:12 +00001398
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001399 // Return the last template parameter list, which corresponds to the
1400 // entity being declared.
1401 return ParamLists[NumParamLists - 1];
1402}
1403
Douglas Gregor7532dc62009-03-30 22:58:21 +00001404QualType Sema::CheckTemplateIdType(TemplateName Name,
1405 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001406 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001407 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001408 if (!Template) {
1409 // The template name does not resolve to a template, so we just
1410 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001411 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001412 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001413
Douglas Gregor40808ce2009-03-09 23:48:35 +00001414 // Check that the template argument list is well-formed for this
1415 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001416 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCalld5532b62009-11-23 01:53:49 +00001417 TemplateArgs.size());
1418 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001419 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001420 return QualType();
1421
Mike Stump1eb44332009-09-09 15:08:12 +00001422 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001423 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001424 "Converted template argument list is too short!");
1425
1426 QualType CanonType;
1427
Douglas Gregorcaddba02009-11-12 18:38:13 +00001428 if (Name.isDependent() ||
1429 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001430 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001431 // This class template specialization is a dependent
1432 // type. Therefore, its canonical type is another class template
1433 // specialization type that contains all of the converted
1434 // arguments in canonical form. This ensures that, e.g., A<T> and
1435 // A<T, T> have identical types when A is declared as:
1436 //
1437 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001438 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001439 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001440 Converted.getFlatArguments(),
1441 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Douglas Gregor1275ae02009-07-28 23:00:59 +00001443 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001444 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001445 // In the future, we need to teach getTemplateSpecializationType to only
1446 // build the canonical type and return that to us.
1447 CanonType = Context.getCanonicalType(CanonType);
Mike Stump1eb44332009-09-09 15:08:12 +00001448 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001449 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001450 // Find the class template specialization declaration that
1451 // corresponds to these arguments.
1452 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001453 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001454 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001455 Converted.flatSize(),
1456 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001457 void *InsertPos = 0;
1458 ClassTemplateSpecializationDecl *Decl
1459 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1460 if (!Decl) {
1461 // This is the first time we have referenced this class template
1462 // specialization. Create the canonical declaration and add it to
1463 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001464 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001465 ClassTemplate->getDeclContext(),
John McCall9cc78072009-09-11 07:25:08 +00001466 ClassTemplate->getLocation(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001467 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00001468 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001469 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1470 Decl->setLexicalDeclContext(CurContext);
1471 }
1472
1473 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001474 assert(isa<RecordType>(CanonType) &&
1475 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001476 }
Mike Stump1eb44332009-09-09 15:08:12 +00001477
Douglas Gregor40808ce2009-03-09 23:48:35 +00001478 // Build the fully-sugared type for this class template
1479 // specialization, which refers back to the class template
1480 // specialization we created or found.
John McCalld5532b62009-11-23 01:53:49 +00001481 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001482}
1483
Douglas Gregorcc636682009-02-17 23:15:12 +00001484Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001485Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001486 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001487 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001488 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001489 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001490
Douglas Gregor40808ce2009-03-09 23:48:35 +00001491 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001492 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001493 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001494
John McCalld5532b62009-11-23 01:53:49 +00001495 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001496 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001497
1498 if (Result.isNull())
1499 return true;
1500
John McCalla93c9342009-12-07 02:54:59 +00001501 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001502 TemplateSpecializationTypeLoc TL
1503 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1504 TL.setTemplateNameLoc(TemplateLoc);
1505 TL.setLAngleLoc(LAngleLoc);
1506 TL.setRAngleLoc(RAngleLoc);
1507 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1508 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1509
1510 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCall6b2becf2009-09-08 17:47:29 +00001511}
John McCallf1bbbb42009-09-04 01:14:41 +00001512
John McCall6b2becf2009-09-08 17:47:29 +00001513Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1514 TagUseKind TUK,
1515 DeclSpec::TST TagSpec,
1516 SourceLocation TagLoc) {
1517 if (TypeResult.isInvalid())
1518 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001519
John McCall833ca992009-10-29 08:12:44 +00001520 // FIXME: preserve source info, ideally without copying the DI.
John McCalla93c9342009-12-07 02:54:59 +00001521 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001522 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001523
John McCall6b2becf2009-09-08 17:47:29 +00001524 // Verify the tag specifier.
1525 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001526
John McCall6b2becf2009-09-08 17:47:29 +00001527 if (const RecordType *RT = Type->getAs<RecordType>()) {
1528 RecordDecl *D = RT->getDecl();
1529
1530 IdentifierInfo *Id = D->getIdentifier();
1531 assert(Id && "templated class must have an identifier");
1532
1533 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1534 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001535 << Type
Douglas Gregor849b2432010-03-31 17:46:05 +00001536 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001537 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001538 }
1539 }
1540
John McCall6b2becf2009-09-08 17:47:29 +00001541 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1542
1543 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001544}
1545
John McCallf7a1a742009-11-24 19:00:30 +00001546Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1547 LookupResult &R,
1548 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001549 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001550 // FIXME: Can we do any checking at this point? I guess we could check the
1551 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001552 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001553 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001554
1555 // These should be filtered out by our callers.
1556 assert(!R.empty() && "empty lookup results when building templateid");
1557 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1558
1559 NestedNameSpecifier *Qualifier = 0;
1560 SourceRange QualifierRange;
1561 if (SS.isSet()) {
1562 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1563 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001564 }
John McCallc373d482010-01-27 01:50:18 +00001565
1566 // We don't want lookup warnings at this point.
1567 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001568
John McCallf7a1a742009-11-24 19:00:30 +00001569 bool Dependent
1570 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1571 &TemplateArgs);
1572 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001573 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001574 Qualifier, QualifierRange,
1575 R.getLookupName(), R.getNameLoc(),
1576 RequiresADL, TemplateArgs);
John McCallc373d482010-01-27 01:50:18 +00001577 ULE->addDecls(R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001578
1579 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001580}
1581
John McCallf7a1a742009-11-24 19:00:30 +00001582// We actually only call this from template instantiation.
1583Sema::OwningExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001584Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001585 DeclarationName Name,
1586 SourceLocation NameLoc,
1587 const TemplateArgumentListInfo &TemplateArgs) {
1588 DeclContext *DC;
1589 if (!(DC = computeDeclContext(SS, false)) ||
1590 DC->isDependentContext() ||
1591 RequireCompleteDeclContext(SS))
1592 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001593
John McCallf7a1a742009-11-24 19:00:30 +00001594 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1595 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00001596
John McCallf7a1a742009-11-24 19:00:30 +00001597 if (R.isAmbiguous())
1598 return ExprError();
1599
1600 if (R.empty()) {
1601 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1602 << Name << SS.getRange();
1603 return ExprError();
1604 }
1605
1606 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1607 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1608 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1609 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1610 return ExprError();
1611 }
1612
1613 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001614}
1615
Douglas Gregorc45c2322009-03-31 00:43:58 +00001616/// \brief Form a dependent template name.
1617///
1618/// This action forms a dependent template name given the template
1619/// name and its (presumably dependent) scope specifier. For
1620/// example, given "MetaFun::template apply", the scope specifier \p
1621/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1622/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump1eb44332009-09-09 15:08:12 +00001623Sema::TemplateTy
Douglas Gregorc45c2322009-03-31 00:43:58 +00001624Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001625 CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +00001626 UnqualifiedId &Name,
Douglas Gregora481edb2009-11-20 23:39:24 +00001627 TypeTy *ObjectType,
1628 bool EnteringContext) {
Douglas Gregor0707bc52010-01-19 16:01:07 +00001629 DeclContext *LookupCtx = 0;
1630 if (SS.isSet())
1631 LookupCtx = computeDeclContext(SS, EnteringContext);
1632 if (!LookupCtx && ObjectType)
1633 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1634 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001635 // C++0x [temp.names]p5:
1636 // If a name prefixed by the keyword template is not the name of
1637 // a template, the program is ill-formed. [Note: the keyword
1638 // template may not be applied to non-template members of class
1639 // templates. -end note ] [ Note: as is the case with the
1640 // typename prefix, the template prefix is allowed in cases
1641 // where it is not strictly necessary; i.e., when the
1642 // nested-name-specifier or the expression on the left of the ->
1643 // or . is not dependent on a template-parameter, or the use
1644 // does not appear in the scope of a template. -end note]
1645 //
1646 // Note: C++03 was more strict here, because it banned the use of
1647 // the "template" keyword prior to a template-name that was not a
1648 // dependent name. C++ DR468 relaxed this requirement (the
1649 // "template" keyword is now permitted). We follow the C++0x
1650 // rules, even in C++03 mode, retroactively applying the DR.
1651 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001652 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregora481edb2009-11-20 23:39:24 +00001653 EnteringContext, Template);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001654 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1655 isa<CXXRecordDecl>(LookupCtx) &&
1656 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001657 // This is a dependent template.
1658 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001659 Diag(Name.getSourceRange().getBegin(),
1660 diag::err_template_kw_refers_to_non_template)
1661 << GetNameFromUnqualifiedId(Name)
1662 << Name.getSourceRange();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001663 return TemplateTy();
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001664 } else {
1665 // We found something; return it.
1666 return Template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001667 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001668 }
1669
Mike Stump1eb44332009-09-09 15:08:12 +00001670 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001671 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001672
1673 switch (Name.getKind()) {
1674 case UnqualifiedId::IK_Identifier:
1675 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1676 Name.Identifier));
1677
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001678 case UnqualifiedId::IK_OperatorFunctionId:
1679 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1680 Name.OperatorFunctionId.Operator));
Sean Hunte6252d12009-11-28 08:58:14 +00001681
1682 case UnqualifiedId::IK_LiteralOperatorId:
1683 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1684
Douglas Gregor014e88d2009-11-03 23:16:33 +00001685 default:
1686 break;
1687 }
1688
1689 Diag(Name.getSourceRange().getBegin(),
1690 diag::err_template_kw_refers_to_non_template)
1691 << GetNameFromUnqualifiedId(Name)
1692 << Name.getSourceRange();
1693 return TemplateTy();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001694}
1695
Mike Stump1eb44332009-09-09 15:08:12 +00001696bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001697 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001698 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001699 const TemplateArgument &Arg = AL.getArgument();
1700
Anders Carlsson436b1562009-06-13 00:33:33 +00001701 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001702 switch(Arg.getKind()) {
1703 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00001704 // C++ [temp.arg.type]p1:
1705 // A template-argument for a template-parameter which is a
1706 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001707 break;
1708 case TemplateArgument::Template: {
1709 // We have a template type parameter but the template argument
1710 // is a template without any arguments.
1711 SourceRange SR = AL.getSourceRange();
1712 TemplateName Name = Arg.getAsTemplate();
1713 Diag(SR.getBegin(), diag::err_template_missing_args)
1714 << Name << SR;
1715 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1716 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00001717
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001718 return true;
1719 }
1720 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00001721 // We have a template type parameter but the template argument
1722 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001723 SourceRange SR = AL.getSourceRange();
1724 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001725 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Anders Carlsson436b1562009-06-13 00:33:33 +00001727 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001728 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001729 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001730
John McCalla93c9342009-12-07 02:54:59 +00001731 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001732 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Anders Carlsson436b1562009-06-13 00:33:33 +00001734 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001735 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001736 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001737 return false;
1738}
1739
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001740/// \brief Substitute template arguments into the default template argument for
1741/// the given template type parameter.
1742///
1743/// \param SemaRef the semantic analysis object for which we are performing
1744/// the substitution.
1745///
1746/// \param Template the template that we are synthesizing template arguments
1747/// for.
1748///
1749/// \param TemplateLoc the location of the template name that started the
1750/// template-id we are checking.
1751///
1752/// \param RAngleLoc the location of the right angle bracket ('>') that
1753/// terminates the template-id.
1754///
1755/// \param Param the template template parameter whose default we are
1756/// substituting into.
1757///
1758/// \param Converted the list of template arguments provided for template
1759/// parameters that precede \p Param in the template parameter list.
1760///
1761/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001762static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001763SubstDefaultTemplateArgument(Sema &SemaRef,
1764 TemplateDecl *Template,
1765 SourceLocation TemplateLoc,
1766 SourceLocation RAngleLoc,
1767 TemplateTypeParmDecl *Param,
1768 TemplateArgumentListBuilder &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001769 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001770
1771 // If the argument type is dependent, instantiate it now based
1772 // on the previously-computed template arguments.
1773 if (ArgType->getType()->isDependentType()) {
1774 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1775 /*TakeArgs=*/false);
1776
1777 MultiLevelTemplateArgumentList AllTemplateArgs
1778 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1779
1780 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1781 Template, Converted.getFlatArguments(),
1782 Converted.flatSize(),
1783 SourceRange(TemplateLoc, RAngleLoc));
1784
1785 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1786 Param->getDefaultArgumentLoc(),
1787 Param->getDeclName());
1788 }
1789
1790 return ArgType;
1791}
1792
1793/// \brief Substitute template arguments into the default template argument for
1794/// the given non-type template parameter.
1795///
1796/// \param SemaRef the semantic analysis object for which we are performing
1797/// the substitution.
1798///
1799/// \param Template the template that we are synthesizing template arguments
1800/// for.
1801///
1802/// \param TemplateLoc the location of the template name that started the
1803/// template-id we are checking.
1804///
1805/// \param RAngleLoc the location of the right angle bracket ('>') that
1806/// terminates the template-id.
1807///
Douglas Gregor788cd062009-11-11 01:00:40 +00001808/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001809/// substituting into.
1810///
1811/// \param Converted the list of template arguments provided for template
1812/// parameters that precede \p Param in the template parameter list.
1813///
1814/// \returns the substituted template argument, or NULL if an error occurred.
1815static Sema::OwningExprResult
1816SubstDefaultTemplateArgument(Sema &SemaRef,
1817 TemplateDecl *Template,
1818 SourceLocation TemplateLoc,
1819 SourceLocation RAngleLoc,
1820 NonTypeTemplateParmDecl *Param,
1821 TemplateArgumentListBuilder &Converted) {
1822 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1823 /*TakeArgs=*/false);
1824
1825 MultiLevelTemplateArgumentList AllTemplateArgs
1826 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1827
1828 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1829 Template, Converted.getFlatArguments(),
1830 Converted.flatSize(),
1831 SourceRange(TemplateLoc, RAngleLoc));
1832
1833 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1834}
1835
Douglas Gregor788cd062009-11-11 01:00:40 +00001836/// \brief Substitute template arguments into the default template argument for
1837/// the given template template parameter.
1838///
1839/// \param SemaRef the semantic analysis object for which we are performing
1840/// the substitution.
1841///
1842/// \param Template the template that we are synthesizing template arguments
1843/// for.
1844///
1845/// \param TemplateLoc the location of the template name that started the
1846/// template-id we are checking.
1847///
1848/// \param RAngleLoc the location of the right angle bracket ('>') that
1849/// terminates the template-id.
1850///
1851/// \param Param the template template parameter whose default we are
1852/// substituting into.
1853///
1854/// \param Converted the list of template arguments provided for template
1855/// parameters that precede \p Param in the template parameter list.
1856///
1857/// \returns the substituted template argument, or NULL if an error occurred.
1858static TemplateName
1859SubstDefaultTemplateArgument(Sema &SemaRef,
1860 TemplateDecl *Template,
1861 SourceLocation TemplateLoc,
1862 SourceLocation RAngleLoc,
1863 TemplateTemplateParmDecl *Param,
1864 TemplateArgumentListBuilder &Converted) {
1865 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1866 /*TakeArgs=*/false);
1867
1868 MultiLevelTemplateArgumentList AllTemplateArgs
1869 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1870
1871 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1872 Template, Converted.getFlatArguments(),
1873 Converted.flatSize(),
1874 SourceRange(TemplateLoc, RAngleLoc));
1875
1876 return SemaRef.SubstTemplateName(
1877 Param->getDefaultArgument().getArgument().getAsTemplate(),
1878 Param->getDefaultArgument().getTemplateNameLoc(),
1879 AllTemplateArgs);
1880}
1881
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001882/// \brief If the given template parameter has a default template
1883/// argument, substitute into that default template argument and
1884/// return the corresponding template argument.
1885TemplateArgumentLoc
1886Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1887 SourceLocation TemplateLoc,
1888 SourceLocation RAngleLoc,
1889 Decl *Param,
1890 TemplateArgumentListBuilder &Converted) {
1891 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1892 if (!TypeParm->hasDefaultArgument())
1893 return TemplateArgumentLoc();
1894
John McCalla93c9342009-12-07 02:54:59 +00001895 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001896 TemplateLoc,
1897 RAngleLoc,
1898 TypeParm,
1899 Converted);
1900 if (DI)
1901 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1902
1903 return TemplateArgumentLoc();
1904 }
1905
1906 if (NonTypeTemplateParmDecl *NonTypeParm
1907 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1908 if (!NonTypeParm->hasDefaultArgument())
1909 return TemplateArgumentLoc();
1910
1911 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1912 TemplateLoc,
1913 RAngleLoc,
1914 NonTypeParm,
1915 Converted);
1916 if (Arg.isInvalid())
1917 return TemplateArgumentLoc();
1918
1919 Expr *ArgE = Arg.takeAs<Expr>();
1920 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1921 }
1922
1923 TemplateTemplateParmDecl *TempTempParm
1924 = cast<TemplateTemplateParmDecl>(Param);
1925 if (!TempTempParm->hasDefaultArgument())
1926 return TemplateArgumentLoc();
1927
1928 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1929 TemplateLoc,
1930 RAngleLoc,
1931 TempTempParm,
1932 Converted);
1933 if (TName.isNull())
1934 return TemplateArgumentLoc();
1935
1936 return TemplateArgumentLoc(TemplateArgument(TName),
1937 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1938 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1939}
1940
Douglas Gregore7526412009-11-11 19:31:23 +00001941/// \brief Check that the given template argument corresponds to the given
1942/// template parameter.
1943bool Sema::CheckTemplateArgument(NamedDecl *Param,
1944 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00001945 TemplateDecl *Template,
1946 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00001947 SourceLocation RAngleLoc,
Douglas Gregor02024a92010-03-28 02:42:43 +00001948 TemplateArgumentListBuilder &Converted,
1949 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00001950 // Check template type parameters.
1951 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00001952 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00001953
Douglas Gregord9e15302009-11-11 19:41:09 +00001954 // Check non-type template parameters.
1955 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00001956 // Do substitution on the type of the non-type template parameter
1957 // with the template arguments we've seen thus far.
1958 QualType NTTPType = NTTP->getType();
1959 if (NTTPType->isDependentType()) {
1960 // Do substitution on the type of the non-type template parameter.
1961 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1962 NTTP, Converted.getFlatArguments(),
1963 Converted.flatSize(),
1964 SourceRange(TemplateLoc, RAngleLoc));
1965
1966 TemplateArgumentList TemplateArgs(Context, Converted,
1967 /*TakeArgs=*/false);
1968 NTTPType = SubstType(NTTPType,
1969 MultiLevelTemplateArgumentList(TemplateArgs),
1970 NTTP->getLocation(),
1971 NTTP->getDeclName());
1972 // If that worked, check the non-type template parameter type
1973 // for validity.
1974 if (!NTTPType.isNull())
1975 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1976 NTTP->getLocation());
1977 if (NTTPType.isNull())
1978 return true;
1979 }
1980
1981 switch (Arg.getArgument().getKind()) {
1982 case TemplateArgument::Null:
1983 assert(false && "Should never see a NULL template argument here");
1984 return true;
1985
1986 case TemplateArgument::Expression: {
1987 Expr *E = Arg.getArgument().getAsExpr();
1988 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00001989 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00001990 return true;
1991
1992 Converted.Append(Result);
1993 break;
1994 }
1995
1996 case TemplateArgument::Declaration:
1997 case TemplateArgument::Integral:
1998 // We've already checked this template argument, so just copy
1999 // it to the list of converted arguments.
2000 Converted.Append(Arg.getArgument());
2001 break;
2002
2003 case TemplateArgument::Template:
2004 // We were given a template template argument. It may not be ill-formed;
2005 // see below.
2006 if (DependentTemplateName *DTN
2007 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2008 // We have a template argument such as \c T::template X, which we
2009 // parsed as a template template argument. However, since we now
2010 // know that we need a non-type template argument, convert this
2011 // template name into an expression.
John McCallf7a1a742009-11-24 19:00:30 +00002012 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2013 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002014 Arg.getTemplateQualifierRange(),
John McCallf7a1a742009-11-24 19:00:30 +00002015 DTN->getIdentifier(),
2016 Arg.getTemplateNameLoc());
Douglas Gregore7526412009-11-11 19:31:23 +00002017
2018 TemplateArgument Result;
2019 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2020 return true;
2021
2022 Converted.Append(Result);
2023 break;
2024 }
2025
2026 // We have a template argument that actually does refer to a class
2027 // template, template alias, or template template parameter, and
2028 // therefore cannot be a non-type template argument.
2029 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2030 << Arg.getSourceRange();
2031
2032 Diag(Param->getLocation(), diag::note_template_param_here);
2033 return true;
2034
2035 case TemplateArgument::Type: {
2036 // We have a non-type template parameter but the template
2037 // argument is a type.
2038
2039 // C++ [temp.arg]p2:
2040 // In a template-argument, an ambiguity between a type-id and
2041 // an expression is resolved to a type-id, regardless of the
2042 // form of the corresponding template-parameter.
2043 //
2044 // We warn specifically about this case, since it can be rather
2045 // confusing for users.
2046 QualType T = Arg.getArgument().getAsType();
2047 SourceRange SR = Arg.getSourceRange();
2048 if (T->isFunctionType())
2049 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2050 else
2051 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2052 Diag(Param->getLocation(), diag::note_template_param_here);
2053 return true;
2054 }
2055
2056 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002057 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002058 break;
2059 }
2060
2061 return false;
2062 }
2063
2064
2065 // Check template template parameters.
2066 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2067
2068 // Substitute into the template parameter list of the template
2069 // template parameter, since previously-supplied template arguments
2070 // may appear within the template template parameter.
2071 {
2072 // Set up a template instantiation context.
2073 LocalInstantiationScope Scope(*this);
2074 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2075 TempParm, Converted.getFlatArguments(),
2076 Converted.flatSize(),
2077 SourceRange(TemplateLoc, RAngleLoc));
2078
2079 TemplateArgumentList TemplateArgs(Context, Converted,
2080 /*TakeArgs=*/false);
2081 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2082 SubstDecl(TempParm, CurContext,
2083 MultiLevelTemplateArgumentList(TemplateArgs)));
2084 if (!TempParm)
2085 return true;
2086
2087 // FIXME: TempParam is leaked.
2088 }
2089
2090 switch (Arg.getArgument().getKind()) {
2091 case TemplateArgument::Null:
2092 assert(false && "Should never see a NULL template argument here");
2093 return true;
2094
2095 case TemplateArgument::Template:
2096 if (CheckTemplateArgument(TempParm, Arg))
2097 return true;
2098
2099 Converted.Append(Arg.getArgument());
2100 break;
2101
2102 case TemplateArgument::Expression:
2103 case TemplateArgument::Type:
2104 // We have a template template parameter but the template
2105 // argument does not refer to a template.
2106 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2107 return true;
2108
2109 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002110 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002111 "Declaration argument with template template parameter");
2112 break;
2113 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002114 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002115 "Integral argument with template template parameter");
2116 break;
2117
2118 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002119 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002120 break;
2121 }
2122
2123 return false;
2124}
2125
Douglas Gregorc15cb382009-02-09 23:23:08 +00002126/// \brief Check that the given template argument list is well-formed
2127/// for specializing the given template.
2128bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2129 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002130 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002131 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002132 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002133 TemplateParameterList *Params = Template->getTemplateParameters();
2134 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002135 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002136 bool Invalid = false;
2137
John McCalld5532b62009-11-23 01:53:49 +00002138 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2139
Mike Stump1eb44332009-09-09 15:08:12 +00002140 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002141 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002143 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002144 (NumArgs < Params->getMinRequiredArguments() &&
2145 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002146 // FIXME: point at either the first arg beyond what we can handle,
2147 // or the '>', depending on whether we have too many or too few
2148 // arguments.
2149 SourceRange Range;
2150 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002151 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002152 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2153 << (NumArgs > NumParams)
2154 << (isa<ClassTemplateDecl>(Template)? 0 :
2155 isa<FunctionTemplateDecl>(Template)? 1 :
2156 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2157 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002158 Diag(Template->getLocation(), diag::note_template_decl_here)
2159 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002160 Invalid = true;
2161 }
Mike Stump1eb44332009-09-09 15:08:12 +00002162
2163 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002164 // [...] The type and form of each template-argument specified in
2165 // a template-id shall match the type and form specified for the
2166 // corresponding parameter declared by the template in its
2167 // template-parameter-list.
2168 unsigned ArgIdx = 0;
2169 for (TemplateParameterList::iterator Param = Params->begin(),
2170 ParamEnd = Params->end();
2171 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002172 if (ArgIdx > NumArgs && PartialTemplateArgs)
2173 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Douglas Gregord9e15302009-11-11 19:41:09 +00002175 // If we have a template parameter pack, check every remaining template
2176 // argument against that template parameter pack.
2177 if ((*Param)->isTemplateParameterPack()) {
2178 Converted.BeginPack();
2179 for (; ArgIdx < NumArgs; ++ArgIdx) {
2180 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2181 TemplateLoc, RAngleLoc, Converted)) {
2182 Invalid = true;
2183 break;
2184 }
2185 }
2186 Converted.EndPack();
2187 continue;
2188 }
2189
Douglas Gregorf35f8282009-11-11 21:54:23 +00002190 if (ArgIdx < NumArgs) {
2191 // Check the template argument we were given.
2192 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2193 TemplateLoc, RAngleLoc, Converted))
2194 return true;
2195
2196 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002197 }
Douglas Gregore7526412009-11-11 19:31:23 +00002198
Douglas Gregorf35f8282009-11-11 21:54:23 +00002199 // We have a default template argument that we will use.
2200 TemplateArgumentLoc Arg;
2201
2202 // Retrieve the default template argument from the template
2203 // parameter. For each kind of template parameter, we substitute the
2204 // template arguments provided thus far and any "outer" template arguments
2205 // (when the template parameter was part of a nested template) into
2206 // the default argument.
2207 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2208 if (!TTP->hasDefaultArgument()) {
2209 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2210 break;
2211 }
2212
John McCalla93c9342009-12-07 02:54:59 +00002213 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002214 Template,
2215 TemplateLoc,
2216 RAngleLoc,
2217 TTP,
2218 Converted);
2219 if (!ArgType)
2220 return true;
2221
2222 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2223 ArgType);
2224 } else if (NonTypeTemplateParmDecl *NTTP
2225 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2226 if (!NTTP->hasDefaultArgument()) {
2227 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2228 break;
2229 }
2230
2231 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2232 TemplateLoc,
2233 RAngleLoc,
2234 NTTP,
2235 Converted);
2236 if (E.isInvalid())
2237 return true;
2238
2239 Expr *Ex = E.takeAs<Expr>();
2240 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2241 } else {
2242 TemplateTemplateParmDecl *TempParm
2243 = cast<TemplateTemplateParmDecl>(*Param);
2244
2245 if (!TempParm->hasDefaultArgument()) {
2246 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2247 break;
2248 }
2249
2250 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2251 TemplateLoc,
2252 RAngleLoc,
2253 TempParm,
2254 Converted);
2255 if (Name.isNull())
2256 return true;
2257
2258 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2259 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2260 TempParm->getDefaultArgument().getTemplateNameLoc());
2261 }
2262
2263 // Introduce an instantiation record that describes where we are using
2264 // the default template argument.
2265 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2266 Converted.getFlatArguments(),
2267 Converted.flatSize(),
2268 SourceRange(TemplateLoc, RAngleLoc));
2269
2270 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002271 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002272 RAngleLoc, Converted))
2273 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002274 }
2275
2276 return Invalid;
2277}
2278
2279/// \brief Check a template argument against its corresponding
2280/// template type parameter.
2281///
2282/// This routine implements the semantics of C++ [temp.arg.type]. It
2283/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002284bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002285 TypeSourceInfo *ArgInfo) {
2286 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002287 QualType Arg = ArgInfo->getType();
2288
Douglas Gregorc15cb382009-02-09 23:23:08 +00002289 // C++ [temp.arg.type]p2:
2290 // A local type, a type with no linkage, an unnamed type or a type
2291 // compounded from any of these types shall not be used as a
2292 // template-argument for a template type-parameter.
2293 //
2294 // FIXME: Perform the recursive and no-linkage type checks.
2295 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00002296 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002297 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00002298 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002299 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00002300 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2301 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2302 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2303 << QualType(Tag, 0) << SR;
2304 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00002305 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall833ca992009-10-29 08:12:44 +00002306 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2307 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002308 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2309 return true;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002310 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2311 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2312 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002313 }
2314
2315 return false;
2316}
2317
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002318/// \brief Checks whether the given template argument is the address
2319/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002320static bool
2321CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2322 NonTypeTemplateParmDecl *Param,
2323 QualType ParamType,
2324 Expr *ArgIn,
2325 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002326 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002327 Expr *Arg = ArgIn;
2328 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002329
2330 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002331 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002332 Arg = Cast->getSubExpr();
2333
2334 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002335 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002336 // A template-argument for a non-type, non-template
2337 // template-parameter shall be one of: [...]
2338 //
2339 // -- the address of an object or function with external
2340 // linkage, including function templates and function
2341 // template-ids but excluding non-static class members,
2342 // expressed as & id-expression where the & is optional if
2343 // the name refers to a function or array, or if the
2344 // corresponding template-parameter is a reference; or
2345 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002346
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002347 // Ignore (and complain about) any excess parentheses.
2348 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2349 if (!Invalid) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002350 S.Diag(Arg->getSourceRange().getBegin(),
2351 diag::err_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002352 << Arg->getSourceRange();
2353 Invalid = true;
2354 }
2355
2356 Arg = Parens->getSubExpr();
2357 }
2358
Douglas Gregorb7a09262010-04-01 18:32:35 +00002359 bool AddressTaken = false;
2360 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002361 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002362 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002363 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb7a09262010-04-01 18:32:35 +00002364 AddressTaken = true;
2365 AddrOpLoc = UnOp->getOperatorLoc();
2366 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002367 } else
2368 DRE = dyn_cast<DeclRefExpr>(Arg);
2369
Douglas Gregorb7a09262010-04-01 18:32:35 +00002370 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002371 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2372 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002373 S.Diag(Param->getLocation(), diag::note_template_param_here);
2374 return true;
2375 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002376
2377 // Stop checking the precise nature of the argument if it is value dependent,
2378 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002379 if (Arg->isValueDependent()) {
2380 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth038cc392010-01-31 10:01:20 +00002381 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002382 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002383
Douglas Gregorb7a09262010-04-01 18:32:35 +00002384 if (!isa<ValueDecl>(DRE->getDecl())) {
2385 S.Diag(Arg->getSourceRange().getBegin(),
2386 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002387 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002388 S.Diag(Param->getLocation(), diag::note_template_param_here);
2389 return true;
2390 }
2391
2392 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002393
2394 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00002395 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2396 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002397 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002398 S.Diag(Param->getLocation(), diag::note_template_param_here);
2399 return true;
2400 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002401
2402 // Cannot refer to non-static member functions
2403 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00002404 if (!Method->isStatic()) {
2405 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002406 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002407 S.Diag(Param->getLocation(), diag::note_template_param_here);
2408 return true;
2409 }
Mike Stump1eb44332009-09-09 15:08:12 +00002410
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002411 // Functions must have external linkage.
2412 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002413 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002414 S.Diag(Arg->getSourceRange().getBegin(),
2415 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002416 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002417 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002418 << true;
2419 return true;
2420 }
2421
2422 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002423 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002424
Douglas Gregorb7a09262010-04-01 18:32:35 +00002425 // If the template parameter has pointer type, the function decays.
2426 if (ParamType->isPointerType() && !AddressTaken)
2427 ArgType = S.Context.getPointerType(Func->getType());
2428 else if (AddressTaken && ParamType->isReferenceType()) {
2429 // If we originally had an address-of operator, but the
2430 // parameter has reference type, complain and (if things look
2431 // like they will work) drop the address-of operator.
2432 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2433 ParamType.getNonReferenceType())) {
2434 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2435 << ParamType;
2436 S.Diag(Param->getLocation(), diag::note_template_param_here);
2437 return true;
2438 }
2439
2440 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2441 << ParamType
2442 << FixItHint::CreateRemoval(AddrOpLoc);
2443 S.Diag(Param->getLocation(), diag::note_template_param_here);
2444
2445 ArgType = Func->getType();
2446 }
2447 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002448 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002449 S.Diag(Arg->getSourceRange().getBegin(),
2450 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002451 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002452 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002453 << true;
2454 return true;
2455 }
2456
Douglas Gregorb7a09262010-04-01 18:32:35 +00002457 // A value of reference type is not an object.
2458 if (Var->getType()->isReferenceType()) {
2459 S.Diag(Arg->getSourceRange().getBegin(),
2460 diag::err_template_arg_reference_var)
2461 << Var->getType() << Arg->getSourceRange();
2462 S.Diag(Param->getLocation(), diag::note_template_param_here);
2463 return true;
2464 }
2465
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002466 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002467 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002468
2469 // If the template parameter has pointer type, we must have taken
2470 // the address of this object.
2471 if (ParamType->isReferenceType()) {
2472 if (AddressTaken) {
2473 // If we originally had an address-of operator, but the
2474 // parameter has reference type, complain and (if things look
2475 // like they will work) drop the address-of operator.
2476 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2477 ParamType.getNonReferenceType())) {
2478 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2479 << ParamType;
2480 S.Diag(Param->getLocation(), diag::note_template_param_here);
2481 return true;
2482 }
2483
2484 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2485 << ParamType
2486 << FixItHint::CreateRemoval(AddrOpLoc);
2487 S.Diag(Param->getLocation(), diag::note_template_param_here);
2488
2489 ArgType = Var->getType();
2490 }
2491 } else if (!AddressTaken && ParamType->isPointerType()) {
2492 if (Var->getType()->isArrayType()) {
2493 // Array-to-pointer decay.
2494 ArgType = S.Context.getArrayDecayedType(Var->getType());
2495 } else {
2496 // If the template parameter has pointer type but the address of
2497 // this object was not taken, complain and (possibly) recover by
2498 // taking the address of the entity.
2499 ArgType = S.Context.getPointerType(Var->getType());
2500 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2501 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2502 << ParamType;
2503 S.Diag(Param->getLocation(), diag::note_template_param_here);
2504 return true;
2505 }
2506
2507 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2508 << ParamType
2509 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2510
2511 S.Diag(Param->getLocation(), diag::note_template_param_here);
2512 }
2513 }
2514 } else {
2515 // We found something else, but we don't know specifically what it is.
2516 S.Diag(Arg->getSourceRange().getBegin(),
2517 diag::err_template_arg_not_object_or_func)
2518 << Arg->getSourceRange();
2519 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2520 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002521 }
Mike Stump1eb44332009-09-09 15:08:12 +00002522
Douglas Gregorb7a09262010-04-01 18:32:35 +00002523 if (ParamType->isPointerType() &&
2524 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2525 S.IsQualificationConversion(ArgType, ParamType)) {
2526 // For pointer-to-object types, qualification conversions are
2527 // permitted.
2528 } else {
2529 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2530 if (!ParamRef->getPointeeType()->isFunctionType()) {
2531 // C++ [temp.arg.nontype]p5b3:
2532 // For a non-type template-parameter of type reference to
2533 // object, no conversions apply. The type referred to by the
2534 // reference may be more cv-qualified than the (otherwise
2535 // identical) type of the template- argument. The
2536 // template-parameter is bound directly to the
2537 // template-argument, which shall be an lvalue.
2538
2539 // FIXME: Other qualifiers?
2540 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2541 unsigned ArgQuals = ArgType.getCVRQualifiers();
2542
2543 if ((ParamQuals | ArgQuals) != ParamQuals) {
2544 S.Diag(Arg->getSourceRange().getBegin(),
2545 diag::err_template_arg_ref_bind_ignores_quals)
2546 << ParamType << Arg->getType()
2547 << Arg->getSourceRange();
2548 S.Diag(Param->getLocation(), diag::note_template_param_here);
2549 return true;
2550 }
2551 }
2552 }
2553
2554 // At this point, the template argument refers to an object or
2555 // function with external linkage. We now need to check whether the
2556 // argument and parameter types are compatible.
2557 if (!S.Context.hasSameUnqualifiedType(ArgType,
2558 ParamType.getNonReferenceType())) {
2559 // We can't perform this conversion or binding.
2560 if (ParamType->isReferenceType())
2561 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2562 << ParamType << Arg->getType() << Arg->getSourceRange();
2563 else
2564 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2565 << Arg->getType() << ParamType << Arg->getSourceRange();
2566 S.Diag(Param->getLocation(), diag::note_template_param_here);
2567 return true;
2568 }
2569 }
2570
2571 // Create the template argument.
2572 Converted = TemplateArgument(Entity->getCanonicalDecl());
2573 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002574}
2575
2576/// \brief Checks whether the given template argument is a pointer to
2577/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002578bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2579 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002580 bool Invalid = false;
2581
2582 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002583 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002584 Arg = Cast->getSubExpr();
2585
2586 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002587 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002588 // A template-argument for a non-type, non-template
2589 // template-parameter shall be one of: [...]
2590 //
2591 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002592 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002593
2594 // Ignore (and complain about) any excess parentheses.
2595 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2596 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002597 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002598 diag::err_template_arg_extra_parens)
2599 << Arg->getSourceRange();
2600 Invalid = true;
2601 }
2602
2603 Arg = Parens->getSubExpr();
2604 }
2605
Douglas Gregorcaddba02009-11-12 18:38:13 +00002606 // A pointer-to-member constant written &Class::member.
2607 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002608 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2609 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2610 if (DRE && !DRE->getQualifier())
2611 DRE = 0;
2612 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002613 }
2614 // A constant of pointer-to-member type.
2615 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2616 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2617 if (VD->getType()->isMemberPointerType()) {
2618 if (isa<NonTypeTemplateParmDecl>(VD) ||
2619 (isa<VarDecl>(VD) &&
2620 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2621 if (Arg->isTypeDependent() || Arg->isValueDependent())
2622 Converted = TemplateArgument(Arg->Retain());
2623 else
2624 Converted = TemplateArgument(VD->getCanonicalDecl());
2625 return Invalid;
2626 }
2627 }
2628 }
2629
2630 DRE = 0;
2631 }
2632
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002633 if (!DRE)
2634 return Diag(Arg->getSourceRange().getBegin(),
2635 diag::err_template_arg_not_pointer_to_member_form)
2636 << Arg->getSourceRange();
2637
2638 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2639 assert((isa<FieldDecl>(DRE->getDecl()) ||
2640 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2641 "Only non-static member pointers can make it here");
2642
2643 // Okay: this is the address of a non-static member, and therefore
2644 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002645 if (Arg->isTypeDependent() || Arg->isValueDependent())
2646 Converted = TemplateArgument(Arg->Retain());
2647 else
2648 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002649 return Invalid;
2650 }
2651
2652 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002653 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002654 diag::err_template_arg_not_pointer_to_member_form)
2655 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002656 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002657 diag::note_template_arg_refers_here);
2658 return true;
2659}
2660
Douglas Gregorc15cb382009-02-09 23:23:08 +00002661/// \brief Check a template argument against its corresponding
2662/// non-type template parameter.
2663///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002664/// This routine implements the semantics of C++ [temp.arg.nontype].
2665/// It returns true if an error occurred, and false otherwise. \p
2666/// InstantiatedParamType is the type of the non-type template
2667/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002668///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002669/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002670bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002671 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00002672 TemplateArgument &Converted,
2673 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002674 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2675
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002676 // If either the parameter has a dependent type or the argument is
2677 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00002678 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2679 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002680 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002681 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002682 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002683
2684 // C++ [temp.arg.nontype]p5:
2685 // The following conversions are performed on each expression used
2686 // as a non-type template-argument. If a non-type
2687 // template-argument cannot be converted to the type of the
2688 // corresponding template-parameter then the program is
2689 // ill-formed.
2690 //
2691 // -- for a non-type template-parameter of integral or
2692 // enumeration type, integral promotions (4.5) and integral
2693 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002694 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002695 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002696 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002697 // C++ [temp.arg.nontype]p1:
2698 // A template-argument for a non-type, non-template
2699 // template-parameter shall be one of:
2700 //
2701 // -- an integral constant-expression of integral or enumeration
2702 // type; or
2703 // -- the name of a non-type template-parameter; or
2704 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002705 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002706 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002707 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002708 diag::err_template_arg_not_integral_or_enumeral)
2709 << ArgType << Arg->getSourceRange();
2710 Diag(Param->getLocation(), diag::note_template_param_here);
2711 return true;
2712 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002713 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002714 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2715 << ArgType << Arg->getSourceRange();
2716 return true;
2717 }
2718
Douglas Gregor02024a92010-03-28 02:42:43 +00002719 // From here on out, all we care about are the unqualified forms
2720 // of the parameter and argument types.
2721 ParamType = ParamType.getUnqualifiedType();
2722 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002723
2724 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002725 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002726 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00002727 } else if (CTAK == CTAK_Deduced) {
2728 // C++ [temp.deduct.type]p17:
2729 // If, in the declaration of a function template with a non-type
2730 // template-parameter, the non-type template- parameter is used
2731 // in an expression in the function parameter-list and, if the
2732 // corresponding template-argument is deduced, the
2733 // template-argument type shall match the type of the
2734 // template-parameter exactly, except that a template-argument
2735 // deduced from an array bound may be of any integral type.
2736 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2737 << ArgType << ParamType;
2738 Diag(Param->getLocation(), diag::note_template_param_here);
2739 return true;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002740 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2741 !ParamType->isEnumeralType()) {
2742 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002743 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002744 } else {
2745 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002746 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002747 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002748 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002749 Diag(Param->getLocation(), diag::note_template_param_here);
2750 return true;
2751 }
2752
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002753 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002754 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002755 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002756
2757 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002758 llvm::APSInt OldValue = Value;
2759
2760 // Coerce the template argument's value to the value it will have
2761 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002762 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002763 if (Value.getBitWidth() != AllowedBits)
2764 Value.extOrTrunc(AllowedBits);
2765 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002766
2767 // Complain if an unsigned parameter received a negative value.
2768 if (IntegerType->isUnsignedIntegerType()
2769 && (OldValue.isSigned() && OldValue.isNegative())) {
2770 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2771 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2772 << Arg->getSourceRange();
2773 Diag(Param->getLocation(), diag::note_template_param_here);
2774 }
2775
2776 // Complain if we overflowed the template parameter's type.
2777 unsigned RequiredBits;
2778 if (IntegerType->isUnsignedIntegerType())
2779 RequiredBits = OldValue.getActiveBits();
2780 else if (OldValue.isUnsigned())
2781 RequiredBits = OldValue.getActiveBits() + 1;
2782 else
2783 RequiredBits = OldValue.getMinSignedBits();
2784 if (RequiredBits > AllowedBits) {
2785 Diag(Arg->getSourceRange().getBegin(),
2786 diag::warn_template_arg_too_large)
2787 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2788 << Arg->getSourceRange();
2789 Diag(Param->getLocation(), diag::note_template_param_here);
2790 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002791 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002792
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002793 // Add the value of this argument to the list of converted
2794 // arguments. We use the bitwidth and signedness of the template
2795 // parameter.
2796 if (Arg->isValueDependent()) {
2797 // The argument is value-dependent. Create a new
2798 // TemplateArgument with the converted expression.
2799 Converted = TemplateArgument(Arg);
2800 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002801 }
2802
John McCall833ca992009-10-29 08:12:44 +00002803 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002804 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002805 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002806 return false;
2807 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002808
John McCall6bb80172010-03-30 21:47:33 +00002809 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2810
Douglas Gregorb7a09262010-04-01 18:32:35 +00002811 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2812 // from a template argument of type std::nullptr_t to a non-type
2813 // template parameter of type pointer to object, pointer to
2814 // function, or pointer-to-member, respectively.
2815 if (ArgType->isNullPtrType() &&
2816 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2817 Converted = TemplateArgument((NamedDecl *)0);
2818 return false;
2819 }
2820
Douglas Gregorb86b0572009-02-11 01:18:59 +00002821 // Handle pointer-to-function, reference-to-function, and
2822 // pointer-to-member-function all in (roughly) the same way.
2823 if (// -- For a non-type template-parameter of type pointer to
2824 // function, only the function-to-pointer conversion (4.3) is
2825 // applied. If the template-argument represents a set of
2826 // overloaded functions (or a pointer to such), the matching
2827 // function is selected from the set (13.4).
2828 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002829 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002830 // -- For a non-type template-parameter of type reference to
2831 // function, no conversions apply. If the template-argument
2832 // represents a set of overloaded functions, the matching
2833 // function is selected from the set (13.4).
2834 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002835 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002836 // -- For a non-type template-parameter of type pointer to
2837 // member function, no conversions apply. If the
2838 // template-argument represents a set of overloaded member
2839 // functions, the matching member function is selected from
2840 // the set (13.4).
2841 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002842 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002843 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002844
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002845 if (Arg->getType() == Context.OverloadTy) {
2846 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2847 true,
2848 FoundResult)) {
2849 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2850 return true;
2851
2852 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2853 ArgType = Arg->getType();
2854 } else
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002855 return true;
Douglas Gregora35284b2009-02-11 00:19:33 +00002856 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002857
Douglas Gregorb7a09262010-04-01 18:32:35 +00002858 if (!ParamType->isMemberPointerType())
2859 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2860 ParamType,
2861 Arg, Converted);
2862
2863 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
2864 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2865 Arg->isLvalue(Context) == Expr::LV_Valid);
2866 } else if (!Context.hasSameUnqualifiedType(ArgType,
2867 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002868 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002869 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002870 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002871 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002872 Diag(Param->getLocation(), diag::note_template_param_here);
2873 return true;
2874 }
Mike Stump1eb44332009-09-09 15:08:12 +00002875
Douglas Gregorb7a09262010-04-01 18:32:35 +00002876 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregora35284b2009-02-11 00:19:33 +00002877 }
2878
Chris Lattnerfe90de72009-02-20 21:37:53 +00002879 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002880 // -- for a non-type template-parameter of type pointer to
2881 // object, qualification conversions (4.4) and the
2882 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002883 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002884 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002885 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002886
Douglas Gregorb7a09262010-04-01 18:32:35 +00002887 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2888 ParamType,
2889 Arg, Converted);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002890 }
Mike Stump1eb44332009-09-09 15:08:12 +00002891
Ted Kremenek6217b802009-07-29 21:53:49 +00002892 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002893 // -- For a non-type template-parameter of type reference to
2894 // object, no conversions apply. The type referred to by the
2895 // reference may be more cv-qualified than the (otherwise
2896 // identical) type of the template-argument. The
2897 // template-parameter is bound directly to the
2898 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002899 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002900 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002901
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002902 if (Arg->getType() == Context.OverloadTy) {
2903 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2904 ParamRefType->getPointeeType(),
2905 true,
2906 FoundResult)) {
2907 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2908 return true;
2909
2910 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2911 ArgType = Arg->getType();
2912 } else
Douglas Gregorb7a09262010-04-01 18:32:35 +00002913 return true;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002914 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002915
Douglas Gregorb7a09262010-04-01 18:32:35 +00002916 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2917 ParamType,
2918 Arg, Converted);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002919 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002920
2921 // -- For a non-type template-parameter of type pointer to data
2922 // member, qualification conversions (4.4) are applied.
2923 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2924
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002925 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002926 // Types match exactly: nothing more to do here.
2927 } else if (IsQualificationConversion(ArgType, ParamType)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002928 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2929 Arg->isLvalue(Context) == Expr::LV_Valid);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002930 } else {
2931 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002932 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00002933 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002934 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00002935 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002936 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00002937 }
2938
Douglas Gregorcaddba02009-11-12 18:38:13 +00002939 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002940}
2941
2942/// \brief Check a template argument against its corresponding
2943/// template template parameter.
2944///
2945/// This routine implements the semantics of C++ [temp.arg.template].
2946/// It returns true if an error occurred, and false otherwise.
2947bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00002948 const TemplateArgumentLoc &Arg) {
2949 TemplateName Name = Arg.getArgument().getAsTemplate();
2950 TemplateDecl *Template = Name.getAsTemplateDecl();
2951 if (!Template) {
2952 // Any dependent template name is fine.
2953 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2954 return false;
2955 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002956
2957 // C++ [temp.arg.template]p1:
2958 // A template-argument for a template template-parameter shall be
2959 // the name of a class template, expressed as id-expression. Only
2960 // primary class templates are considered when matching the
2961 // template template argument with the corresponding parameter;
2962 // partial specializations are not considered even if their
2963 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002964 //
2965 // Note that we also allow template template parameters here, which
2966 // will happen when we are dealing with, e.g., class template
2967 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00002968 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002969 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002970 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00002971 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00002972 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00002973 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002974 << Template;
2975 }
2976
2977 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2978 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00002979 true,
2980 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00002981 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00002982}
2983
Douglas Gregor02024a92010-03-28 02:42:43 +00002984/// \brief Given a non-type template argument that refers to a
2985/// declaration and the type of its corresponding non-type template
2986/// parameter, produce an expression that properly refers to that
2987/// declaration.
2988Sema::OwningExprResult
2989Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
2990 QualType ParamType,
2991 SourceLocation Loc) {
2992 assert(Arg.getKind() == TemplateArgument::Declaration &&
2993 "Only declaration template arguments permitted here");
2994 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
2995
2996 if (VD->getDeclContext()->isRecord() &&
2997 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
2998 // If the value is a class member, we might have a pointer-to-member.
2999 // Determine whether the non-type template template parameter is of
3000 // pointer-to-member type. If so, we need to build an appropriate
3001 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3002 // would refer to the member itself.
3003 if (ParamType->isMemberPointerType()) {
3004 QualType ClassType
3005 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3006 NestedNameSpecifier *Qualifier
3007 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
3008 CXXScopeSpec SS;
3009 SS.setScopeRep(Qualifier);
3010 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
3011 VD->getType().getNonReferenceType(),
3012 Loc,
3013 &SS);
3014 if (RefExpr.isInvalid())
3015 return ExprError();
3016
3017 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
3018 assert(!RefExpr.isInvalid() &&
3019 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
3020 ParamType));
3021 return move(RefExpr);
3022 }
3023 }
3024
3025 QualType T = VD->getType().getNonReferenceType();
3026 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003027 // When the non-type template parameter is a pointer, take the
3028 // address of the declaration.
Douglas Gregor02024a92010-03-28 02:42:43 +00003029 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3030 if (RefExpr.isInvalid())
3031 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003032
3033 if (T->isFunctionType() || T->isArrayType()) {
3034 // Decay functions and arrays.
3035 Expr *RefE = (Expr *)RefExpr.get();
3036 DefaultFunctionArrayConversion(RefE);
3037 if (RefE != RefExpr.get()) {
3038 RefExpr.release();
3039 RefExpr = Owned(RefE);
3040 }
3041
3042 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00003043 }
3044
Douglas Gregorb7a09262010-04-01 18:32:35 +00003045 // Take the address of everything else
3046 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregor02024a92010-03-28 02:42:43 +00003047 }
3048
3049 // If the non-type template parameter has reference type, qualify the
3050 // resulting declaration reference with the extra qualifiers on the
3051 // type that the reference refers to.
3052 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3053 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3054
3055 return BuildDeclRefExpr(VD, T, Loc);
3056}
3057
3058/// \brief Construct a new expression that refers to the given
3059/// integral template argument with the given source-location
3060/// information.
3061///
3062/// This routine takes care of the mapping from an integral template
3063/// argument (which may have any integral type) to the appropriate
3064/// literal value.
3065Sema::OwningExprResult
3066Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3067 SourceLocation Loc) {
3068 assert(Arg.getKind() == TemplateArgument::Integral &&
3069 "Operation is only value for integral template arguments");
3070 QualType T = Arg.getIntegralType();
3071 if (T->isCharType() || T->isWideCharType())
3072 return Owned(new (Context) CharacterLiteral(
3073 Arg.getAsIntegral()->getZExtValue(),
3074 T->isWideCharType(),
3075 T,
3076 Loc));
3077 if (T->isBooleanType())
3078 return Owned(new (Context) CXXBoolLiteralExpr(
3079 Arg.getAsIntegral()->getBoolValue(),
3080 T,
3081 Loc));
3082
3083 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3084}
3085
3086
Douglas Gregorddc29e12009-02-06 22:42:48 +00003087/// \brief Determine whether the given template parameter lists are
3088/// equivalent.
3089///
Mike Stump1eb44332009-09-09 15:08:12 +00003090/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00003091/// source code as part of a new template declaration.
3092///
3093/// \param Old The old template parameter list, typically found via
3094/// name lookup of the template declared with this template parameter
3095/// list.
3096///
3097/// \param Complain If true, this routine will produce a diagnostic if
3098/// the template parameter lists are not equivalent.
3099///
Douglas Gregorfb898e12009-11-12 16:20:59 +00003100/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00003101///
3102/// \param TemplateArgLoc If this source location is valid, then we
3103/// are actually checking the template parameter list of a template
3104/// argument (New) against the template parameter list of its
3105/// corresponding template template parameter (Old). We produce
3106/// slightly different diagnostics in this scenario.
3107///
Douglas Gregorddc29e12009-02-06 22:42:48 +00003108/// \returns True if the template parameter lists are equal, false
3109/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003110bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00003111Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3112 TemplateParameterList *Old,
3113 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003114 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003115 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003116 if (Old->size() != New->size()) {
3117 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003118 unsigned NextDiag = diag::err_template_param_list_different_arity;
3119 if (TemplateArgLoc.isValid()) {
3120 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3121 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00003122 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003123 Diag(New->getTemplateLoc(), NextDiag)
3124 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00003125 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003126 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00003127 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003128 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003129 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3130 }
3131
3132 return false;
3133 }
3134
3135 for (TemplateParameterList::iterator OldParm = Old->begin(),
3136 OldParmEnd = Old->end(), NewParm = New->begin();
3137 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3138 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003139 if (Complain) {
3140 unsigned NextDiag = diag::err_template_param_different_kind;
3141 if (TemplateArgLoc.isValid()) {
3142 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3143 NextDiag = diag::note_template_param_different_kind;
3144 }
3145 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003146 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003147 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003148 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00003149 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003150 return false;
3151 }
3152
3153 if (isa<TemplateTypeParmDecl>(*OldParm)) {
3154 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00003155 // know we're at the same index).
Mike Stump1eb44332009-09-09 15:08:12 +00003156 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003157 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3158 // The types of non-type template parameters must agree.
3159 NonTypeTemplateParmDecl *NewNTTP
3160 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00003161
3162 // If we are matching a template template argument to a template
3163 // template parameter and one of the non-type template parameter types
3164 // is dependent, then we must wait until template instantiation time
3165 // to actually compare the arguments.
3166 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3167 (OldNTTP->getType()->isDependentType() ||
3168 NewNTTP->getType()->isDependentType()))
3169 continue;
3170
Douglas Gregorddc29e12009-02-06 22:42:48 +00003171 if (Context.getCanonicalType(OldNTTP->getType()) !=
3172 Context.getCanonicalType(NewNTTP->getType())) {
3173 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003174 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3175 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003176 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003177 diag::err_template_arg_template_params_mismatch);
3178 NextDiag = diag::note_template_nontype_parm_different_type;
3179 }
3180 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003181 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00003182 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00003183 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00003184 diag::note_template_nontype_parm_prev_declaration)
3185 << OldNTTP->getType();
3186 }
3187 return false;
3188 }
3189 } else {
3190 // The template parameter lists of template template
3191 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00003192 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00003193 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00003194 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003195 = cast<TemplateTemplateParmDecl>(*OldParm);
3196 TemplateTemplateParmDecl *NewTTP
3197 = cast<TemplateTemplateParmDecl>(*NewParm);
3198 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3199 OldTTP->getTemplateParameters(),
3200 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003201 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00003202 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003203 return false;
3204 }
3205 }
3206
3207 return true;
3208}
3209
3210/// \brief Check whether a template can be declared within this scope.
3211///
3212/// If the template declaration is valid in this scope, returns
3213/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003214bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003215Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003216 // Find the nearest enclosing declaration scope.
3217 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3218 (S->getFlags() & Scope::TemplateParamScope) != 0)
3219 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003220
Douglas Gregorddc29e12009-02-06 22:42:48 +00003221 // C++ [temp]p2:
3222 // A template-declaration can appear only as a namespace scope or
3223 // class scope declaration.
3224 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003225 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3226 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003227 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003228 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003229
Eli Friedman1503f772009-07-31 01:43:05 +00003230 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003231 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003232
3233 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3234 return false;
3235
Mike Stump1eb44332009-09-09 15:08:12 +00003236 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003237 diag::err_template_outside_namespace_or_class_scope)
3238 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003239}
Douglas Gregorcc636682009-02-17 23:15:12 +00003240
Douglas Gregord5cb8762009-10-07 00:13:32 +00003241/// \brief Determine what kind of template specialization the given declaration
3242/// is.
3243static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3244 if (!D)
3245 return TSK_Undeclared;
3246
Douglas Gregorf6b11852009-10-08 15:14:33 +00003247 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3248 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003249 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3250 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003251 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3252 return Var->getTemplateSpecializationKind();
3253
Douglas Gregord5cb8762009-10-07 00:13:32 +00003254 return TSK_Undeclared;
3255}
3256
Douglas Gregor9302da62009-10-14 23:50:59 +00003257/// \brief Check whether a specialization is well-formed in the current
3258/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003259///
Douglas Gregor9302da62009-10-14 23:50:59 +00003260/// This routine determines whether a template specialization can be declared
3261/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003262///
3263/// \param S the semantic analysis object for which this check is being
3264/// performed.
3265///
3266/// \param Specialized the entity being specialized or instantiated, which
3267/// may be a kind of template (class template, function template, etc.) or
3268/// a member of a class template (member function, static data member,
3269/// member class).
3270///
3271/// \param PrevDecl the previous declaration of this entity, if any.
3272///
3273/// \param Loc the location of the explicit specialization or instantiation of
3274/// this entity.
3275///
3276/// \param IsPartialSpecialization whether this is a partial specialization of
3277/// a class template.
3278///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003279/// \returns true if there was an error that we cannot recover from, false
3280/// otherwise.
3281static bool CheckTemplateSpecializationScope(Sema &S,
3282 NamedDecl *Specialized,
3283 NamedDecl *PrevDecl,
3284 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003285 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003286 // Keep these "kind" numbers in sync with the %select statements in the
3287 // various diagnostics emitted by this routine.
3288 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003289 bool isTemplateSpecialization = false;
3290 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003291 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003292 isTemplateSpecialization = true;
3293 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003294 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003295 isTemplateSpecialization = true;
3296 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003297 EntityKind = 3;
3298 else if (isa<VarDecl>(Specialized))
3299 EntityKind = 4;
3300 else if (isa<RecordDecl>(Specialized))
3301 EntityKind = 5;
3302 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003303 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3304 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003305 return true;
3306 }
3307
Douglas Gregor88b70942009-02-25 22:02:03 +00003308 // C++ [temp.expl.spec]p2:
3309 // An explicit specialization shall be declared in the namespace
3310 // of which the template is a member, or, for member templates, in
3311 // the namespace of which the enclosing class or enclosing class
3312 // template is a member. An explicit specialization of a member
3313 // function, member class or static data member of a class
3314 // template shall be declared in the namespace of which the class
3315 // template is a member. Such a declaration may also be a
3316 // definition. If the declaration is not a definition, the
3317 // specialization may be defined later in the name- space in which
3318 // the explicit specialization was declared, or in a namespace
3319 // that encloses the one in which the explicit specialization was
3320 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003321 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3322 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003323 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003324 return true;
3325 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003326
Douglas Gregor0a407472009-10-07 17:30:37 +00003327 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3328 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003329 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003330 return true;
3331 }
3332
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003333 // C++ [temp.class.spec]p6:
3334 // A class template partial specialization may be declared or redeclared
3335 // in any namespace scope in which its definition may be defined (14.5.1
3336 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003337 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003338 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003339 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003340 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003341 if ((!PrevDecl ||
3342 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3343 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3344 // There is no prior declaration of this entity, so this
3345 // specialization must be in the same context as the template
3346 // itself.
3347 if (!DC->Equals(SpecializedContext)) {
3348 if (isa<TranslationUnitDecl>(SpecializedContext))
3349 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3350 << EntityKind << Specialized;
3351 else if (isa<NamespaceDecl>(SpecializedContext))
3352 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3353 << EntityKind << Specialized
3354 << cast<NamedDecl>(SpecializedContext);
3355
3356 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3357 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003358 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003359 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003360
3361 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003362 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003363 // Note that HandleDeclarator() performs this check for explicit
3364 // specializations of function templates, static data members, and member
3365 // functions, so we skip the check here for those kinds of entities.
3366 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003367 // Should we refactor that check, so that it occurs later?
3368 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003369 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3370 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003371 if (isa<TranslationUnitDecl>(SpecializedContext))
3372 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3373 << EntityKind << Specialized;
3374 else if (isa<NamespaceDecl>(SpecializedContext))
3375 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3376 << EntityKind << Specialized
3377 << cast<NamedDecl>(SpecializedContext);
3378
Douglas Gregor9302da62009-10-14 23:50:59 +00003379 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003380 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003381
3382 // FIXME: check for specialization-after-instantiation errors and such.
3383
Douglas Gregor88b70942009-02-25 22:02:03 +00003384 return false;
3385}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003386
Douglas Gregore94866f2009-06-12 21:21:02 +00003387/// \brief Check the non-type template arguments of a class template
3388/// partial specialization according to C++ [temp.class.spec]p9.
3389///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003390/// \param TemplateParams the template parameters of the primary class
3391/// template.
3392///
3393/// \param TemplateArg the template arguments of the class template
3394/// partial specialization.
3395///
3396/// \param MirrorsPrimaryTemplate will be set true if the class
3397/// template partial specialization arguments are identical to the
3398/// implicit template arguments of the primary template. This is not
3399/// necessarily an error (C++0x), and it is left to the caller to diagnose
3400/// this condition when it is an error.
3401///
Douglas Gregore94866f2009-06-12 21:21:02 +00003402/// \returns true if there was an error, false otherwise.
3403bool Sema::CheckClassTemplatePartialSpecializationArgs(
3404 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00003405 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003406 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003407 // FIXME: the interface to this function will have to change to
3408 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003409 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003410
Anders Carlssonfb250522009-06-23 01:26:57 +00003411 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00003412
Douglas Gregore94866f2009-06-12 21:21:02 +00003413 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003414 // Determine whether the template argument list of the partial
3415 // specialization is identical to the implicit argument list of
3416 // the primary template. The caller may need to diagnostic this as
3417 // an error per C++ [temp.class.spec]p9b3.
3418 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003419 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003420 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3421 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003422 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003423 MirrorsPrimaryTemplate = false;
3424 } else if (TemplateTemplateParmDecl *TTP
3425 = dyn_cast<TemplateTemplateParmDecl>(
3426 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003427 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003428 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003429 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003430 if (!ArgDecl ||
3431 ArgDecl->getIndex() != TTP->getIndex() ||
3432 ArgDecl->getDepth() != TTP->getDepth())
3433 MirrorsPrimaryTemplate = false;
3434 }
3435 }
3436
Mike Stump1eb44332009-09-09 15:08:12 +00003437 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003438 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003439 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003440 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003441 }
3442
Anders Carlsson6360be72009-06-13 18:20:51 +00003443 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003444 if (!ArgExpr) {
3445 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003446 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003447 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003448
3449 // C++ [temp.class.spec]p8:
3450 // A non-type argument is non-specialized if it is the name of a
3451 // non-type parameter. All other non-type arguments are
3452 // specialized.
3453 //
3454 // Below, we check the two conditions that only apply to
3455 // specialized non-type arguments, so skip any non-specialized
3456 // arguments.
3457 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003458 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003459 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003460 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003461 (Param->getIndex() != NTTP->getIndex() ||
3462 Param->getDepth() != NTTP->getDepth()))
3463 MirrorsPrimaryTemplate = false;
3464
Douglas Gregore94866f2009-06-12 21:21:02 +00003465 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003466 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003467
3468 // C++ [temp.class.spec]p9:
3469 // Within the argument list of a class template partial
3470 // specialization, the following restrictions apply:
3471 // -- A partially specialized non-type argument expression
3472 // shall not involve a template parameter of the partial
3473 // specialization except when the argument expression is a
3474 // simple identifier.
3475 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003476 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003477 diag::err_dependent_non_type_arg_in_partial_spec)
3478 << ArgExpr->getSourceRange();
3479 return true;
3480 }
3481
3482 // -- The type of a template parameter corresponding to a
3483 // specialized non-type argument shall not be dependent on a
3484 // parameter of the specialization.
3485 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003486 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003487 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3488 << Param->getType()
3489 << ArgExpr->getSourceRange();
3490 Diag(Param->getLocation(), diag::note_template_param_here);
3491 return true;
3492 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003493
3494 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003495 }
3496
3497 return false;
3498}
3499
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003500/// \brief Retrieve the previous declaration of the given declaration.
3501static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3502 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3503 return VD->getPreviousDeclaration();
3504 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3505 return FD->getPreviousDeclaration();
3506 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3507 return TD->getPreviousDeclaration();
3508 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3509 return TD->getPreviousDeclaration();
3510 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3511 return FTD->getPreviousDeclaration();
3512 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3513 return CTD->getPreviousDeclaration();
3514 return 0;
3515}
3516
Douglas Gregor212e81c2009-03-25 00:13:59 +00003517Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003518Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3519 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00003520 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003521 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003522 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00003523 SourceLocation TemplateNameLoc,
3524 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00003525 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00003526 SourceLocation RAngleLoc,
3527 AttributeList *Attr,
3528 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003529 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00003530
Douglas Gregorcc636682009-02-17 23:15:12 +00003531 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00003532 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003533 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00003534 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3535
3536 if (!ClassTemplate) {
3537 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3538 << (Name.getAsTemplateDecl() &&
3539 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3540 return true;
3541 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003542
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003543 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003544 bool isPartialSpecialization = false;
3545
Douglas Gregor88b70942009-02-25 22:02:03 +00003546 // Check the validity of the template headers that introduce this
3547 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003548 // FIXME: We probably shouldn't complain about these headers for
3549 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00003550 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00003551 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3552 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003553 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00003554 TUK == TUK_Friend,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003555 isExplicitSpecialization);
Douglas Gregor05396e22009-08-25 17:23:04 +00003556 if (TemplateParams && TemplateParams->size() > 0) {
3557 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003558
Douglas Gregor05396e22009-08-25 17:23:04 +00003559 // C++ [temp.class.spec]p10:
3560 // The template parameter list of a specialization shall not
3561 // contain default template argument values.
3562 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3563 Decl *Param = TemplateParams->getParam(I);
3564 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3565 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003566 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003567 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00003568 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003569 }
3570 } else if (NonTypeTemplateParmDecl *NTTP
3571 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3572 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003573 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003574 diag::err_default_arg_in_partial_spec)
3575 << DefArg->getSourceRange();
3576 NTTP->setDefaultArgument(0);
3577 DefArg->Destroy(Context);
3578 }
3579 } else {
3580 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003581 if (TTP->hasDefaultArgument()) {
3582 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003583 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003584 << TTP->getDefaultArgument().getSourceRange();
3585 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003586 }
3587 }
3588 }
Douglas Gregora735b202009-10-13 14:39:41 +00003589 } else if (TemplateParams) {
3590 if (TUK == TUK_Friend)
3591 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00003592 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00003593 SourceRange(TemplateParams->getTemplateLoc(),
3594 TemplateParams->getRAngleLoc()))
3595 << SourceRange(LAngleLoc, RAngleLoc);
3596 else
3597 isExplicitSpecialization = true;
3598 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003599 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00003600 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003601 isExplicitSpecialization = true;
3602 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003603
Douglas Gregorcc636682009-02-17 23:15:12 +00003604 // Check that the specialization uses the same tag kind as the
3605 // original template.
3606 TagDecl::TagKind Kind;
3607 switch (TagSpec) {
3608 default: assert(0 && "Unknown tag type!");
3609 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3610 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3611 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3612 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003613 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003614 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003615 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003616 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003617 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00003618 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003619 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003620 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003621 diag::note_previous_use);
3622 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3623 }
3624
Douglas Gregor40808ce2009-03-09 23:48:35 +00003625 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00003626 TemplateArgumentListInfo TemplateArgs;
3627 TemplateArgs.setLAngleLoc(LAngleLoc);
3628 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00003629 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003630
Douglas Gregorcc636682009-02-17 23:15:12 +00003631 // Check that the template argument list is well-formed for this
3632 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003633 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3634 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00003635 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3636 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003637 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003638
Mike Stump1eb44332009-09-09 15:08:12 +00003639 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003640 ClassTemplate->getTemplateParameters()->size()) &&
3641 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003642
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003643 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003644 // corresponds to these arguments.
3645 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003646 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003647 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003648 if (CheckClassTemplatePartialSpecializationArgs(
3649 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003650 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003651 return true;
3652
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003653 if (MirrorsPrimaryTemplate) {
3654 // C++ [temp.class.spec]p9b3:
3655 //
Mike Stump1eb44332009-09-09 15:08:12 +00003656 // -- The argument list of the specialization shall not be identical
3657 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003658 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003659 << (TUK == TUK_Definition)
Douglas Gregor849b2432010-03-31 17:46:05 +00003660 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003661 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003662 ClassTemplate->getIdentifier(),
3663 TemplateNameLoc,
3664 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003665 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003666 AS_none);
3667 }
3668
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003669 // FIXME: Diagnose friend partial specializations
3670
Douglas Gregorde090962010-02-09 00:37:32 +00003671 if (!Name.isDependent() &&
3672 !TemplateSpecializationType::anyDependentTemplateArguments(
3673 TemplateArgs.getArgumentArray(),
3674 TemplateArgs.size())) {
3675 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3676 << ClassTemplate->getDeclName();
3677 isPartialSpecialization = false;
3678 } else {
3679 // FIXME: Template parameter list matters, too
3680 ClassTemplatePartialSpecializationDecl::Profile(ID,
3681 Converted.getFlatArguments(),
3682 Converted.flatSize(),
3683 Context);
3684 }
3685 }
3686
3687 if (!isPartialSpecialization)
Anders Carlsson1c5976e2009-06-05 03:43:12 +00003688 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003689 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003690 Converted.flatSize(),
3691 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00003692 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003693 ClassTemplateSpecializationDecl *PrevDecl = 0;
3694
3695 if (isPartialSpecialization)
3696 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00003697 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003698 InsertPos);
3699 else
3700 PrevDecl
3701 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003702
3703 ClassTemplateSpecializationDecl *Specialization = 0;
3704
Douglas Gregor88b70942009-02-25 22:02:03 +00003705 // Check whether we can declare a class template specialization in
3706 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003707 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003708 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003709 TemplateNameLoc,
3710 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003711 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003712
Douglas Gregorb88e8882009-07-30 17:40:51 +00003713 // The canonical type
3714 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003715 if (PrevDecl &&
3716 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00003717 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003718 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003719 // arguments was referenced but not declared, or we're only
3720 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003721 // declaration node as our own, updating its source location to
3722 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003723 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003724 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003725 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003726 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003727 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003728 // Build the canonical type that describes the converted template
3729 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00003730 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3731 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb88e8882009-07-30 17:40:51 +00003732 Converted.getFlatArguments(),
3733 Converted.flatSize());
3734
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003735 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003736 ClassTemplatePartialSpecializationDecl *PrevPartial
3737 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00003738 ClassTemplatePartialSpecializationDecl *Partial
3739 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003740 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003741 TemplateNameLoc,
3742 TemplateParams,
3743 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003744 Converted,
John McCalld5532b62009-11-23 01:53:49 +00003745 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00003746 CanonType,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003747 PrevPartial);
John McCallb6217662010-03-15 10:12:16 +00003748 SetNestedNameSpecifier(Partial, SS);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003749
3750 if (PrevPartial) {
3751 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3752 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3753 } else {
3754 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3755 }
3756 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003757
Douglas Gregored9c0f92009-10-29 00:04:11 +00003758 // If we are providing an explicit specialization of a member class
3759 // template specialization, make a note of that.
3760 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3761 PrevPartial->setMemberSpecialization();
3762
Douglas Gregor031a5882009-06-13 00:26:55 +00003763 // Check that all of the template parameters of the class template
3764 // partial specialization are deducible from the template
3765 // arguments. If not, this class template partial specialization
3766 // will never be used.
3767 llvm::SmallVector<bool, 8> DeducibleParams;
3768 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003769 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003770 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003771 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003772 unsigned NumNonDeducible = 0;
3773 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3774 if (!DeducibleParams[I])
3775 ++NumNonDeducible;
3776
3777 if (NumNonDeducible) {
3778 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3779 << (NumNonDeducible > 1)
3780 << SourceRange(TemplateNameLoc, RAngleLoc);
3781 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3782 if (!DeducibleParams[I]) {
3783 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3784 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003785 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003786 diag::note_partial_spec_unused_parameter)
3787 << Param->getDeclName();
3788 else
Mike Stump1eb44332009-09-09 15:08:12 +00003789 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003790 diag::note_partial_spec_unused_parameter)
3791 << std::string("<anonymous>");
3792 }
3793 }
3794 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003795 } else {
3796 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003797 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003798 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00003799 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorcc636682009-02-17 23:15:12 +00003800 ClassTemplate->getDeclContext(),
3801 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003802 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003803 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003804 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00003805 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregorcc636682009-02-17 23:15:12 +00003806
3807 if (PrevDecl) {
3808 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3809 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3810 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003811 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00003812 InsertPos);
3813 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00003814
3815 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003816 }
3817
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003818 // C++ [temp.expl.spec]p6:
3819 // If a template, a member template or the member of a class template is
3820 // explicitly specialized then that specialization shall be declared
3821 // before the first use of that specialization that would cause an implicit
3822 // instantiation to take place, in every translation unit in which such a
3823 // use occurs; no diagnostic is required.
3824 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003825 bool Okay = false;
3826 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3827 // Is there any previous explicit specialization declaration?
3828 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3829 Okay = true;
3830 break;
3831 }
3832 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003833
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003834 if (!Okay) {
3835 SourceRange Range(TemplateNameLoc, RAngleLoc);
3836 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3837 << Context.getTypeDeclType(Specialization) << Range;
3838
3839 Diag(PrevDecl->getPointOfInstantiation(),
3840 diag::note_instantiation_required_here)
3841 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003842 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003843 return true;
3844 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003845 }
3846
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003847 // If this is not a friend, note that this is an explicit specialization.
3848 if (TUK != TUK_Friend)
3849 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003850
3851 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003852 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00003853 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003854 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003855 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003856 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003857 Diag(Def->getLocation(), diag::note_previous_definition);
3858 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003859 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003860 }
3861 }
3862
Douglas Gregorfc705b82009-02-26 22:19:44 +00003863 // Build the fully-sugared type for this class template
3864 // specialization as the user wrote in the specialization
3865 // itself. This means that we'll pretty-print the type retrieved
3866 // from the specialization's declaration the way that the user
3867 // actually wrote the specialization, rather than formatting the
3868 // name based on the "canonical" representation used to store the
3869 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00003870 TypeSourceInfo *WrittenTy
3871 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3872 TemplateArgs, CanonType);
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003873 if (TUK != TUK_Friend)
3874 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003875 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00003876
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003877 // C++ [temp.expl.spec]p9:
3878 // A template explicit specialization is in the scope of the
3879 // namespace in which the template was defined.
3880 //
3881 // We actually implement this paragraph where we set the semantic
3882 // context (in the creation of the ClassTemplateSpecializationDecl),
3883 // but we also maintain the lexical context where the actual
3884 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00003885 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003886
Douglas Gregorcc636682009-02-17 23:15:12 +00003887 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003888 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00003889 Specialization->startDefinition();
3890
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003891 if (TUK == TUK_Friend) {
3892 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3893 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00003894 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003895 /*FIXME:*/KWLoc);
3896 Friend->setAccess(AS_public);
3897 CurContext->addDecl(Friend);
3898 } else {
3899 // Add the specialization into its lexical context, so that it can
3900 // be seen when iterating through the list of declarations in that
3901 // context. However, specializations are not found by name lookup.
3902 CurContext->addDecl(Specialization);
3903 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003904 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003905}
Douglas Gregord57959a2009-03-27 23:10:48 +00003906
Mike Stump1eb44332009-09-09 15:08:12 +00003907Sema::DeclPtrTy
3908Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00003909 MultiTemplateParamsArg TemplateParameterLists,
3910 Declarator &D) {
3911 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3912}
3913
Mike Stump1eb44332009-09-09 15:08:12 +00003914Sema::DeclPtrTy
3915Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003916 MultiTemplateParamsArg TemplateParameterLists,
3917 Declarator &D) {
3918 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3919 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3920 "Not a function declarator!");
3921 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00003922
Douglas Gregor52591bf2009-06-24 00:54:41 +00003923 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00003924 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00003925 }
Mike Stump1eb44332009-09-09 15:08:12 +00003926
Douglas Gregor52591bf2009-06-24 00:54:41 +00003927 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003928
3929 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003930 move(TemplateParameterLists),
3931 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003932 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003933 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00003934 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00003935 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003936 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3937 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00003938 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00003939}
3940
John McCall75042392010-02-11 01:33:53 +00003941/// \brief Strips various properties off an implicit instantiation
3942/// that has just been explicitly specialized.
3943static void StripImplicitInstantiation(NamedDecl *D) {
3944 D->invalidateAttrs();
3945
3946 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3947 FD->setInlineSpecified(false);
3948 }
3949}
3950
Douglas Gregor454885e2009-10-15 15:54:05 +00003951/// \brief Diagnose cases where we have an explicit template specialization
3952/// before/after an explicit template instantiation, producing diagnostics
3953/// for those cases where they are required and determining whether the
3954/// new specialization/instantiation will have any effect.
3955///
Douglas Gregor454885e2009-10-15 15:54:05 +00003956/// \param NewLoc the location of the new explicit specialization or
3957/// instantiation.
3958///
3959/// \param NewTSK the kind of the new explicit specialization or instantiation.
3960///
3961/// \param PrevDecl the previous declaration of the entity.
3962///
3963/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3964///
3965/// \param PrevPointOfInstantiation if valid, indicates where the previus
3966/// declaration was instantiated (either implicitly or explicitly).
3967///
3968/// \param SuppressNew will be set to true to indicate that the new
3969/// specialization or instantiation has no effect and should be ignored.
3970///
3971/// \returns true if there was an error that should prevent the introduction of
3972/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00003973bool
3974Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3975 TemplateSpecializationKind NewTSK,
3976 NamedDecl *PrevDecl,
3977 TemplateSpecializationKind PrevTSK,
3978 SourceLocation PrevPointOfInstantiation,
3979 bool &SuppressNew) {
Douglas Gregor454885e2009-10-15 15:54:05 +00003980 SuppressNew = false;
3981
3982 switch (NewTSK) {
3983 case TSK_Undeclared:
3984 case TSK_ImplicitInstantiation:
3985 assert(false && "Don't check implicit instantiations here");
3986 return false;
3987
3988 case TSK_ExplicitSpecialization:
3989 switch (PrevTSK) {
3990 case TSK_Undeclared:
3991 case TSK_ExplicitSpecialization:
3992 // Okay, we're just specializing something that is either already
3993 // explicitly specialized or has merely been mentioned without any
3994 // instantiation.
3995 return false;
3996
3997 case TSK_ImplicitInstantiation:
3998 if (PrevPointOfInstantiation.isInvalid()) {
3999 // The declaration itself has not actually been instantiated, so it is
4000 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00004001 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00004002 return false;
4003 }
4004 // Fall through
4005
4006 case TSK_ExplicitInstantiationDeclaration:
4007 case TSK_ExplicitInstantiationDefinition:
4008 assert((PrevTSK == TSK_ImplicitInstantiation ||
4009 PrevPointOfInstantiation.isValid()) &&
4010 "Explicit instantiation without point of instantiation?");
4011
4012 // C++ [temp.expl.spec]p6:
4013 // If a template, a member template or the member of a class template
4014 // is explicitly specialized then that specialization shall be declared
4015 // before the first use of that specialization that would cause an
4016 // implicit instantiation to take place, in every translation unit in
4017 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004018 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4019 // Is there any previous explicit specialization declaration?
4020 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4021 return false;
4022 }
4023
Douglas Gregor0d035142009-10-27 18:42:08 +00004024 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00004025 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004026 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00004027 << (PrevTSK != TSK_ImplicitInstantiation);
4028
4029 return true;
4030 }
4031 break;
4032
4033 case TSK_ExplicitInstantiationDeclaration:
4034 switch (PrevTSK) {
4035 case TSK_ExplicitInstantiationDeclaration:
4036 // This explicit instantiation declaration is redundant (that's okay).
4037 SuppressNew = true;
4038 return false;
4039
4040 case TSK_Undeclared:
4041 case TSK_ImplicitInstantiation:
4042 // We're explicitly instantiating something that may have already been
4043 // implicitly instantiated; that's fine.
4044 return false;
4045
4046 case TSK_ExplicitSpecialization:
4047 // C++0x [temp.explicit]p4:
4048 // For a given set of template parameters, if an explicit instantiation
4049 // of a template appears after a declaration of an explicit
4050 // specialization for that template, the explicit instantiation has no
4051 // effect.
John McCalle97c32f2010-03-02 23:09:38 +00004052 SuppressNew = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004053 return false;
4054
4055 case TSK_ExplicitInstantiationDefinition:
4056 // C++0x [temp.explicit]p10:
4057 // If an entity is the subject of both an explicit instantiation
4058 // declaration and an explicit instantiation definition in the same
4059 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00004060 Diag(NewLoc,
4061 diag::err_explicit_instantiation_declaration_after_definition);
4062 Diag(PrevPointOfInstantiation,
4063 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00004064 assert(PrevPointOfInstantiation.isValid() &&
4065 "Explicit instantiation without point of instantiation?");
4066 SuppressNew = true;
4067 return false;
4068 }
4069 break;
4070
4071 case TSK_ExplicitInstantiationDefinition:
4072 switch (PrevTSK) {
4073 case TSK_Undeclared:
4074 case TSK_ImplicitInstantiation:
4075 // We're explicitly instantiating something that may have already been
4076 // implicitly instantiated; that's fine.
4077 return false;
4078
4079 case TSK_ExplicitSpecialization:
4080 // C++ DR 259, C++0x [temp.explicit]p4:
4081 // For a given set of template parameters, if an explicit
4082 // instantiation of a template appears after a declaration of
4083 // an explicit specialization for that template, the explicit
4084 // instantiation has no effect.
4085 //
4086 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00004087 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00004088 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00004089 if (!getLangOptions().CPlusPlus0x) {
4090 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00004091 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004092 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00004093 diag::note_previous_template_specialization);
4094 }
4095 SuppressNew = true;
4096 return false;
4097
4098 case TSK_ExplicitInstantiationDeclaration:
4099 // We're explicity instantiating a definition for something for which we
4100 // were previously asked to suppress instantiations. That's fine.
4101 return false;
4102
4103 case TSK_ExplicitInstantiationDefinition:
4104 // C++0x [temp.spec]p5:
4105 // For a given template and a given set of template-arguments,
4106 // - an explicit instantiation definition shall appear at most once
4107 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00004108 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00004109 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004110 Diag(PrevPointOfInstantiation,
4111 diag::note_previous_explicit_instantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00004112 SuppressNew = true;
4113 return false;
4114 }
4115 break;
4116 }
4117
4118 assert(false && "Missing specialization/instantiation case?");
4119
4120 return false;
4121}
4122
John McCallaf2094e2010-04-08 09:05:18 +00004123/// \brief Perform semantic analysis for the given dependent function
4124/// template specialization. The only possible way to get a dependent
4125/// function template specialization is with a friend declaration,
4126/// like so:
4127///
4128/// template <class T> void foo(T);
4129/// template <class T> class A {
4130/// friend void foo<>(T);
4131/// };
4132///
4133/// There really isn't any useful analysis we can do here, so we
4134/// just store the information.
4135bool
4136Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4137 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4138 LookupResult &Previous) {
4139 // Remove anything from Previous that isn't a function template in
4140 // the correct context.
4141 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4142 LookupResult::Filter F = Previous.makeFilter();
4143 while (F.hasNext()) {
4144 NamedDecl *D = F.next()->getUnderlyingDecl();
4145 if (!isa<FunctionTemplateDecl>(D) ||
4146 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4147 F.erase();
4148 }
4149 F.done();
4150
4151 // Should this be diagnosed here?
4152 if (Previous.empty()) return true;
4153
4154 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4155 ExplicitTemplateArgs);
4156 return false;
4157}
4158
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004159/// \brief Perform semantic analysis for the given function template
4160/// specialization.
4161///
4162/// This routine performs all of the semantic analysis required for an
4163/// explicit function template specialization. On successful completion,
4164/// the function declaration \p FD will become a function template
4165/// specialization.
4166///
4167/// \param FD the function declaration, which will be updated to become a
4168/// function template specialization.
4169///
4170/// \param HasExplicitTemplateArgs whether any template arguments were
4171/// explicitly provided.
4172///
4173/// \param LAngleLoc the location of the left angle bracket ('<'), if
4174/// template arguments were explicitly provided.
4175///
4176/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4177/// if any.
4178///
4179/// \param NumExplicitTemplateArgs the number of explicitly-provided template
4180/// arguments. This number may be zero even when HasExplicitTemplateArgs is
4181/// true as in, e.g., \c void sort<>(char*, char*);
4182///
4183/// \param RAngleLoc the location of the right angle bracket ('>'), if
4184/// template arguments were explicitly provided.
4185///
4186/// \param PrevDecl the set of declarations that
4187bool
4188Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004189 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004190 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004191 // The set of function template specializations that could match this
4192 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004193 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004194
4195 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall68263142009-11-18 22:49:29 +00004196 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4197 I != E; ++I) {
4198 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4199 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004200 // Only consider templates found within the same semantic lookup scope as
4201 // FD.
4202 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4203 continue;
4204
4205 // C++ [temp.expl.spec]p11:
4206 // A trailing template-argument can be left unspecified in the
4207 // template-id naming an explicit function template specialization
4208 // provided it can be deduced from the function argument type.
4209 // Perform template argument deduction to determine whether we may be
4210 // specializing this template.
4211 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004212 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004213 FunctionDecl *Specialization = 0;
4214 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004215 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004216 FD->getType(),
4217 Specialization,
4218 Info)) {
4219 // FIXME: Template argument deduction failed; record why it failed, so
4220 // that we can provide nifty diagnostics.
4221 (void)TDK;
4222 continue;
4223 }
4224
4225 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004226 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004227 }
4228 }
4229
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004230 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004231 UnresolvedSetIterator Result
4232 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4233 TPOC_Other, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004234 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004235 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004236 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004237 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004238 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004239 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004240 return true;
John McCallc373d482010-01-27 01:50:18 +00004241
4242 // Ignore access information; it doesn't figure into redeclaration checking.
4243 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorc42b6522010-04-09 21:02:29 +00004244 Specialization->setLocation(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004245
4246 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004247 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004248
4249 // If this is a friend declaration, then we're not really declaring
4250 // an explicit specialization.
4251 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004252
Douglas Gregord5cb8762009-10-07 00:13:32 +00004253 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004254 if (!isFriend &&
4255 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004256 Specialization->getPrimaryTemplate(),
4257 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004258 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004259 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004260
4261 // C++ [temp.expl.spec]p6:
4262 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004263 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004264 // before the first use of that specialization that would cause an implicit
4265 // instantiation to take place, in every translation unit in which such a
4266 // use occurs; no diagnostic is required.
4267 FunctionTemplateSpecializationInfo *SpecInfo
4268 = Specialization->getTemplateSpecializationInfo();
4269 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004270
4271 bool SuppressNew = false;
John McCall7ad650f2010-03-24 07:46:06 +00004272 if (!isFriend &&
4273 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004274 TSK_ExplicitSpecialization,
4275 Specialization,
4276 SpecInfo->getTemplateSpecializationKind(),
4277 SpecInfo->getPointOfInstantiation(),
4278 SuppressNew))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004279 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004280
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004281 // Mark the prior declaration as an explicit specialization, so that later
4282 // clients know that this is an explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004283 if (!isFriend)
4284 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004285
4286 // Turn the given function declaration into a function template
4287 // specialization, with the template arguments from the previous
4288 // specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00004289 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004290 new (Context) TemplateArgumentList(
4291 *Specialization->getTemplateSpecializationArgs()),
4292 /*InsertPos=*/0,
John McCall7ad650f2010-03-24 07:46:06 +00004293 SpecInfo->getTemplateSpecializationKind());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004294
4295 // The "previous declaration" for this function template specialization is
4296 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004297 Previous.clear();
4298 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004299 return false;
4300}
4301
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004302/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004303/// specialization.
4304///
4305/// This routine performs all of the semantic analysis required for an
4306/// explicit member function specialization. On successful completion,
4307/// the function declaration \p FD will become a member function
4308/// specialization.
4309///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004310/// \param Member the member declaration, which will be updated to become a
4311/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004312///
John McCall68263142009-11-18 22:49:29 +00004313/// \param Previous the set of declarations, one of which may be specialized
4314/// by this function specialization; the set will be modified to contain the
4315/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004316bool
John McCall68263142009-11-18 22:49:29 +00004317Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004318 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00004319
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004320 // Try to find the member we are instantiating.
4321 NamedDecl *Instantiation = 0;
4322 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004323 MemberSpecializationInfo *MSInfo = 0;
4324
John McCall68263142009-11-18 22:49:29 +00004325 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004326 // Nowhere to look anyway.
4327 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004328 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4329 I != E; ++I) {
4330 NamedDecl *D = (*I)->getUnderlyingDecl();
4331 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004332 if (Context.hasSameType(Function->getType(), Method->getType())) {
4333 Instantiation = Method;
4334 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004335 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004336 break;
4337 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004338 }
4339 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004340 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004341 VarDecl *PrevVar;
4342 if (Previous.isSingleResult() &&
4343 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004344 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004345 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004346 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004347 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004348 }
4349 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004350 CXXRecordDecl *PrevRecord;
4351 if (Previous.isSingleResult() &&
4352 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4353 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004354 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004355 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004356 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004357 }
4358
4359 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004360 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004361 // specializations are always out-of-line, the caller will complain about
4362 // this mismatch later.
4363 return false;
4364 }
John McCall77e8b112010-04-13 20:37:33 +00004365
4366 // If this is a friend, just bail out here before we start turning
4367 // things into explicit specializations.
4368 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4369 // Preserve instantiation information.
4370 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4371 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4372 cast<CXXMethodDecl>(InstantiatedFrom),
4373 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4374 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4375 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4376 cast<CXXRecordDecl>(InstantiatedFrom),
4377 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4378 }
4379
4380 Previous.clear();
4381 Previous.addDecl(Instantiation);
4382 return false;
4383 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004384
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004385 // Make sure that this is a specialization of a member.
4386 if (!InstantiatedFrom) {
4387 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4388 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004389 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4390 return true;
4391 }
4392
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004393 // C++ [temp.expl.spec]p6:
4394 // If a template, a member template or the member of a class template is
4395 // explicitly specialized then that spe- cialization shall be declared
4396 // before the first use of that specialization that would cause an implicit
4397 // instantiation to take place, in every translation unit in which such a
4398 // use occurs; no diagnostic is required.
4399 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004400
4401 bool SuppressNew = false;
4402 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4403 TSK_ExplicitSpecialization,
4404 Instantiation,
4405 MSInfo->getTemplateSpecializationKind(),
4406 MSInfo->getPointOfInstantiation(),
4407 SuppressNew))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004408 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004409
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004410 // Check the scope of this explicit specialization.
4411 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004412 InstantiatedFrom,
4413 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004414 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004415 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004416
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004417 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004418 // the original declaration to note that it is an explicit specialization
4419 // (if it was previously an implicit instantiation). This latter step
4420 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004421 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004422 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4423 if (InstantiationFunction->getTemplateSpecializationKind() ==
4424 TSK_ImplicitInstantiation) {
4425 InstantiationFunction->setTemplateSpecializationKind(
4426 TSK_ExplicitSpecialization);
4427 InstantiationFunction->setLocation(Member->getLocation());
4428 }
4429
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004430 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4431 cast<CXXMethodDecl>(InstantiatedFrom),
4432 TSK_ExplicitSpecialization);
4433 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004434 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4435 if (InstantiationVar->getTemplateSpecializationKind() ==
4436 TSK_ImplicitInstantiation) {
4437 InstantiationVar->setTemplateSpecializationKind(
4438 TSK_ExplicitSpecialization);
4439 InstantiationVar->setLocation(Member->getLocation());
4440 }
4441
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004442 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4443 cast<VarDecl>(InstantiatedFrom),
4444 TSK_ExplicitSpecialization);
4445 } else {
4446 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004447 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4448 if (InstantiationClass->getTemplateSpecializationKind() ==
4449 TSK_ImplicitInstantiation) {
4450 InstantiationClass->setTemplateSpecializationKind(
4451 TSK_ExplicitSpecialization);
4452 InstantiationClass->setLocation(Member->getLocation());
4453 }
4454
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004455 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004456 cast<CXXRecordDecl>(InstantiatedFrom),
4457 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004458 }
4459
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004460 // Save the caller the trouble of having to figure out which declaration
4461 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004462 Previous.clear();
4463 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004464 return false;
4465}
4466
Douglas Gregor558c0322009-10-14 23:41:34 +00004467/// \brief Check the scope of an explicit instantiation.
4468static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4469 SourceLocation InstLoc,
4470 bool WasQualifiedName) {
4471 DeclContext *ExpectedContext
4472 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4473 DeclContext *CurContext = S.CurContext->getLookupContext();
4474
4475 // C++0x [temp.explicit]p2:
4476 // An explicit instantiation shall appear in an enclosing namespace of its
4477 // template.
4478 //
4479 // This is DR275, which we do not retroactively apply to C++98/03.
4480 if (S.getLangOptions().CPlusPlus0x &&
4481 !CurContext->Encloses(ExpectedContext)) {
4482 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4483 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4484 << D << NS;
4485 else
4486 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4487 << D;
4488 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4489 return;
4490 }
4491
4492 // C++0x [temp.explicit]p2:
4493 // If the name declared in the explicit instantiation is an unqualified
4494 // name, the explicit instantiation shall appear in the namespace where
4495 // its template is declared or, if that namespace is inline (7.3.1), any
4496 // namespace from its enclosing namespace set.
4497 if (WasQualifiedName)
4498 return;
4499
4500 if (CurContext->Equals(ExpectedContext))
4501 return;
4502
4503 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4504 << D << ExpectedContext;
4505 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4506}
4507
4508/// \brief Determine whether the given scope specifier has a template-id in it.
4509static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4510 if (!SS.isSet())
4511 return false;
4512
4513 // C++0x [temp.explicit]p2:
4514 // If the explicit instantiation is for a member function, a member class
4515 // or a static data member of a class template specialization, the name of
4516 // the class template specialization in the qualified-id for the member
4517 // name shall be a simple-template-id.
4518 //
4519 // C++98 has the same restriction, just worded differently.
4520 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4521 NNS; NNS = NNS->getPrefix())
4522 if (Type *T = NNS->getAsType())
4523 if (isa<TemplateSpecializationType>(T))
4524 return true;
4525
4526 return false;
4527}
4528
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004529// Explicit instantiation of a class template specialization
Douglas Gregor45f96552009-09-04 06:33:52 +00004530// FIXME: Implement extern template semantics
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004531Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004532Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004533 SourceLocation ExternLoc,
4534 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004535 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004536 SourceLocation KWLoc,
4537 const CXXScopeSpec &SS,
4538 TemplateTy TemplateD,
4539 SourceLocation TemplateNameLoc,
4540 SourceLocation LAngleLoc,
4541 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004542 SourceLocation RAngleLoc,
4543 AttributeList *Attr) {
4544 // Find the class template we're specializing
4545 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004546 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004547 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4548
4549 // Check that the specialization uses the same tag kind as the
4550 // original template.
4551 TagDecl::TagKind Kind;
4552 switch (TagSpec) {
4553 default: assert(0 && "Unknown tag type!");
4554 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4555 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4556 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4557 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004558 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004559 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004560 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004561 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004562 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004563 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004564 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004565 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004566 diag::note_previous_use);
4567 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4568 }
4569
Douglas Gregor558c0322009-10-14 23:41:34 +00004570 // C++0x [temp.explicit]p2:
4571 // There are two forms of explicit instantiation: an explicit instantiation
4572 // definition and an explicit instantiation declaration. An explicit
4573 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00004574 TemplateSpecializationKind TSK
4575 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4576 : TSK_ExplicitInstantiationDeclaration;
4577
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004578 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004579 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004580 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004581
4582 // Check that the template argument list is well-formed for this
4583 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00004584 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4585 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00004586 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4587 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004588 return true;
4589
Mike Stump1eb44332009-09-09 15:08:12 +00004590 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004591 ClassTemplate->getTemplateParameters()->size()) &&
4592 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004593
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004594 // Find the class template specialization declaration that
4595 // corresponds to these arguments.
4596 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00004597 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00004598 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00004599 Converted.flatSize(),
4600 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004601 void *InsertPos = 0;
4602 ClassTemplateSpecializationDecl *PrevDecl
4603 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4604
Douglas Gregord5cb8762009-10-07 00:13:32 +00004605 // C++0x [temp.explicit]p2:
4606 // [...] An explicit instantiation shall appear in an enclosing
4607 // namespace of its template. [...]
4608 //
4609 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004610 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4611 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00004612
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004613 ClassTemplateSpecializationDecl *Specialization = 0;
4614
Douglas Gregord78f5982009-11-25 06:01:46 +00004615 bool ReusedDecl = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004616 if (PrevDecl) {
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004617 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004618 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004619 PrevDecl,
4620 PrevDecl->getSpecializationKind(),
4621 PrevDecl->getPointOfInstantiation(),
4622 SuppressNew))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004623 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004624
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004625 if (SuppressNew)
Douglas Gregor52604ab2009-09-11 21:19:12 +00004626 return DeclPtrTy::make(PrevDecl);
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004627
Douglas Gregor52604ab2009-09-11 21:19:12 +00004628 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4629 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4630 // Since the only prior class template specialization with these
4631 // arguments was referenced but not declared, reuse that
4632 // declaration node as our own, updating its source location to
4633 // reflect our new declaration.
4634 Specialization = PrevDecl;
4635 Specialization->setLocation(TemplateNameLoc);
4636 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00004637 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00004638 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004639 }
Douglas Gregor52604ab2009-09-11 21:19:12 +00004640
4641 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004642 // Create a new class template specialization declaration node for
4643 // this explicit specialization.
4644 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00004645 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004646 ClassTemplate->getDeclContext(),
4647 TemplateNameLoc,
4648 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00004649 Converted, PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004650 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004651
Douglas Gregor52604ab2009-09-11 21:19:12 +00004652 if (PrevDecl) {
4653 // Remove the previous declaration from the folding set, since we want
4654 // to introduce a new declaration.
4655 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4656 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4657 }
4658
4659 // Insert the new specialization.
4660 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004661 }
4662
4663 // Build the fully-sugared type for this explicit instantiation as
4664 // the user wrote in the explicit instantiation itself. This means
4665 // that we'll pretty-print the type retrieved from the
4666 // specialization's declaration the way that the user actually wrote
4667 // the explicit instantiation, rather than formatting the name based
4668 // on the "canonical" representation used to store the template
4669 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004670 TypeSourceInfo *WrittenTy
4671 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4672 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004673 Context.getTypeDeclType(Specialization));
4674 Specialization->setTypeAsWritten(WrittenTy);
4675 TemplateArgsIn.release();
4676
Douglas Gregord78f5982009-11-25 06:01:46 +00004677 if (!ReusedDecl) {
4678 // Add the explicit instantiation into its lexical context. However,
4679 // since explicit instantiations are never found by name lookup, we
4680 // just put it into the declaration context directly.
4681 Specialization->setLexicalDeclContext(CurContext);
4682 CurContext->addDecl(Specialization);
4683 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004684
4685 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004686 // A definition of a class template or class member template
4687 // shall be in scope at the point of the explicit instantiation of
4688 // the class template or class member template.
4689 //
4690 // This check comes when we actually try to perform the
4691 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004692 ClassTemplateSpecializationDecl *Def
4693 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004694 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004695 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004696 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor0d035142009-10-27 18:42:08 +00004697
4698 // Instantiate the members of this class template specialization.
4699 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004700 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004701 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00004702 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4703
4704 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4705 // TSK_ExplicitInstantiationDefinition
4706 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4707 TSK == TSK_ExplicitInstantiationDefinition)
4708 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004709
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004710 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004711 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004712
4713 return DeclPtrTy::make(Specialization);
4714}
4715
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004716// Explicit instantiation of a member class of a class template.
4717Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004718Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004719 SourceLocation ExternLoc,
4720 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004721 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004722 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004723 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004724 IdentifierInfo *Name,
4725 SourceLocation NameLoc,
4726 AttributeList *Attr) {
4727
Douglas Gregor402abb52009-05-28 23:31:59 +00004728 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004729 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00004730 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004731 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00004732 MultiTemplateParamsArg(*this, 0, 0),
4733 Owned, IsDependent);
4734 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4735
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004736 if (!TagD)
4737 return true;
4738
4739 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4740 if (Tag->isEnum()) {
4741 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4742 << Context.getTypeDeclType(Tag);
4743 return true;
4744 }
4745
Douglas Gregord0c87372009-05-27 17:30:49 +00004746 if (Tag->isInvalidDecl())
4747 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004748
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004749 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4750 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4751 if (!Pattern) {
4752 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4753 << Context.getTypeDeclType(Record);
4754 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4755 return true;
4756 }
4757
Douglas Gregor558c0322009-10-14 23:41:34 +00004758 // C++0x [temp.explicit]p2:
4759 // If the explicit instantiation is for a class or member class, the
4760 // elaborated-type-specifier in the declaration shall include a
4761 // simple-template-id.
4762 //
4763 // C++98 has the same restriction, just worded differently.
4764 if (!ScopeSpecifierHasTemplateId(SS))
4765 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4766 << Record << SS.getRange();
4767
4768 // C++0x [temp.explicit]p2:
4769 // There are two forms of explicit instantiation: an explicit instantiation
4770 // definition and an explicit instantiation declaration. An explicit
4771 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004772 TemplateSpecializationKind TSK
4773 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4774 : TSK_ExplicitInstantiationDeclaration;
4775
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004776 // C++0x [temp.explicit]p2:
4777 // [...] An explicit instantiation shall appear in an enclosing
4778 // namespace of its template. [...]
4779 //
4780 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004781 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004782
4783 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004784 CXXRecordDecl *PrevDecl
4785 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00004786 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00004787 PrevDecl = Record;
4788 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004789 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4790 bool SuppressNew = false;
4791 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004792 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004793 PrevDecl,
4794 MSInfo->getTemplateSpecializationKind(),
4795 MSInfo->getPointOfInstantiation(),
4796 SuppressNew))
4797 return true;
4798 if (SuppressNew)
4799 return TagD;
4800 }
4801
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004802 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00004803 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004804 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004805 // C++ [temp.explicit]p3:
4806 // A definition of a member class of a class template shall be in scope
4807 // at the point of an explicit instantiation of the member class.
4808 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00004809 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004810 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004811 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4812 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004813 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4814 << Pattern;
4815 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004816 } else {
4817 if (InstantiateClass(NameLoc, Record, Def,
4818 getTemplateInstantiationArgs(Record),
4819 TSK))
4820 return true;
4821
Douglas Gregor952b0172010-02-11 01:04:33 +00004822 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00004823 if (!RecordDef)
4824 return true;
4825 }
4826 }
4827
4828 // Instantiate all of the members of the class.
4829 InstantiateClassMembers(NameLoc, RecordDef,
4830 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004831
Mike Stump390b4cc2009-05-16 07:39:55 +00004832 // FIXME: We don't have any representation for explicit instantiations of
4833 // member classes. Such a representation is not needed for compilation, but it
4834 // should be available for clients that want to see all of the declarations in
4835 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004836 return TagD;
4837}
4838
Douglas Gregord5a423b2009-09-25 18:43:00 +00004839Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4840 SourceLocation ExternLoc,
4841 SourceLocation TemplateLoc,
4842 Declarator &D) {
4843 // Explicit instantiations always require a name.
4844 DeclarationName Name = GetNameForDeclarator(D);
4845 if (!Name) {
4846 if (!D.isInvalidType())
4847 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4848 diag::err_explicit_instantiation_requires_name)
4849 << D.getDeclSpec().getSourceRange()
4850 << D.getSourceRange();
4851
4852 return true;
4853 }
4854
4855 // The scope passed in may not be a decl scope. Zip up the scope tree until
4856 // we find one that is.
4857 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4858 (S->getFlags() & Scope::TemplateParamScope) != 0)
4859 S = S->getParent();
4860
4861 // Determine the type of the declaration.
4862 QualType R = GetTypeForDeclarator(D, S, 0);
4863 if (R.isNull())
4864 return true;
4865
4866 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4867 // Cannot explicitly instantiate a typedef.
4868 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4869 << Name;
4870 return true;
4871 }
4872
Douglas Gregor663b5a02009-10-14 20:14:33 +00004873 // C++0x [temp.explicit]p1:
4874 // [...] An explicit instantiation of a function template shall not use the
4875 // inline or constexpr specifiers.
4876 // Presumably, this also applies to member functions of class templates as
4877 // well.
4878 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4879 Diag(D.getDeclSpec().getInlineSpecLoc(),
4880 diag::err_explicit_instantiation_inline)
Douglas Gregor849b2432010-03-31 17:46:05 +00004881 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00004882
4883 // FIXME: check for constexpr specifier.
4884
Douglas Gregor558c0322009-10-14 23:41:34 +00004885 // C++0x [temp.explicit]p2:
4886 // There are two forms of explicit instantiation: an explicit instantiation
4887 // definition and an explicit instantiation declaration. An explicit
4888 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00004889 TemplateSpecializationKind TSK
4890 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4891 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00004892
John McCalla24dc2e2009-11-17 02:14:36 +00004893 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4894 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004895
4896 if (!R->isFunctionType()) {
4897 // C++ [temp.explicit]p1:
4898 // A [...] static data member of a class template can be explicitly
4899 // instantiated from the member definition associated with its class
4900 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00004901 if (Previous.isAmbiguous())
4902 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004903
John McCall1bcee0a2009-12-02 08:25:40 +00004904 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004905 if (!Prev || !Prev->isStaticDataMember()) {
4906 // We expect to see a data data member here.
4907 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4908 << Name;
4909 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4910 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00004911 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004912 return true;
4913 }
4914
4915 if (!Prev->getInstantiatedFromStaticDataMember()) {
4916 // FIXME: Check for explicit specialization?
4917 Diag(D.getIdentifierLoc(),
4918 diag::err_explicit_instantiation_data_member_not_instantiated)
4919 << Prev;
4920 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4921 // FIXME: Can we provide a note showing where this was declared?
4922 return true;
4923 }
4924
Douglas Gregor558c0322009-10-14 23:41:34 +00004925 // C++0x [temp.explicit]p2:
4926 // If the explicit instantiation is for a member function, a member class
4927 // or a static data member of a class template specialization, the name of
4928 // the class template specialization in the qualified-id for the member
4929 // name shall be a simple-template-id.
4930 //
4931 // C++98 has the same restriction, just worded differently.
4932 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4933 Diag(D.getIdentifierLoc(),
4934 diag::err_explicit_instantiation_without_qualified_id)
4935 << Prev << D.getCXXScopeSpec().getRange();
4936
4937 // Check the scope of this explicit instantiation.
4938 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4939
Douglas Gregor454885e2009-10-15 15:54:05 +00004940 // Verify that it is okay to explicitly instantiate here.
4941 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4942 assert(MSInfo && "Missing static data member specialization info?");
4943 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004944 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00004945 MSInfo->getTemplateSpecializationKind(),
4946 MSInfo->getPointOfInstantiation(),
4947 SuppressNew))
4948 return true;
4949 if (SuppressNew)
4950 return DeclPtrTy();
4951
Douglas Gregord5a423b2009-09-25 18:43:00 +00004952 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004953 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004954 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004955 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4956 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004957
4958 // FIXME: Create an ExplicitInstantiation node?
4959 return DeclPtrTy();
4960 }
4961
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004962 // If the declarator is a template-id, translate the parser's template
4963 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00004964 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00004965 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004966 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4967 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00004968 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4969 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00004970 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4971 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00004972 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00004973 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00004974 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00004975 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00004976 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004977
Douglas Gregord5a423b2009-09-25 18:43:00 +00004978 // C++ [temp.explicit]p1:
4979 // A [...] function [...] can be explicitly instantiated from its template.
4980 // A member function [...] of a class template can be explicitly
4981 // instantiated from the member definition associated with its class
4982 // template.
John McCallc373d482010-01-27 01:50:18 +00004983 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004984 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4985 P != PEnd; ++P) {
4986 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00004987 if (!HasExplicitTemplateArgs) {
4988 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4989 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4990 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00004991
John McCallc373d482010-01-27 01:50:18 +00004992 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00004993 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
4994 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00004995 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00004996 }
4997 }
4998
4999 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5000 if (!FunTmpl)
5001 continue;
5002
John McCall5769d612010-02-08 23:07:23 +00005003 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005004 FunctionDecl *Specialization = 0;
5005 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00005006 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00005007 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00005008 R, Specialization, Info)) {
5009 // FIXME: Keep track of almost-matches?
5010 (void)TDK;
5011 continue;
5012 }
5013
John McCallc373d482010-01-27 01:50:18 +00005014 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005015 }
5016
5017 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005018 UnresolvedSetIterator Result
5019 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregord5a423b2009-09-25 18:43:00 +00005020 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005021 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5022 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5023 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00005024
John McCallc373d482010-01-27 01:50:18 +00005025 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00005026 return true;
John McCallc373d482010-01-27 01:50:18 +00005027
5028 // Ignore access control bits, we don't need them for redeclaration checking.
5029 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005030
Douglas Gregor0a897e32009-10-15 17:21:20 +00005031 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005032 Diag(D.getIdentifierLoc(),
5033 diag::err_explicit_instantiation_member_function_not_instantiated)
5034 << Specialization
5035 << (Specialization->getTemplateSpecializationKind() ==
5036 TSK_ExplicitSpecialization);
5037 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5038 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005039 }
Douglas Gregor558c0322009-10-14 23:41:34 +00005040
Douglas Gregor0a897e32009-10-15 17:21:20 +00005041 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00005042 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5043 PrevDecl = Specialization;
5044
Douglas Gregor0a897e32009-10-15 17:21:20 +00005045 if (PrevDecl) {
5046 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005047 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00005048 PrevDecl,
5049 PrevDecl->getTemplateSpecializationKind(),
5050 PrevDecl->getPointOfInstantiation(),
5051 SuppressNew))
5052 return true;
5053
5054 // FIXME: We may still want to build some representation of this
5055 // explicit specialization.
5056 if (SuppressNew)
5057 return DeclPtrTy();
5058 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00005059
5060 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00005061
5062 if (TSK == TSK_ExplicitInstantiationDefinition)
5063 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5064 false, /*DefinitionRequired=*/true);
Douglas Gregor0a897e32009-10-15 17:21:20 +00005065
Douglas Gregor558c0322009-10-14 23:41:34 +00005066 // C++0x [temp.explicit]p2:
5067 // If the explicit instantiation is for a member function, a member class
5068 // or a static data member of a class template specialization, the name of
5069 // the class template specialization in the qualified-id for the member
5070 // name shall be a simple-template-id.
5071 //
5072 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005073 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005074 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00005075 D.getCXXScopeSpec().isSet() &&
5076 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5077 Diag(D.getIdentifierLoc(),
5078 diag::err_explicit_instantiation_without_qualified_id)
5079 << Specialization << D.getCXXScopeSpec().getRange();
5080
5081 CheckExplicitInstantiationScope(*this,
5082 FunTmpl? (NamedDecl *)FunTmpl
5083 : Specialization->getInstantiatedFromMemberFunction(),
5084 D.getIdentifierLoc(),
5085 D.getCXXScopeSpec().isSet());
5086
Douglas Gregord5a423b2009-09-25 18:43:00 +00005087 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5088 return DeclPtrTy();
5089}
5090
Douglas Gregord57959a2009-03-27 23:10:48 +00005091Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00005092Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5093 const CXXScopeSpec &SS, IdentifierInfo *Name,
5094 SourceLocation TagLoc, SourceLocation NameLoc) {
5095 // This has to hold, because SS is expected to be defined.
5096 assert(Name && "Expected a name in a dependent tag");
5097
5098 NestedNameSpecifier *NNS
5099 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5100 if (!NNS)
5101 return true;
5102
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005103 ElaboratedTypeKeyword Keyword = ETK_None;
Douglas Gregor40336422010-03-31 22:19:08 +00005104 switch (TagDecl::getTagKindForTypeSpec(TagSpec)) {
5105 case TagDecl::TK_struct: Keyword = ETK_Struct; break;
5106 case TagDecl::TK_class: Keyword = ETK_Class; break;
5107 case TagDecl::TK_union: Keyword = ETK_Union; break;
5108 case TagDecl::TK_enum: Keyword = ETK_Enum; break;
5109 }
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005110 assert(Keyword != ETK_None && "Invalid tag kind!");
5111
Douglas Gregor40336422010-03-31 22:19:08 +00005112 return Context.getDependentNameType(Keyword, NNS, Name).getAsOpaquePtr();
John McCallc4e70192009-09-11 04:59:25 +00005113}
5114
5115Sema::TypeResult
Douglas Gregord57959a2009-03-27 23:10:48 +00005116Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5117 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005118 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00005119 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5120 if (!NNS)
5121 return true;
5122
5123 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00005124 if (T.isNull())
5125 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00005126 return T.getAsOpaquePtr();
5127}
5128
Douglas Gregor17343172009-04-01 00:28:59 +00005129Sema::TypeResult
5130Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5131 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005132 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005133 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00005134 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +00005135 const TemplateSpecializationType *TemplateId
John McCall183700f2009-09-21 23:43:11 +00005136 = T->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00005137 assert(TemplateId && "Expected a template specialization type");
5138
Douglas Gregor6946baf2009-09-02 13:05:45 +00005139 if (computeDeclContext(SS, false)) {
5140 // If we can compute a declaration context, then the "typename"
5141 // keyword was superfluous. Just build a QualifiedNameType to keep
5142 // track of the nested-name-specifier.
Mike Stump1eb44332009-09-09 15:08:12 +00005143
Douglas Gregor6946baf2009-09-02 13:05:45 +00005144 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
5145 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
5146 }
Mike Stump1eb44332009-09-09 15:08:12 +00005147
Douglas Gregor4a2023f2010-03-31 20:19:30 +00005148 return Context.getDependentNameType(ETK_Typename, NNS, TemplateId)
5149 .getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00005150}
5151
Douglas Gregord57959a2009-03-27 23:10:48 +00005152/// \brief Build the type that describes a C++ typename specifier,
5153/// e.g., "typename T::type".
5154QualType
5155Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
5156 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00005157 CXXRecordDecl *CurrentInstantiation = 0;
5158 if (NNS->isDependent()) {
5159 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00005160
Douglas Gregor42af25f2009-05-11 19:58:34 +00005161 // If the nested-name-specifier does not refer to the current
5162 // instantiation, then build a typename type.
5163 if (!CurrentInstantiation)
Douglas Gregor4a2023f2010-03-31 20:19:30 +00005164 return Context.getDependentNameType(ETK_Typename, NNS, &II);
Mike Stump1eb44332009-09-09 15:08:12 +00005165
Douglas Gregorde18d122009-09-02 13:12:51 +00005166 // The nested-name-specifier refers to the current instantiation, so the
5167 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump1eb44332009-09-09 15:08:12 +00005168 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorde18d122009-09-02 13:12:51 +00005169 // extraneous "typename" keywords, and we retroactively apply this DR to
5170 // C++03 code.
Douglas Gregor42af25f2009-05-11 19:58:34 +00005171 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005172
Douglas Gregor42af25f2009-05-11 19:58:34 +00005173 DeclContext *Ctx = 0;
5174
5175 if (CurrentInstantiation)
5176 Ctx = CurrentInstantiation;
5177 else {
5178 CXXScopeSpec SS;
5179 SS.setScopeRep(NNS);
5180 SS.setRange(Range);
5181 if (RequireCompleteDeclContext(SS))
5182 return QualType();
5183
5184 Ctx = computeDeclContext(SS);
5185 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005186 assert(Ctx && "No declaration context?");
5187
5188 DeclarationName Name(&II);
John McCalla24dc2e2009-11-17 02:14:36 +00005189 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
5190 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005191 unsigned DiagID = 0;
5192 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005193 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005194 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005195 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005196 break;
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005197
5198 case LookupResult::NotFoundInCurrentInstantiation:
5199 // Okay, it's a member of an unknown instantiation.
Douglas Gregor4a2023f2010-03-31 20:19:30 +00005200 return Context.getDependentNameType(ETK_Typename, NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00005201
5202 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +00005203 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005204 // We found a type. Build a QualifiedNameType, since the
5205 // typename-specifier was just sugar. FIXME: Tell
5206 // QualifiedNameType that it has a "typename" prefix.
5207 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
5208 }
5209
5210 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00005211 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00005212 break;
5213
John McCall7ba107a2009-11-18 02:36:19 +00005214 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005215 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00005216 return QualType();
5217
Douglas Gregord57959a2009-03-27 23:10:48 +00005218 case LookupResult::FoundOverloaded:
5219 DiagID = diag::err_typename_nested_not_type;
5220 Referenced = *Result.begin();
5221 break;
5222
John McCall6e247262009-10-10 05:48:19 +00005223 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00005224 return QualType();
5225 }
5226
5227 // If we get here, it's because name lookup did not find a
5228 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor3f093272009-10-13 21:16:44 +00005229 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00005230 if (Referenced)
5231 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5232 << Name;
5233 return QualType();
5234}
Douglas Gregor4a959d82009-08-06 16:20:37 +00005235
5236namespace {
5237 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00005238 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00005239 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00005240 SourceLocation Loc;
5241 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00005242
Douglas Gregor4a959d82009-08-06 16:20:37 +00005243 public:
Mike Stump1eb44332009-09-09 15:08:12 +00005244 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005245 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005246 DeclarationName Entity)
5247 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00005248 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00005249
5250 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00005251 /// transformed.
5252 ///
5253 /// For the purposes of type reconstruction, a type has already been
5254 /// transformed if it is NULL or if it is not dependent.
5255 bool AlreadyTransformed(QualType T) {
5256 return T.isNull() || !T->isDependentType();
5257 }
Mike Stump1eb44332009-09-09 15:08:12 +00005258
5259 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00005260 /// rebuilt.
5261 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00005262
Douglas Gregor4a959d82009-08-06 16:20:37 +00005263 /// \brief Returns the name of the entity whose type is being rebuilt.
5264 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00005265
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005266 /// \brief Sets the "base" location and entity when that
5267 /// information is known based on another transformation.
5268 void setBase(SourceLocation Loc, DeclarationName Entity) {
5269 this->Loc = Loc;
5270 this->Entity = Entity;
5271 }
5272
Douglas Gregor4a959d82009-08-06 16:20:37 +00005273 /// \brief Transforms an expression by returning the expression itself
5274 /// (an identity function).
5275 ///
5276 /// FIXME: This is completely unsafe; we will need to actually clone the
5277 /// expressions.
5278 Sema::OwningExprResult TransformExpr(Expr *E) {
5279 return getSema().Owned(E);
5280 }
Mike Stump1eb44332009-09-09 15:08:12 +00005281
Douglas Gregor4a959d82009-08-06 16:20:37 +00005282 /// \brief Transforms a typename type by determining whether the type now
5283 /// refers to a member of the current instantiation, and then
5284 /// type-checking and building a QualifiedNameType (when possible).
Douglas Gregor4714c122010-03-31 17:34:00 +00005285 QualType TransformDependentNameType(TypeLocBuilder &TLB, DependentNameTypeLoc TL,
Douglas Gregor124b8782010-02-16 19:09:40 +00005286 QualType ObjectType);
Douglas Gregor4a959d82009-08-06 16:20:37 +00005287 };
5288}
5289
Mike Stump1eb44332009-09-09 15:08:12 +00005290QualType
Douglas Gregor4714c122010-03-31 17:34:00 +00005291CurrentInstantiationRebuilder::TransformDependentNameType(TypeLocBuilder &TLB,
5292 DependentNameTypeLoc TL,
Douglas Gregor124b8782010-02-16 19:09:40 +00005293 QualType ObjectType) {
Douglas Gregor4714c122010-03-31 17:34:00 +00005294 DependentNameType *T = TL.getTypePtr();
John McCalla2becad2009-10-21 00:40:46 +00005295
Douglas Gregor4a959d82009-08-06 16:20:37 +00005296 NestedNameSpecifier *NNS
5297 = TransformNestedNameSpecifier(T->getQualifier(),
Douglas Gregor124b8782010-02-16 19:09:40 +00005298 /*FIXME:*/SourceRange(getBaseLocation()),
5299 ObjectType);
Douglas Gregor4a959d82009-08-06 16:20:37 +00005300 if (!NNS)
5301 return QualType();
5302
5303 // If the nested-name-specifier did not change, and we cannot compute the
5304 // context corresponding to the nested-name-specifier, then this
5305 // typename type will not change; exit early.
5306 CXXScopeSpec SS;
5307 SS.setRange(SourceRange(getBaseLocation()));
5308 SS.setScopeRep(NNS);
John McCall833ca992009-10-29 08:12:44 +00005309
5310 QualType Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00005311 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall833ca992009-10-29 08:12:44 +00005312 Result = QualType(T, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00005313
5314 // Rebuild the typename type, which will probably turn into a
Douglas Gregor4a959d82009-08-06 16:20:37 +00005315 // QualifiedNameType.
John McCall833ca992009-10-29 08:12:44 +00005316 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005317 QualType NewTemplateId
Douglas Gregor4a959d82009-08-06 16:20:37 +00005318 = TransformType(QualType(TemplateId, 0));
5319 if (NewTemplateId.isNull())
5320 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005321
Douglas Gregor4a959d82009-08-06 16:20:37 +00005322 if (NNS == T->getQualifier() &&
5323 NewTemplateId == QualType(TemplateId, 0))
John McCall833ca992009-10-29 08:12:44 +00005324 Result = QualType(T, 0);
5325 else
Douglas Gregor4a2023f2010-03-31 20:19:30 +00005326 Result = getDerived().RebuildDependentNameType(T->getKeyword(),
5327 NNS, NewTemplateId);
John McCall833ca992009-10-29 08:12:44 +00005328 } else
Douglas Gregor4a2023f2010-03-31 20:19:30 +00005329 Result = getDerived().RebuildDependentNameType(T->getKeyword(),
5330 NNS, T->getIdentifier(),
5331 SourceRange(TL.getNameLoc()));
Mike Stump1eb44332009-09-09 15:08:12 +00005332
Douglas Gregora50ce322010-03-07 23:26:22 +00005333 if (Result.isNull())
5334 return QualType();
5335
Douglas Gregor4714c122010-03-31 17:34:00 +00005336 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
John McCall833ca992009-10-29 08:12:44 +00005337 NewTL.setNameLoc(TL.getNameLoc());
5338 return Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00005339}
5340
5341/// \brief Rebuilds a type within the context of the current instantiation.
5342///
Mike Stump1eb44332009-09-09 15:08:12 +00005343/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00005344/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00005345/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00005346/// partial specialization thereof). This routine will rebuild that type now
5347/// that we have entered the declarator's scope, which may produce different
5348/// canonical types, e.g.,
5349///
5350/// \code
5351/// template<typename T>
5352/// struct X {
5353/// typedef T* pointer;
5354/// pointer data();
5355/// };
5356///
5357/// template<typename T>
5358/// typename X<T>::pointer X<T>::data() { ... }
5359/// \endcode
5360///
Douglas Gregor4714c122010-03-31 17:34:00 +00005361/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005362/// since we do not know that we can look into X<T> when we parsed the type.
5363/// This function will rebuild the type, performing the lookup of "pointer"
5364/// in X<T> and returning a QualifiedNameType whose canonical type is the same
5365/// as the canonical type of T*, allowing the return types of the out-of-line
5366/// definition and the declaration to match.
5367QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
5368 DeclarationName Name) {
5369 if (T.isNull() || !T->isDependentType())
5370 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00005371
Douglas Gregor4a959d82009-08-06 16:20:37 +00005372 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5373 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00005374}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005375
5376/// \brief Produces a formatted string that describes the binding of
5377/// template parameters to template arguments.
5378std::string
5379Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5380 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005381 // FIXME: For variadic templates, we'll need to get the structured list.
5382 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5383 Args.flat_size());
5384}
5385
5386std::string
5387Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5388 const TemplateArgument *Args,
5389 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005390 std::string Result;
5391
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005392 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005393 return Result;
5394
5395 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005396 if (I >= NumArgs)
5397 break;
5398
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005399 if (I == 0)
5400 Result += "[with ";
5401 else
5402 Result += ", ";
5403
5404 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5405 Result += Id->getName();
5406 } else {
5407 Result += '$';
5408 Result += llvm::utostr(I);
5409 }
5410
5411 Result += " = ";
5412
5413 switch (Args[I].getKind()) {
5414 case TemplateArgument::Null:
5415 Result += "<no value>";
5416 break;
5417
5418 case TemplateArgument::Type: {
5419 std::string TypeStr;
5420 Args[I].getAsType().getAsStringInternal(TypeStr,
5421 Context.PrintingPolicy);
5422 Result += TypeStr;
5423 break;
5424 }
5425
5426 case TemplateArgument::Declaration: {
5427 bool Unnamed = true;
5428 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5429 if (ND->getDeclName()) {
5430 Unnamed = false;
5431 Result += ND->getNameAsString();
5432 }
5433 }
5434
5435 if (Unnamed) {
5436 Result += "<anonymous>";
5437 }
5438 break;
5439 }
5440
Douglas Gregor788cd062009-11-11 01:00:40 +00005441 case TemplateArgument::Template: {
5442 std::string Str;
5443 llvm::raw_string_ostream OS(Str);
5444 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5445 Result += OS.str();
5446 break;
5447 }
5448
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005449 case TemplateArgument::Integral: {
5450 Result += Args[I].getAsIntegral()->toString(10);
5451 break;
5452 }
5453
5454 case TemplateArgument::Expression: {
5455 assert(false && "No expressions in deduced template arguments!");
5456 Result += "<expression>";
5457 break;
5458 }
5459
5460 case TemplateArgument::Pack:
5461 // FIXME: Format template argument packs
5462 Result += "<template argument pack>";
5463 break;
5464 }
5465 }
5466
5467 Result += ']';
5468 return Result;
5469}