blob: ecb89edcf7dfe2b82abc033427ed76da3f3badbb [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"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000020#include "clang/Parse/Template.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000023#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000024using namespace clang;
25
Douglas Gregor2dd078a2009-09-02 22:59:36 +000026/// \brief Determine whether the declaration found is acceptable as the name
27/// of a template and, if so, return that template declaration. Otherwise,
28/// returns NULL.
29static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
30 if (!D)
31 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +000032
Douglas Gregor2dd078a2009-09-02 22:59:36 +000033 if (isa<TemplateDecl>(D))
34 return D;
Mike Stump1eb44332009-09-09 15:08:12 +000035
Douglas Gregor2dd078a2009-09-02 22:59:36 +000036 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
37 // C++ [temp.local]p1:
38 // Like normal (non-template) classes, class templates have an
39 // injected-class-name (Clause 9). The injected-class-name
40 // can be used with or without a template-argument-list. When
41 // it is used without a template-argument-list, it is
42 // equivalent to the injected-class-name followed by the
43 // template-parameters of the class template enclosed in
44 // <>. When it is used with a template-argument-list, it
45 // refers to the specified class template specialization,
46 // which could be the current specialization or another
47 // specialization.
48 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000049 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000050 if (Record->getDescribedClassTemplate())
51 return Record->getDescribedClassTemplate();
52
53 if (ClassTemplateSpecializationDecl *Spec
54 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
55 return Spec->getSpecializedTemplate();
56 }
Mike Stump1eb44332009-09-09 15:08:12 +000057
Douglas Gregor2dd078a2009-09-02 22:59:36 +000058 return 0;
59 }
Mike Stump1eb44332009-09-09 15:08:12 +000060
Douglas Gregor2dd078a2009-09-02 22:59:36 +000061 return 0;
62}
63
John McCallf7a1a742009-11-24 19:00:30 +000064static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
65 LookupResult::Filter filter = R.makeFilter();
66 while (filter.hasNext()) {
67 NamedDecl *Orig = filter.next();
68 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
69 if (!Repl)
70 filter.erase();
71 else if (Repl != Orig)
72 filter.replace(Repl);
73 }
74 filter.done();
75}
76
Douglas Gregor2dd078a2009-09-02 22:59:36 +000077TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor014e88d2009-11-03 23:16:33 +000078 const CXXScopeSpec &SS,
79 UnqualifiedId &Name,
Douglas Gregor2dd078a2009-09-02 22:59:36 +000080 TypeTy *ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +000081 bool EnteringContext,
Douglas Gregor2dd078a2009-09-02 22:59:36 +000082 TemplateTy &TemplateResult) {
Douglas Gregor014e88d2009-11-03 23:16:33 +000083 DeclarationName TName;
84
85 switch (Name.getKind()) {
86 case UnqualifiedId::IK_Identifier:
87 TName = DeclarationName(Name.Identifier);
88 break;
89
90 case UnqualifiedId::IK_OperatorFunctionId:
91 TName = Context.DeclarationNames.getCXXOperatorName(
92 Name.OperatorFunctionId.Operator);
93 break;
94
Sean Hunte6252d12009-11-28 08:58:14 +000095 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +000096 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
97 break;
Sean Hunte6252d12009-11-28 08:58:14 +000098
Douglas Gregor014e88d2009-11-03 23:16:33 +000099 default:
100 return TNK_Non_template;
101 }
Mike Stump1eb44332009-09-09 15:08:12 +0000102
John McCallf7a1a742009-11-24 19:00:30 +0000103 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Douglas Gregorbfea2392009-12-31 08:11:17 +0000105 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
106 LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +0000107 R.suppressDiagnostics();
108 LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
109 if (R.empty())
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000110 return TNK_Non_template;
111
John McCall0bd6feb2009-12-02 08:04:21 +0000112 TemplateName Template;
113 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000114
John McCall0bd6feb2009-12-02 08:04:21 +0000115 unsigned ResultCount = R.end() - R.begin();
116 if (ResultCount > 1) {
117 // We assume that we'll preserve the qualifier from a function
118 // template name in other ways.
119 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
120 TemplateKind = TNK_Function_template;
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000121 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000122 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
123
124 if (SS.isSet() && !SS.isInvalid()) {
125 NestedNameSpecifier *Qualifier
126 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
127 Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
128 } else {
129 Template = TemplateName(TD);
130 }
131
132 if (isa<FunctionTemplateDecl>(TD))
133 TemplateKind = TNK_Function_template;
134 else {
135 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
136 TemplateKind = TNK_Type_template;
137 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000138 }
Mike Stump1eb44332009-09-09 15:08:12 +0000139
John McCall0bd6feb2009-12-02 08:04:21 +0000140 TemplateResult = TemplateTy::make(Template);
141 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000142}
143
144void Sema::LookupTemplateName(LookupResult &Found,
145 Scope *S, const CXXScopeSpec &SS,
146 QualType ObjectType,
147 bool EnteringContext) {
148 // Determine where to perform name lookup
149 DeclContext *LookupCtx = 0;
150 bool isDependent = false;
151 if (!ObjectType.isNull()) {
152 // This nested-name-specifier occurs in a member access expression, e.g.,
153 // x->B::f, and we are looking into the type of the object.
154 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
155 LookupCtx = computeDeclContext(ObjectType);
156 isDependent = ObjectType->isDependentType();
157 assert((isDependent || !ObjectType->isIncompleteType()) &&
158 "Caller should have completed object type");
159 } else if (SS.isSet()) {
160 // This nested-name-specifier occurs after another nested-name-specifier,
161 // so long into the context associated with the prior nested-name-specifier.
162 LookupCtx = computeDeclContext(SS, EnteringContext);
163 isDependent = isDependentScopeSpecifier(SS);
164
165 // The declaration context must be complete.
166 if (LookupCtx && RequireCompleteDeclContext(SS))
167 return;
168 }
169
170 bool ObjectTypeSearchedInScope = false;
171 if (LookupCtx) {
172 // Perform "qualified" name lookup into the declaration context we
173 // computed, which is either the type of the base of a member access
174 // expression or the declaration context associated with a prior
175 // nested-name-specifier.
176 LookupQualifiedName(Found, LookupCtx);
177
178 if (!ObjectType.isNull() && Found.empty()) {
179 // C++ [basic.lookup.classref]p1:
180 // In a class member access expression (5.2.5), if the . or -> token is
181 // immediately followed by an identifier followed by a <, the
182 // identifier must be looked up to determine whether the < is the
183 // beginning of a template argument list (14.2) or a less-than operator.
184 // The identifier is first looked up in the class of the object
185 // expression. If the identifier is not found, it is then looked up in
186 // the context of the entire postfix-expression and shall name a class
187 // or function template.
188 //
189 // FIXME: When we're instantiating a template, do we actually have to
190 // look in the scope of the template? Seems fishy...
191 if (S) LookupName(Found, S);
192 ObjectTypeSearchedInScope = true;
193 }
194 } else if (isDependent) {
195 // We cannot look into a dependent object type or
196 return;
197 } else {
198 // Perform unqualified name lookup in the current scope.
199 LookupName(Found, S);
200 }
201
202 // FIXME: Cope with ambiguous name-lookup results.
203 assert(!Found.isAmbiguous() &&
204 "Cannot handle template name-lookup ambiguities");
205
Douglas Gregorbfea2392009-12-31 08:11:17 +0000206 if (Found.empty()) {
207 // If we did not find any names, attempt to correct any typos.
208 DeclarationName Name = Found.getLookupName();
209 if (CorrectTypo(Found, S, &SS, LookupCtx)) {
210 FilterAcceptableTemplateNames(Context, Found);
211 if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
212 if (LookupCtx)
213 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
214 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
215 << CodeModificationHint::CreateReplacement(Found.getNameLoc(),
216 Found.getLookupName().getAsString());
217 else
218 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
219 << Name << Found.getLookupName()
220 << CodeModificationHint::CreateReplacement(Found.getNameLoc(),
221 Found.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000222 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
223 Diag(Template->getLocation(), diag::note_previous_decl)
224 << Template->getDeclName();
Douglas Gregorbfea2392009-12-31 08:11:17 +0000225 } else
226 Found.clear();
227 } else {
228 Found.clear();
229 }
230 }
231
John McCallf7a1a742009-11-24 19:00:30 +0000232 FilterAcceptableTemplateNames(Context, Found);
233 if (Found.empty())
234 return;
235
236 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
237 // C++ [basic.lookup.classref]p1:
238 // [...] If the lookup in the class of the object expression finds a
239 // template, the name is also looked up in the context of the entire
240 // postfix-expression and [...]
241 //
242 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
243 LookupOrdinaryName);
244 LookupName(FoundOuter, S);
245 FilterAcceptableTemplateNames(Context, FoundOuter);
246 // FIXME: Handle ambiguities in this lookup better
247
248 if (FoundOuter.empty()) {
249 // - if the name is not found, the name found in the class of the
250 // object expression is used, otherwise
251 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
252 // - if the name is found in the context of the entire
253 // postfix-expression and does not name a class template, the name
254 // found in the class of the object expression is used, otherwise
255 } else {
256 // - if the name found is a class template, it must refer to the same
257 // entity as the one found in the class of the object expression,
258 // otherwise the program is ill-formed.
259 if (!Found.isSingleResult() ||
260 Found.getFoundDecl()->getCanonicalDecl()
261 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
262 Diag(Found.getNameLoc(),
263 diag::err_nested_name_member_ref_lookup_ambiguous)
264 << Found.getLookupName();
265 Diag(Found.getRepresentativeDecl()->getLocation(),
266 diag::note_ambig_member_ref_object_type)
267 << ObjectType;
268 Diag(FoundOuter.getFoundDecl()->getLocation(),
269 diag::note_ambig_member_ref_scope);
270
271 // Recover by taking the template that we found in the object
272 // expression's type.
273 }
274 }
275 }
276}
277
John McCall2f841ba2009-12-02 03:53:29 +0000278/// ActOnDependentIdExpression - Handle a dependent id-expression that
279/// was just parsed. This is only possible with an explicit scope
280/// specifier naming a dependent type.
John McCallf7a1a742009-11-24 19:00:30 +0000281Sema::OwningExprResult
282Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
283 DeclarationName Name,
284 SourceLocation NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +0000285 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000286 const TemplateArgumentListInfo *TemplateArgs) {
287 NestedNameSpecifier *Qualifier
288 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
289
John McCall2f841ba2009-12-02 03:53:29 +0000290 if (!isAddressOfOperand &&
291 isa<CXXMethodDecl>(CurContext) &&
292 cast<CXXMethodDecl>(CurContext)->isInstance()) {
293 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
294
John McCallf7a1a742009-11-24 19:00:30 +0000295 // Since the 'this' expression is synthesized, we don't need to
296 // perform the double-lookup check.
297 NamedDecl *FirstQualifierInScope = 0;
298
John McCallaa81e162009-12-01 22:10:20 +0000299 return Owned(CXXDependentScopeMemberExpr::Create(Context,
300 /*This*/ 0, ThisType,
301 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000302 /*Op*/ SourceLocation(),
303 Qualifier, SS.getRange(),
304 FirstQualifierInScope,
305 Name, NameLoc,
306 TemplateArgs));
307 }
308
309 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
310}
311
312Sema::OwningExprResult
313Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
314 DeclarationName Name,
315 SourceLocation NameLoc,
316 const TemplateArgumentListInfo *TemplateArgs) {
317 return Owned(DependentScopeDeclRefExpr::Create(Context,
318 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
319 SS.getRange(),
320 Name, NameLoc,
321 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000322}
323
Douglas Gregor72c3f312008-12-05 18:15:24 +0000324/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
325/// that the template parameter 'PrevDecl' is being shadowed by a new
326/// declaration at location Loc. Returns true to indicate that this is
327/// an error, and false otherwise.
328bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000329 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000330
331 // Microsoft Visual C++ permits template parameters to be shadowed.
332 if (getLangOptions().Microsoft)
333 return false;
334
335 // C++ [temp.local]p4:
336 // A template-parameter shall not be redeclared within its
337 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000338 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000339 << cast<NamedDecl>(PrevDecl)->getDeclName();
340 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
341 return true;
342}
343
Douglas Gregor2943aed2009-03-03 04:44:36 +0000344/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000345/// the parameter D to reference the templated declaration and return a pointer
346/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000347TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor13d2d6c2009-10-06 21:27:51 +0000348 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000349 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000350 return Temp;
351 }
352 return 0;
353}
354
Douglas Gregor788cd062009-11-11 01:00:40 +0000355static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
356 const ParsedTemplateArgument &Arg) {
357
358 switch (Arg.getKind()) {
359 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000360 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000361 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
362 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000363 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000364 return TemplateArgumentLoc(TemplateArgument(T), DI);
365 }
366
367 case ParsedTemplateArgument::NonType: {
368 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
369 return TemplateArgumentLoc(TemplateArgument(E), E);
370 }
371
372 case ParsedTemplateArgument::Template: {
373 TemplateName Template
374 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
375 return TemplateArgumentLoc(TemplateArgument(Template),
376 Arg.getScopeSpec().getRange(),
377 Arg.getLocation());
378 }
379 }
380
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000381 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000382 return TemplateArgumentLoc();
383}
384
385/// \brief Translates template arguments as provided by the parser
386/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000387void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
388 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000389 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000390 TemplateArgs.addArgument(translateTemplateArgument(*this,
391 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000392}
393
Douglas Gregor72c3f312008-12-05 18:15:24 +0000394/// ActOnTypeParameter - Called when a C++ template type parameter
395/// (e.g., "typename T") has been parsed. Typename specifies whether
396/// the keyword "typename" was used to declare the type parameter
397/// (otherwise, "class" was used), and KeyLoc is the location of the
398/// "class" or "typename" keyword. ParamName is the name of the
399/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump1eb44332009-09-09 15:08:12 +0000400/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000401/// If the type parameter has a default argument, it will be added
402/// later via ActOnTypeParameterDefault.
Mike Stump1eb44332009-09-09 15:08:12 +0000403Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson941df7d2009-06-12 19:58:00 +0000404 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000405 SourceLocation KeyLoc,
406 IdentifierInfo *ParamName,
407 SourceLocation ParamNameLoc,
408 unsigned Depth, unsigned Position) {
Mike Stump1eb44332009-09-09 15:08:12 +0000409 assert(S->isTemplateParamScope() &&
410 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000411 bool Invalid = false;
412
413 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000414 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000415 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000416 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000417 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000418 }
419
Douglas Gregorddc29e12009-02-06 22:42:48 +0000420 SourceLocation Loc = ParamNameLoc;
421 if (!ParamName)
422 Loc = KeyLoc;
423
Douglas Gregor72c3f312008-12-05 18:15:24 +0000424 TemplateTypeParmDecl *Param
Mike Stump1eb44332009-09-09 15:08:12 +0000425 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
426 Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000427 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000428 if (Invalid)
429 Param->setInvalidDecl();
430
431 if (ParamName) {
432 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000433 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000434 IdResolver.AddDecl(Param);
435 }
436
Chris Lattnerb28317a2009-03-28 19:18:32 +0000437 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000438}
439
Douglas Gregord684b002009-02-10 19:49:53 +0000440/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump1eb44332009-09-09 15:08:12 +0000441/// Default) to the given template type parameter (TypeParam).
442void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000443 SourceLocation EqualLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000444 SourceLocation DefaultLoc,
Douglas Gregord684b002009-02-10 19:49:53 +0000445 TypeTy *DefaultT) {
Mike Stump1eb44332009-09-09 15:08:12 +0000446 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000447 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall833ca992009-10-29 08:12:44 +0000448
John McCalla93c9342009-12-07 02:54:59 +0000449 TypeSourceInfo *DefaultTInfo;
450 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall833ca992009-10-29 08:12:44 +0000451
John McCalla93c9342009-12-07 02:54:59 +0000452 assert(DefaultTInfo && "expected source information for type");
Douglas Gregord684b002009-02-10 19:49:53 +0000453
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000454 // C++0x [temp.param]p9:
455 // A default template-argument may be specified for any kind of
Mike Stump1eb44332009-09-09 15:08:12 +0000456 // template-parameter that is not a template parameter pack.
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000457 if (Parm->isParameterPack()) {
458 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000459 return;
460 }
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Douglas Gregord684b002009-02-10 19:49:53 +0000462 // C++ [temp.param]p14:
463 // A template-parameter shall not be used in its own default argument.
464 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Douglas Gregord684b002009-02-10 19:49:53 +0000466 // Check the template argument itself.
John McCalla93c9342009-12-07 02:54:59 +0000467 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000468 Parm->setInvalidDecl();
469 return;
470 }
471
John McCalla93c9342009-12-07 02:54:59 +0000472 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000473}
474
Douglas Gregor2943aed2009-03-03 04:44:36 +0000475/// \brief Check that the type of a non-type template parameter is
476/// well-formed.
477///
478/// \returns the (possibly-promoted) parameter type if valid;
479/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000480QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000481Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
482 // C++ [temp.param]p4:
483 //
484 // A non-type template-parameter shall have one of the following
485 // (optionally cv-qualified) types:
486 //
487 // -- integral or enumeration type,
488 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000489 // -- pointer to object or pointer to function,
490 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000491 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
492 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000493 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000494 T->isReferenceType() ||
495 // -- pointer to member.
496 T->isMemberPointerType() ||
497 // If T is a dependent type, we can't do the check now, so we
498 // assume that it is well-formed.
499 T->isDependentType())
500 return T;
501 // C++ [temp.param]p8:
502 //
503 // A non-type template-parameter of type "array of T" or
504 // "function returning T" is adjusted to be of type "pointer to
505 // T" or "pointer to function returning T", respectively.
506 else if (T->isArrayType())
507 // FIXME: Keep the type prior to promotion?
508 return Context.getArrayDecayedType(T);
509 else if (T->isFunctionType())
510 // FIXME: Keep the type prior to promotion?
511 return Context.getPointerType(T);
512
513 Diag(Loc, diag::err_template_nontype_parm_bad_type)
514 << T;
515
516 return QualType();
517}
518
Douglas Gregor72c3f312008-12-05 18:15:24 +0000519/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
520/// template parameter (e.g., "int Size" in "template<int Size>
521/// class Array") has been parsed. S is the current scope and D is
522/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000523Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump1eb44332009-09-09 15:08:12 +0000524 unsigned Depth,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000525 unsigned Position) {
John McCalla93c9342009-12-07 02:54:59 +0000526 TypeSourceInfo *TInfo = 0;
527 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000528
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000529 assert(S->isTemplateParamScope() &&
530 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000531 bool Invalid = false;
532
533 IdentifierInfo *ParamName = D.getIdentifier();
534 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000535 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000536 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000537 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000538 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000539 }
540
Douglas Gregor2943aed2009-03-03 04:44:36 +0000541 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000542 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000543 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000544 Invalid = true;
545 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000546
Douglas Gregor72c3f312008-12-05 18:15:24 +0000547 NonTypeTemplateParmDecl *Param
548 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
John McCalla93c9342009-12-07 02:54:59 +0000549 Depth, Position, ParamName, T, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000550 if (Invalid)
551 Param->setInvalidDecl();
552
553 if (D.getIdentifier()) {
554 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000555 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000556 IdResolver.AddDecl(Param);
557 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000558 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000559}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000560
Douglas Gregord684b002009-02-10 19:49:53 +0000561/// \brief Adds a default argument to the given non-type template
562/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000563void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000564 SourceLocation EqualLoc,
565 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000566 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000567 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000568 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Douglas Gregord684b002009-02-10 19:49:53 +0000570 // C++ [temp.param]p14:
571 // A template-parameter shall not be used in its own default argument.
572 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Douglas Gregord684b002009-02-10 19:49:53 +0000574 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000575 TemplateArgument Converted;
576 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
577 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000578 TemplateParm->setInvalidDecl();
579 return;
580 }
581
Anders Carlssone9146f22009-05-01 19:49:17 +0000582 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000583}
584
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000585
586/// ActOnTemplateTemplateParameter - Called when a C++ template template
587/// parameter (e.g. T in template <template <typename> class T> class array)
588/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000589Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
590 SourceLocation TmpLoc,
591 TemplateParamsTy *Params,
592 IdentifierInfo *Name,
593 SourceLocation NameLoc,
594 unsigned Depth,
Mike Stump1eb44332009-09-09 15:08:12 +0000595 unsigned Position) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000596 assert(S->isTemplateParamScope() &&
597 "Template template parameter not in template parameter scope!");
598
599 // Construct the parameter object.
600 TemplateTemplateParmDecl *Param =
601 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
602 Position, Name,
603 (TemplateParameterList*)Params);
604
605 // Make sure the parameter is valid.
606 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
607 // do anything yet. However, if the template parameter list or (eventual)
608 // default value is ever invalidated, that will propagate here.
609 bool Invalid = false;
610 if (Invalid) {
611 Param->setInvalidDecl();
612 }
613
614 // If the tt-param has a name, then link the identifier into the scope
615 // and lookup mechanisms.
616 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000617 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000618 IdResolver.AddDecl(Param);
619 }
620
Chris Lattnerb28317a2009-03-28 19:18:32 +0000621 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000622}
623
Douglas Gregord684b002009-02-10 19:49:53 +0000624/// \brief Adds a default argument to the given template template
625/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000626void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000627 SourceLocation EqualLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +0000628 const ParsedTemplateArgument &Default) {
Mike Stump1eb44332009-09-09 15:08:12 +0000629 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000630 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor788cd062009-11-11 01:00:40 +0000631
Douglas Gregord684b002009-02-10 19:49:53 +0000632 // C++ [temp.param]p14:
633 // A template-parameter shall not be used in its own default argument.
634 // FIXME: Implement this check! Needs a recursive walk over the types.
635
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000636 // Check only that we have a template template argument. We don't want to
637 // try to check well-formedness now, because our template template parameter
638 // might have dependent types in its template parameters, which we wouldn't
639 // be able to match now.
640 //
641 // If none of the template template parameter's template arguments mention
642 // other template parameters, we could actually perform more checking here.
643 // However, it isn't worth doing.
Douglas Gregor788cd062009-11-11 01:00:40 +0000644 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000645 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
646 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
647 << DefaultArg.getSourceRange();
Douglas Gregord684b002009-02-10 19:49:53 +0000648 return;
649 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000650
Douglas Gregor788cd062009-11-11 01:00:40 +0000651 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregord684b002009-02-10 19:49:53 +0000652}
653
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000654/// ActOnTemplateParameterList - Builds a TemplateParameterList that
655/// contains the template parameters in Params/NumParams.
656Sema::TemplateParamsTy *
657Sema::ActOnTemplateParameterList(unsigned Depth,
658 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000659 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000660 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000661 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000662 SourceLocation RAngleLoc) {
663 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000664 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000665
Douglas Gregorddc29e12009-02-06 22:42:48 +0000666 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000667 (NamedDecl**)Params, NumParams,
668 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000669}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000670
Douglas Gregor212e81c2009-03-25 00:13:59 +0000671Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000672Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000673 SourceLocation KWLoc, const CXXScopeSpec &SS,
674 IdentifierInfo *Name, SourceLocation NameLoc,
675 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000676 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000677 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000678 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000679 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000680 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000681 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000682
683 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000684 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000685 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000686
John McCall05b23ea2009-09-14 21:59:20 +0000687 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
688 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000689
690 // There is no such thing as an unnamed class template.
691 if (!Name) {
692 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000693 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000694 }
695
696 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000697 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000698 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000699 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000700 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregorf0510d42009-10-12 23:11:44 +0000701 if (RequireCompleteDeclContext(SS))
702 return true;
703
Douglas Gregor05396e22009-08-25 17:23:04 +0000704 SemanticContext = computeDeclContext(SS, true);
705 if (!SemanticContext) {
706 // FIXME: Produce a reasonable diagnostic here
707 return true;
708 }
Mike Stump1eb44332009-09-09 15:08:12 +0000709
John McCalla24dc2e2009-11-17 02:14:36 +0000710 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000711 } else {
712 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000713 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000714 }
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Douglas Gregorddc29e12009-02-06 22:42:48 +0000716 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
717 NamedDecl *PrevDecl = 0;
718 if (Previous.begin() != Previous.end())
719 PrevDecl = *Previous.begin();
720
Douglas Gregorddc29e12009-02-06 22:42:48 +0000721 // If there is a previous declaration with the same name, check
722 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000723 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000724 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000725
726 // We may have found the injected-class-name of a class template,
727 // class template partial specialization, or class template specialization.
728 // In these cases, grab the template that is being defined or specialized.
729 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
730 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
731 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
732 PrevClassTemplate
733 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
734 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
735 PrevClassTemplate
736 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
737 ->getSpecializedTemplate();
738 }
739 }
740
John McCall65c49462009-12-18 11:25:59 +0000741 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000742 // C++ [namespace.memdef]p3:
743 // [...] When looking for a prior declaration of a class or a function
744 // declared as a friend, and when the name of the friend class or
745 // function is neither a qualified name nor a template-id, scopes outside
746 // the innermost enclosing namespace scope are not considered.
747 DeclContext *OutermostContext = CurContext;
748 while (!OutermostContext->isFileContext())
749 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000750
751 if (PrevDecl &&
752 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
753 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
John McCalle129d442009-12-17 23:21:11 +0000754 SemanticContext = PrevDecl->getDeclContext();
755 } else {
756 // Declarations in outer scopes don't matter. However, the outermost
757 // context we computed is the semantic context for our new
758 // declaration.
759 PrevDecl = PrevClassTemplate = 0;
760 SemanticContext = OutermostContext;
761 }
762
763 if (CurContext->isDependentContext()) {
764 // If this is a dependent context, we don't want to link the friend
765 // class template to the template in scope, because that would perform
766 // checking of the template parameter lists that can't be performed
767 // until the outer context is instantiated.
768 PrevDecl = PrevClassTemplate = 0;
769 }
770 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
771 PrevDecl = PrevClassTemplate = 0;
772
Douglas Gregorddc29e12009-02-06 22:42:48 +0000773 if (PrevClassTemplate) {
774 // Ensure that the template parameter lists are compatible.
775 if (!TemplateParameterListsAreEqual(TemplateParams,
776 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000777 /*Complain=*/true,
778 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000779 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000780
781 // C++ [temp.class]p4:
782 // In a redeclaration, partial specialization, explicit
783 // specialization or explicit instantiation of a class template,
784 // the class-key shall agree in kind with the original class
785 // template declaration (7.1.5.3).
786 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000787 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000788 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000789 << Name
Mike Stump1eb44332009-09-09 15:08:12 +0000790 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +0000791 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000792 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000793 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000794 }
795
Douglas Gregorddc29e12009-02-06 22:42:48 +0000796 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000797 if (TUK == TUK_Definition) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000798 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
799 Diag(NameLoc, diag::err_redefinition) << Name;
800 Diag(Def->getLocation(), diag::note_previous_definition);
801 // FIXME: Would it make sense to try to "forget" the previous
802 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000803 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000804 }
805 }
806 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
807 // Maybe we will complain about the shadowed template parameter.
808 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
809 // Just pretend that we didn't see the previous declaration.
810 PrevDecl = 0;
811 } else if (PrevDecl) {
812 // C++ [temp]p5:
813 // A class template shall not have the same name as any other
814 // template, class, function, object, enumeration, enumerator,
815 // namespace, or type in the same scope (3.3), except as specified
816 // in (14.5.4).
817 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
818 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000819 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000820 }
821
Douglas Gregord684b002009-02-10 19:49:53 +0000822 // Check the template parameter list of this declaration, possibly
823 // merging in the template parameter list from the previous class
824 // template declaration.
825 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000826 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
827 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000828 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Douglas Gregor7da97d02009-05-10 22:57:19 +0000830 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000831 // declaration!
832
Mike Stump1eb44332009-09-09 15:08:12 +0000833 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000834 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000835 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000836 PrevClassTemplate->getTemplatedDecl() : 0,
837 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000838
839 ClassTemplateDecl *NewTemplate
840 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
841 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000842 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000843 NewClass->setDescribedClassTemplate(NewTemplate);
844
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000845 // Build the type for the class template declaration now.
Mike Stump1eb44332009-09-09 15:08:12 +0000846 QualType T =
847 Context.getTypeDeclType(NewClass,
848 PrevClassTemplate?
849 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000850 assert(T->isDependentType() && "Class template type is not dependent?");
851 (void)T;
852
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000853 // If we are providing an explicit specialization of a member that is a
854 // class template, make a note of that.
855 if (PrevClassTemplate &&
856 PrevClassTemplate->getInstantiatedFromMemberTemplate())
857 PrevClassTemplate->setMemberSpecialization();
858
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000859 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000860 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000861 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Douglas Gregorddc29e12009-02-06 22:42:48 +0000863 // Set the lexical context of these templates
864 NewClass->setLexicalDeclContext(CurContext);
865 NewTemplate->setLexicalDeclContext(CurContext);
866
John McCall0f434ec2009-07-31 02:45:11 +0000867 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000868 NewClass->startDefinition();
869
870 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000871 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000872
John McCall05b23ea2009-09-14 21:59:20 +0000873 if (TUK != TUK_Friend)
874 PushOnScopeChains(NewTemplate, S);
875 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000876 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000877 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000878 NewClass->setAccess(PrevClassTemplate->getAccess());
879 }
John McCall05b23ea2009-09-14 21:59:20 +0000880
Douglas Gregord85bea22009-09-26 06:47:28 +0000881 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
882 PrevClassTemplate != NULL);
883
John McCall05b23ea2009-09-14 21:59:20 +0000884 // Friend templates are visible in fairly strange ways.
885 if (!CurContext->isDependentContext()) {
886 DeclContext *DC = SemanticContext->getLookupContext();
887 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
888 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
889 PushOnScopeChains(NewTemplate, EnclosingScope,
890 /* AddToContext = */ false);
891 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000892
893 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
894 NewClass->getLocation(),
895 NewTemplate,
896 /*FIXME:*/NewClass->getLocation());
897 Friend->setAccess(AS_public);
898 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000899 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000900
Douglas Gregord684b002009-02-10 19:49:53 +0000901 if (Invalid) {
902 NewTemplate->setInvalidDecl();
903 NewClass->setInvalidDecl();
904 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000905 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000906}
907
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000908/// \brief Diagnose the presence of a default template argument on a
909/// template parameter, which is ill-formed in certain contexts.
910///
911/// \returns true if the default template argument should be dropped.
912static bool DiagnoseDefaultTemplateArgument(Sema &S,
913 Sema::TemplateParamListContext TPC,
914 SourceLocation ParamLoc,
915 SourceRange DefArgRange) {
916 switch (TPC) {
917 case Sema::TPC_ClassTemplate:
918 return false;
919
920 case Sema::TPC_FunctionTemplate:
921 // C++ [temp.param]p9:
922 // A default template-argument shall not be specified in a
923 // function template declaration or a function template
924 // definition [...]
925 // (This sentence is not in C++0x, per DR226).
926 if (!S.getLangOptions().CPlusPlus0x)
927 S.Diag(ParamLoc,
928 diag::err_template_parameter_default_in_function_template)
929 << DefArgRange;
930 return false;
931
932 case Sema::TPC_ClassTemplateMember:
933 // C++0x [temp.param]p9:
934 // A default template-argument shall not be specified in the
935 // template-parameter-lists of the definition of a member of a
936 // class template that appears outside of the member's class.
937 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
938 << DefArgRange;
939 return true;
940
941 case Sema::TPC_FriendFunctionTemplate:
942 // C++ [temp.param]p9:
943 // A default template-argument shall not be specified in a
944 // friend template declaration.
945 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
946 << DefArgRange;
947 return true;
948
949 // FIXME: C++0x [temp.param]p9 allows default template-arguments
950 // for friend function templates if there is only a single
951 // declaration (and it is a definition). Strange!
952 }
953
954 return false;
955}
956
Douglas Gregord684b002009-02-10 19:49:53 +0000957/// \brief Checks the validity of a template parameter list, possibly
958/// considering the template parameter list from a previous
959/// declaration.
960///
961/// If an "old" template parameter list is provided, it must be
962/// equivalent (per TemplateParameterListsAreEqual) to the "new"
963/// template parameter list.
964///
965/// \param NewParams Template parameter list for a new template
966/// declaration. This template parameter list will be updated with any
967/// default arguments that are carried through from the previous
968/// template parameter list.
969///
970/// \param OldParams If provided, template parameter list from a
971/// previous declaration of the same template. Default template
972/// arguments will be merged from the old template parameter list to
973/// the new template parameter list.
974///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000975/// \param TPC Describes the context in which we are checking the given
976/// template parameter list.
977///
Douglas Gregord684b002009-02-10 19:49:53 +0000978/// \returns true if an error occurred, false otherwise.
979bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000980 TemplateParameterList *OldParams,
981 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +0000982 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Douglas Gregord684b002009-02-10 19:49:53 +0000984 // C++ [temp.param]p10:
985 // The set of default template-arguments available for use with a
986 // template declaration or definition is obtained by merging the
987 // default arguments from the definition (if in scope) and all
988 // declarations in scope in the same way default function
989 // arguments are (8.3.6).
990 bool SawDefaultArgument = false;
991 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000992
Anders Carlsson49d25572009-06-12 23:20:15 +0000993 bool SawParameterPack = false;
994 SourceLocation ParameterPackLoc;
995
Mike Stump1a35fde2009-02-11 23:03:27 +0000996 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000997 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000998 if (OldParams)
999 OldParam = OldParams->begin();
1000
1001 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1002 NewParamEnd = NewParams->end();
1003 NewParam != NewParamEnd; ++NewParam) {
1004 // Variables used to diagnose redundant default arguments
1005 bool RedundantDefaultArg = false;
1006 SourceLocation OldDefaultLoc;
1007 SourceLocation NewDefaultLoc;
1008
1009 // Variables used to diagnose missing default arguments
1010 bool MissingDefaultArg = false;
1011
Anders Carlsson49d25572009-06-12 23:20:15 +00001012 // C++0x [temp.param]p11:
1013 // If a template parameter of a class template is a template parameter pack,
1014 // it must be the last template parameter.
1015 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001016 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001017 diag::err_template_param_pack_must_be_last_template_parameter);
1018 Invalid = true;
1019 }
1020
Douglas Gregord684b002009-02-10 19:49:53 +00001021 if (TemplateTypeParmDecl *NewTypeParm
1022 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001023 // Check the presence of a default argument here.
1024 if (NewTypeParm->hasDefaultArgument() &&
1025 DiagnoseDefaultTemplateArgument(*this, TPC,
1026 NewTypeParm->getLocation(),
1027 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1028 .getFullSourceRange()))
1029 NewTypeParm->removeDefaultArgument();
1030
1031 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001032 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001033 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001034
Anders Carlsson49d25572009-06-12 23:20:15 +00001035 if (NewTypeParm->isParameterPack()) {
1036 assert(!NewTypeParm->hasDefaultArgument() &&
1037 "Parameter packs can't have a default argument!");
1038 SawParameterPack = true;
1039 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001040 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001041 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001042 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1043 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1044 SawDefaultArgument = true;
1045 RedundantDefaultArg = true;
1046 PreviousDefaultArgLoc = NewDefaultLoc;
1047 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1048 // Merge the default argument from the old declaration to the
1049 // new declaration.
1050 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001051 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001052 true);
1053 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1054 } else if (NewTypeParm->hasDefaultArgument()) {
1055 SawDefaultArgument = true;
1056 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1057 } else if (SawDefaultArgument)
1058 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001059 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001060 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001061 // Check the presence of a default argument here.
1062 if (NewNonTypeParm->hasDefaultArgument() &&
1063 DiagnoseDefaultTemplateArgument(*this, TPC,
1064 NewNonTypeParm->getLocation(),
1065 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1066 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1067 NewNonTypeParm->setDefaultArgument(0);
1068 }
1069
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001070 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001071 NonTypeTemplateParmDecl *OldNonTypeParm
1072 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001073 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001074 NewNonTypeParm->hasDefaultArgument()) {
1075 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1076 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1077 SawDefaultArgument = true;
1078 RedundantDefaultArg = true;
1079 PreviousDefaultArgLoc = NewDefaultLoc;
1080 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1081 // Merge the default argument from the old declaration to the
1082 // new declaration.
1083 SawDefaultArgument = true;
1084 // FIXME: We need to create a new kind of "default argument"
1085 // expression that points to a previous template template
1086 // parameter.
1087 NewNonTypeParm->setDefaultArgument(
1088 OldNonTypeParm->getDefaultArgument());
1089 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1090 } else if (NewNonTypeParm->hasDefaultArgument()) {
1091 SawDefaultArgument = true;
1092 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1093 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001094 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001095 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001096 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001097 TemplateTemplateParmDecl *NewTemplateParm
1098 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001099 if (NewTemplateParm->hasDefaultArgument() &&
1100 DiagnoseDefaultTemplateArgument(*this, TPC,
1101 NewTemplateParm->getLocation(),
1102 NewTemplateParm->getDefaultArgument().getSourceRange()))
1103 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1104
1105 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001106 TemplateTemplateParmDecl *OldTemplateParm
1107 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001108 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001109 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001110 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1111 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001112 SawDefaultArgument = true;
1113 RedundantDefaultArg = true;
1114 PreviousDefaultArgLoc = NewDefaultLoc;
1115 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1116 // Merge the default argument from the old declaration to the
1117 // new declaration.
1118 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001119 // FIXME: We need to create a new kind of "default argument" expression
1120 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001121 NewTemplateParm->setDefaultArgument(
1122 OldTemplateParm->getDefaultArgument());
Douglas Gregor788cd062009-11-11 01:00:40 +00001123 PreviousDefaultArgLoc
1124 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001125 } else if (NewTemplateParm->hasDefaultArgument()) {
1126 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001127 PreviousDefaultArgLoc
1128 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001129 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001130 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001131 }
1132
1133 if (RedundantDefaultArg) {
1134 // C++ [temp.param]p12:
1135 // A template-parameter shall not be given default arguments
1136 // by two different declarations in the same scope.
1137 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1138 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1139 Invalid = true;
1140 } else if (MissingDefaultArg) {
1141 // C++ [temp.param]p11:
1142 // If a template-parameter has a default template-argument,
1143 // all subsequent template-parameters shall have a default
1144 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001145 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001146 diag::err_template_param_default_arg_missing);
1147 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1148 Invalid = true;
1149 }
1150
1151 // If we have an old template parameter list that we're merging
1152 // in, move on to the next parameter.
1153 if (OldParams)
1154 ++OldParam;
1155 }
1156
1157 return Invalid;
1158}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001159
Mike Stump1eb44332009-09-09 15:08:12 +00001160/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001161/// specifier, returning the template parameter list that applies to the
1162/// name.
1163///
1164/// \param DeclStartLoc the start of the declaration that has a scope
1165/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001166///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001167/// \param SS the scope specifier that will be matched to the given template
1168/// parameter lists. This scope specifier precedes a qualified name that is
1169/// being declared.
1170///
1171/// \param ParamLists the template parameter lists, from the outermost to the
1172/// innermost template parameter lists.
1173///
1174/// \param NumParamLists the number of template parameter lists in ParamLists.
1175///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001176/// \param IsExplicitSpecialization will be set true if the entity being
1177/// declared is an explicit specialization, false otherwise.
1178///
Mike Stump1eb44332009-09-09 15:08:12 +00001179/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001180/// name that is preceded by the scope specifier @p SS. This template
1181/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001182/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001183/// template specialization), or may be NULL (if we were's declaring isn't
1184/// itself a template).
1185TemplateParameterList *
1186Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1187 const CXXScopeSpec &SS,
1188 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001189 unsigned NumParamLists,
1190 bool &IsExplicitSpecialization) {
1191 IsExplicitSpecialization = false;
1192
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001193 // Find the template-ids that occur within the nested-name-specifier. These
1194 // template-ids will match up with the template parameter lists.
1195 llvm::SmallVector<const TemplateSpecializationType *, 4>
1196 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001197 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1198 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001199 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1200 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001201 const Type *T = NNS->getAsType();
1202 if (!T) break;
1203
1204 // C++0x [temp.expl.spec]p17:
1205 // A member or a member template may be nested within many
1206 // enclosing class templates. In an explicit specialization for
1207 // such a member, the member declaration shall be preceded by a
1208 // template<> for each enclosing class template that is
1209 // explicitly specialized.
1210 // We interpret this as forbidding typedefs of template
1211 // specializations in the scope specifiers of out-of-line decls.
1212 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) {
1213 const Type *UnderlyingT = TT->LookThroughTypedefs().getTypePtr();
1214 if (isa<TemplateSpecializationType>(UnderlyingT))
1215 // FIXME: better source location information.
1216 Diag(DeclStartLoc, diag::err_typedef_in_def_scope) << QualType(T,0);
1217 T = UnderlyingT;
1218 }
1219
Mike Stump1eb44332009-09-09 15:08:12 +00001220 if (const TemplateSpecializationType *SpecType
John McCall4b2b02b2009-12-15 02:19:47 +00001221 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001222 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1223 if (!Template)
1224 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Ted Kremenek6217b802009-07-29 21:53:49 +00001226 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001227 ClassTemplateSpecializationDecl *SpecDecl
1228 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1229 // If the nested name specifier refers to an explicit specialization,
1230 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001231 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1232 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001233 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001234 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001235 }
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001237 TemplateIdsInSpecifier.push_back(SpecType);
1238 }
1239 }
Mike Stump1eb44332009-09-09 15:08:12 +00001240
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001241 // Reverse the list of template-ids in the scope specifier, so that we can
1242 // more easily match up the template-ids and the template parameter lists.
1243 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001245 SourceLocation FirstTemplateLoc = DeclStartLoc;
1246 if (NumParamLists)
1247 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001248
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001249 // Match the template-ids found in the specifier to the template parameter
1250 // lists.
1251 unsigned Idx = 0;
1252 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1253 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001254 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1255 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001256 if (Idx >= NumParamLists) {
1257 // We have a template-id without a corresponding template parameter
1258 // list.
1259 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001260 // FIXME: the location information here isn't great.
1261 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001262 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001263 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001264 << SS.getRange();
1265 } else {
1266 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1267 << SS.getRange()
1268 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1269 "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001270 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001271 }
1272 return 0;
1273 }
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001275 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001276 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001277 TemplateDecl *Template
Douglas Gregorb88e8882009-07-30 17:40:51 +00001278 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1279
Mike Stump1eb44332009-09-09 15:08:12 +00001280 if (ClassTemplateDecl *ClassTemplate
Douglas Gregorb88e8882009-07-30 17:40:51 +00001281 = dyn_cast<ClassTemplateDecl>(Template)) {
1282 TemplateParameterList *ExpectedTemplateParams = 0;
1283 // Is this template-id naming the primary template?
1284 if (Context.hasSameType(TemplateId,
1285 ClassTemplate->getInjectedClassNameType(Context)))
1286 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1287 // ... or a partial specialization?
1288 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1289 = ClassTemplate->findPartialSpecialization(TemplateId))
1290 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1291
1292 if (ExpectedTemplateParams)
Mike Stump1eb44332009-09-09 15:08:12 +00001293 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregorb88e8882009-07-30 17:40:51 +00001294 ExpectedTemplateParams,
Douglas Gregorfb898e12009-11-12 16:20:59 +00001295 true, TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00001296 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001297
1298 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregorb88e8882009-07-30 17:40:51 +00001299 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001300 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001301 diag::err_template_param_list_matches_nontemplate)
1302 << TemplateId
1303 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001304 else
1305 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001306 }
Mike Stump1eb44332009-09-09 15:08:12 +00001307
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001308 // If there were at least as many template-ids as there were template
1309 // parameter lists, then there are no template parameter lists remaining for
1310 // the declaration itself.
1311 if (Idx >= NumParamLists)
1312 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001314 // If there were too many template parameter lists, complain about that now.
1315 if (Idx != NumParamLists - 1) {
1316 while (Idx < NumParamLists - 1) {
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001317 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001318 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001319 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1320 : diag::err_template_spec_extra_headers)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001321 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1322 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001323
1324 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1325 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1326 diag::note_explicit_template_spec_does_not_need_header)
1327 << ExplicitSpecializationsInSpecifier.back();
1328 ExplicitSpecializationsInSpecifier.pop_back();
1329 }
1330
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001331 ++Idx;
1332 }
1333 }
Mike Stump1eb44332009-09-09 15:08:12 +00001334
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001335 // Return the last template parameter list, which corresponds to the
1336 // entity being declared.
1337 return ParamLists[NumParamLists - 1];
1338}
1339
Douglas Gregor7532dc62009-03-30 22:58:21 +00001340QualType Sema::CheckTemplateIdType(TemplateName Name,
1341 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001342 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001343 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001344 if (!Template) {
1345 // The template name does not resolve to a template, so we just
1346 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001347 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001348 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001349
Douglas Gregor40808ce2009-03-09 23:48:35 +00001350 // Check that the template argument list is well-formed for this
1351 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001352 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCalld5532b62009-11-23 01:53:49 +00001353 TemplateArgs.size());
1354 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001355 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001356 return QualType();
1357
Mike Stump1eb44332009-09-09 15:08:12 +00001358 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001359 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001360 "Converted template argument list is too short!");
1361
1362 QualType CanonType;
1363
Douglas Gregorcaddba02009-11-12 18:38:13 +00001364 if (Name.isDependent() ||
1365 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001366 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001367 // This class template specialization is a dependent
1368 // type. Therefore, its canonical type is another class template
1369 // specialization type that contains all of the converted
1370 // arguments in canonical form. This ensures that, e.g., A<T> and
1371 // A<T, T> have identical types when A is declared as:
1372 //
1373 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001374 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001375 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001376 Converted.getFlatArguments(),
1377 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001378
Douglas Gregor1275ae02009-07-28 23:00:59 +00001379 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001380 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001381 // In the future, we need to teach getTemplateSpecializationType to only
1382 // build the canonical type and return that to us.
1383 CanonType = Context.getCanonicalType(CanonType);
Mike Stump1eb44332009-09-09 15:08:12 +00001384 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001385 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001386 // Find the class template specialization declaration that
1387 // corresponds to these arguments.
1388 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001389 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001390 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001391 Converted.flatSize(),
1392 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001393 void *InsertPos = 0;
1394 ClassTemplateSpecializationDecl *Decl
1395 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1396 if (!Decl) {
1397 // This is the first time we have referenced this class template
1398 // specialization. Create the canonical declaration and add it to
1399 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001400 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001401 ClassTemplate->getDeclContext(),
John McCall9cc78072009-09-11 07:25:08 +00001402 ClassTemplate->getLocation(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001403 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00001404 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001405 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1406 Decl->setLexicalDeclContext(CurContext);
1407 }
1408
1409 CanonType = Context.getTypeDeclType(Decl);
1410 }
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Douglas Gregor40808ce2009-03-09 23:48:35 +00001412 // Build the fully-sugared type for this class template
1413 // specialization, which refers back to the class template
1414 // specialization we created or found.
John McCalld5532b62009-11-23 01:53:49 +00001415 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001416}
1417
Douglas Gregorcc636682009-02-17 23:15:12 +00001418Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001419Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001420 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001421 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001422 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001423 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001424
Douglas Gregor40808ce2009-03-09 23:48:35 +00001425 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001426 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001427 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001428
John McCalld5532b62009-11-23 01:53:49 +00001429 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001430 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001431
1432 if (Result.isNull())
1433 return true;
1434
John McCalla93c9342009-12-07 02:54:59 +00001435 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001436 TemplateSpecializationTypeLoc TL
1437 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1438 TL.setTemplateNameLoc(TemplateLoc);
1439 TL.setLAngleLoc(LAngleLoc);
1440 TL.setRAngleLoc(RAngleLoc);
1441 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1442 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1443
1444 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCall6b2becf2009-09-08 17:47:29 +00001445}
John McCallf1bbbb42009-09-04 01:14:41 +00001446
John McCall6b2becf2009-09-08 17:47:29 +00001447Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1448 TagUseKind TUK,
1449 DeclSpec::TST TagSpec,
1450 SourceLocation TagLoc) {
1451 if (TypeResult.isInvalid())
1452 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001453
John McCall833ca992009-10-29 08:12:44 +00001454 // FIXME: preserve source info, ideally without copying the DI.
John McCalla93c9342009-12-07 02:54:59 +00001455 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001456 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001457
John McCall6b2becf2009-09-08 17:47:29 +00001458 // Verify the tag specifier.
1459 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001460
John McCall6b2becf2009-09-08 17:47:29 +00001461 if (const RecordType *RT = Type->getAs<RecordType>()) {
1462 RecordDecl *D = RT->getDecl();
1463
1464 IdentifierInfo *Id = D->getIdentifier();
1465 assert(Id && "templated class must have an identifier");
1466
1467 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1468 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001469 << Type
John McCall6b2becf2009-09-08 17:47:29 +00001470 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1471 D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001472 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001473 }
1474 }
1475
John McCall6b2becf2009-09-08 17:47:29 +00001476 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1477
1478 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001479}
1480
John McCallf7a1a742009-11-24 19:00:30 +00001481Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1482 LookupResult &R,
1483 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001484 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001485 // FIXME: Can we do any checking at this point? I guess we could check the
1486 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001487 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001488 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001489
1490 // These should be filtered out by our callers.
1491 assert(!R.empty() && "empty lookup results when building templateid");
1492 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1493
1494 NestedNameSpecifier *Qualifier = 0;
1495 SourceRange QualifierRange;
1496 if (SS.isSet()) {
1497 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1498 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001499 }
1500
John McCallf7a1a742009-11-24 19:00:30 +00001501 bool Dependent
1502 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1503 &TemplateArgs);
1504 UnresolvedLookupExpr *ULE
1505 = UnresolvedLookupExpr::Create(Context, Dependent,
1506 Qualifier, QualifierRange,
1507 R.getLookupName(), R.getNameLoc(),
1508 RequiresADL, TemplateArgs);
1509 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1510 ULE->addDecl(*I);
1511
1512 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001513}
1514
John McCallf7a1a742009-11-24 19:00:30 +00001515// We actually only call this from template instantiation.
1516Sema::OwningExprResult
1517Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1518 DeclarationName Name,
1519 SourceLocation NameLoc,
1520 const TemplateArgumentListInfo &TemplateArgs) {
1521 DeclContext *DC;
1522 if (!(DC = computeDeclContext(SS, false)) ||
1523 DC->isDependentContext() ||
1524 RequireCompleteDeclContext(SS))
1525 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001526
John McCallf7a1a742009-11-24 19:00:30 +00001527 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1528 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00001529
John McCallf7a1a742009-11-24 19:00:30 +00001530 if (R.isAmbiguous())
1531 return ExprError();
1532
1533 if (R.empty()) {
1534 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1535 << Name << SS.getRange();
1536 return ExprError();
1537 }
1538
1539 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1540 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1541 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1542 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1543 return ExprError();
1544 }
1545
1546 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001547}
1548
Douglas Gregorc45c2322009-03-31 00:43:58 +00001549/// \brief Form a dependent template name.
1550///
1551/// This action forms a dependent template name given the template
1552/// name and its (presumably dependent) scope specifier. For
1553/// example, given "MetaFun::template apply", the scope specifier \p
1554/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1555/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump1eb44332009-09-09 15:08:12 +00001556Sema::TemplateTy
Douglas Gregorc45c2322009-03-31 00:43:58 +00001557Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001558 const CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +00001559 UnqualifiedId &Name,
Douglas Gregora481edb2009-11-20 23:39:24 +00001560 TypeTy *ObjectType,
1561 bool EnteringContext) {
Mike Stump1eb44332009-09-09 15:08:12 +00001562 if ((ObjectType &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001563 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
Douglas Gregora481edb2009-11-20 23:39:24 +00001564 (SS.isSet() && computeDeclContext(SS, EnteringContext))) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001565 // C++0x [temp.names]p5:
1566 // If a name prefixed by the keyword template is not the name of
1567 // a template, the program is ill-formed. [Note: the keyword
1568 // template may not be applied to non-template members of class
1569 // templates. -end note ] [ Note: as is the case with the
1570 // typename prefix, the template prefix is allowed in cases
1571 // where it is not strictly necessary; i.e., when the
1572 // nested-name-specifier or the expression on the left of the ->
1573 // or . is not dependent on a template-parameter, or the use
1574 // does not appear in the scope of a template. -end note]
1575 //
1576 // Note: C++03 was more strict here, because it banned the use of
1577 // the "template" keyword prior to a template-name that was not a
1578 // dependent name. C++ DR468 relaxed this requirement (the
1579 // "template" keyword is now permitted). We follow the C++0x
1580 // rules, even in C++03 mode, retroactively applying the DR.
1581 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001582 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregora481edb2009-11-20 23:39:24 +00001583 EnteringContext, Template);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001584 if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001585 Diag(Name.getSourceRange().getBegin(),
1586 diag::err_template_kw_refers_to_non_template)
1587 << GetNameFromUnqualifiedId(Name)
1588 << Name.getSourceRange();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001589 return TemplateTy();
1590 }
1591
1592 return Template;
1593 }
1594
Mike Stump1eb44332009-09-09 15:08:12 +00001595 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001596 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001597
1598 switch (Name.getKind()) {
1599 case UnqualifiedId::IK_Identifier:
1600 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1601 Name.Identifier));
1602
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001603 case UnqualifiedId::IK_OperatorFunctionId:
1604 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1605 Name.OperatorFunctionId.Operator));
Sean Hunte6252d12009-11-28 08:58:14 +00001606
1607 case UnqualifiedId::IK_LiteralOperatorId:
1608 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1609
Douglas Gregor014e88d2009-11-03 23:16:33 +00001610 default:
1611 break;
1612 }
1613
1614 Diag(Name.getSourceRange().getBegin(),
1615 diag::err_template_kw_refers_to_non_template)
1616 << GetNameFromUnqualifiedId(Name)
1617 << Name.getSourceRange();
1618 return TemplateTy();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001619}
1620
Mike Stump1eb44332009-09-09 15:08:12 +00001621bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001622 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001623 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001624 const TemplateArgument &Arg = AL.getArgument();
1625
Anders Carlsson436b1562009-06-13 00:33:33 +00001626 // Check template type parameter.
1627 if (Arg.getKind() != TemplateArgument::Type) {
1628 // C++ [temp.arg.type]p1:
1629 // A template-argument for a template-parameter which is a
1630 // type shall be a type-id.
1631
1632 // We have a template type parameter but the template argument
1633 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001634 SourceRange SR = AL.getSourceRange();
1635 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001636 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Anders Carlsson436b1562009-06-13 00:33:33 +00001638 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001639 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001640
John McCalla93c9342009-12-07 02:54:59 +00001641 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001642 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Anders Carlsson436b1562009-06-13 00:33:33 +00001644 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001645 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001646 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001647 return false;
1648}
1649
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001650/// \brief Substitute template arguments into the default template argument for
1651/// the given template type parameter.
1652///
1653/// \param SemaRef the semantic analysis object for which we are performing
1654/// the substitution.
1655///
1656/// \param Template the template that we are synthesizing template arguments
1657/// for.
1658///
1659/// \param TemplateLoc the location of the template name that started the
1660/// template-id we are checking.
1661///
1662/// \param RAngleLoc the location of the right angle bracket ('>') that
1663/// terminates the template-id.
1664///
1665/// \param Param the template template parameter whose default we are
1666/// substituting into.
1667///
1668/// \param Converted the list of template arguments provided for template
1669/// parameters that precede \p Param in the template parameter list.
1670///
1671/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001672static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001673SubstDefaultTemplateArgument(Sema &SemaRef,
1674 TemplateDecl *Template,
1675 SourceLocation TemplateLoc,
1676 SourceLocation RAngleLoc,
1677 TemplateTypeParmDecl *Param,
1678 TemplateArgumentListBuilder &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001679 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001680
1681 // If the argument type is dependent, instantiate it now based
1682 // on the previously-computed template arguments.
1683 if (ArgType->getType()->isDependentType()) {
1684 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1685 /*TakeArgs=*/false);
1686
1687 MultiLevelTemplateArgumentList AllTemplateArgs
1688 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1689
1690 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1691 Template, Converted.getFlatArguments(),
1692 Converted.flatSize(),
1693 SourceRange(TemplateLoc, RAngleLoc));
1694
1695 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1696 Param->getDefaultArgumentLoc(),
1697 Param->getDeclName());
1698 }
1699
1700 return ArgType;
1701}
1702
1703/// \brief Substitute template arguments into the default template argument for
1704/// the given non-type template parameter.
1705///
1706/// \param SemaRef the semantic analysis object for which we are performing
1707/// the substitution.
1708///
1709/// \param Template the template that we are synthesizing template arguments
1710/// for.
1711///
1712/// \param TemplateLoc the location of the template name that started the
1713/// template-id we are checking.
1714///
1715/// \param RAngleLoc the location of the right angle bracket ('>') that
1716/// terminates the template-id.
1717///
Douglas Gregor788cd062009-11-11 01:00:40 +00001718/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001719/// substituting into.
1720///
1721/// \param Converted the list of template arguments provided for template
1722/// parameters that precede \p Param in the template parameter list.
1723///
1724/// \returns the substituted template argument, or NULL if an error occurred.
1725static Sema::OwningExprResult
1726SubstDefaultTemplateArgument(Sema &SemaRef,
1727 TemplateDecl *Template,
1728 SourceLocation TemplateLoc,
1729 SourceLocation RAngleLoc,
1730 NonTypeTemplateParmDecl *Param,
1731 TemplateArgumentListBuilder &Converted) {
1732 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1733 /*TakeArgs=*/false);
1734
1735 MultiLevelTemplateArgumentList AllTemplateArgs
1736 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1737
1738 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1739 Template, Converted.getFlatArguments(),
1740 Converted.flatSize(),
1741 SourceRange(TemplateLoc, RAngleLoc));
1742
1743 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1744}
1745
Douglas Gregor788cd062009-11-11 01:00:40 +00001746/// \brief Substitute template arguments into the default template argument for
1747/// the given template template parameter.
1748///
1749/// \param SemaRef the semantic analysis object for which we are performing
1750/// the substitution.
1751///
1752/// \param Template the template that we are synthesizing template arguments
1753/// for.
1754///
1755/// \param TemplateLoc the location of the template name that started the
1756/// template-id we are checking.
1757///
1758/// \param RAngleLoc the location of the right angle bracket ('>') that
1759/// terminates the template-id.
1760///
1761/// \param Param the template template parameter whose default we are
1762/// substituting into.
1763///
1764/// \param Converted the list of template arguments provided for template
1765/// parameters that precede \p Param in the template parameter list.
1766///
1767/// \returns the substituted template argument, or NULL if an error occurred.
1768static TemplateName
1769SubstDefaultTemplateArgument(Sema &SemaRef,
1770 TemplateDecl *Template,
1771 SourceLocation TemplateLoc,
1772 SourceLocation RAngleLoc,
1773 TemplateTemplateParmDecl *Param,
1774 TemplateArgumentListBuilder &Converted) {
1775 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1776 /*TakeArgs=*/false);
1777
1778 MultiLevelTemplateArgumentList AllTemplateArgs
1779 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1780
1781 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1782 Template, Converted.getFlatArguments(),
1783 Converted.flatSize(),
1784 SourceRange(TemplateLoc, RAngleLoc));
1785
1786 return SemaRef.SubstTemplateName(
1787 Param->getDefaultArgument().getArgument().getAsTemplate(),
1788 Param->getDefaultArgument().getTemplateNameLoc(),
1789 AllTemplateArgs);
1790}
1791
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001792/// \brief If the given template parameter has a default template
1793/// argument, substitute into that default template argument and
1794/// return the corresponding template argument.
1795TemplateArgumentLoc
1796Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1797 SourceLocation TemplateLoc,
1798 SourceLocation RAngleLoc,
1799 Decl *Param,
1800 TemplateArgumentListBuilder &Converted) {
1801 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1802 if (!TypeParm->hasDefaultArgument())
1803 return TemplateArgumentLoc();
1804
John McCalla93c9342009-12-07 02:54:59 +00001805 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001806 TemplateLoc,
1807 RAngleLoc,
1808 TypeParm,
1809 Converted);
1810 if (DI)
1811 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1812
1813 return TemplateArgumentLoc();
1814 }
1815
1816 if (NonTypeTemplateParmDecl *NonTypeParm
1817 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1818 if (!NonTypeParm->hasDefaultArgument())
1819 return TemplateArgumentLoc();
1820
1821 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1822 TemplateLoc,
1823 RAngleLoc,
1824 NonTypeParm,
1825 Converted);
1826 if (Arg.isInvalid())
1827 return TemplateArgumentLoc();
1828
1829 Expr *ArgE = Arg.takeAs<Expr>();
1830 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1831 }
1832
1833 TemplateTemplateParmDecl *TempTempParm
1834 = cast<TemplateTemplateParmDecl>(Param);
1835 if (!TempTempParm->hasDefaultArgument())
1836 return TemplateArgumentLoc();
1837
1838 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1839 TemplateLoc,
1840 RAngleLoc,
1841 TempTempParm,
1842 Converted);
1843 if (TName.isNull())
1844 return TemplateArgumentLoc();
1845
1846 return TemplateArgumentLoc(TemplateArgument(TName),
1847 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1848 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1849}
1850
Douglas Gregore7526412009-11-11 19:31:23 +00001851/// \brief Check that the given template argument corresponds to the given
1852/// template parameter.
1853bool Sema::CheckTemplateArgument(NamedDecl *Param,
1854 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00001855 TemplateDecl *Template,
1856 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00001857 SourceLocation RAngleLoc,
1858 TemplateArgumentListBuilder &Converted) {
Douglas Gregord9e15302009-11-11 19:41:09 +00001859 // Check template type parameters.
1860 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00001861 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00001862
Douglas Gregord9e15302009-11-11 19:41:09 +00001863 // Check non-type template parameters.
1864 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00001865 // Do substitution on the type of the non-type template parameter
1866 // with the template arguments we've seen thus far.
1867 QualType NTTPType = NTTP->getType();
1868 if (NTTPType->isDependentType()) {
1869 // Do substitution on the type of the non-type template parameter.
1870 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1871 NTTP, Converted.getFlatArguments(),
1872 Converted.flatSize(),
1873 SourceRange(TemplateLoc, RAngleLoc));
1874
1875 TemplateArgumentList TemplateArgs(Context, Converted,
1876 /*TakeArgs=*/false);
1877 NTTPType = SubstType(NTTPType,
1878 MultiLevelTemplateArgumentList(TemplateArgs),
1879 NTTP->getLocation(),
1880 NTTP->getDeclName());
1881 // If that worked, check the non-type template parameter type
1882 // for validity.
1883 if (!NTTPType.isNull())
1884 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1885 NTTP->getLocation());
1886 if (NTTPType.isNull())
1887 return true;
1888 }
1889
1890 switch (Arg.getArgument().getKind()) {
1891 case TemplateArgument::Null:
1892 assert(false && "Should never see a NULL template argument here");
1893 return true;
1894
1895 case TemplateArgument::Expression: {
1896 Expr *E = Arg.getArgument().getAsExpr();
1897 TemplateArgument Result;
1898 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1899 return true;
1900
1901 Converted.Append(Result);
1902 break;
1903 }
1904
1905 case TemplateArgument::Declaration:
1906 case TemplateArgument::Integral:
1907 // We've already checked this template argument, so just copy
1908 // it to the list of converted arguments.
1909 Converted.Append(Arg.getArgument());
1910 break;
1911
1912 case TemplateArgument::Template:
1913 // We were given a template template argument. It may not be ill-formed;
1914 // see below.
1915 if (DependentTemplateName *DTN
1916 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1917 // We have a template argument such as \c T::template X, which we
1918 // parsed as a template template argument. However, since we now
1919 // know that we need a non-type template argument, convert this
1920 // template name into an expression.
John McCallf7a1a742009-11-24 19:00:30 +00001921 Expr *E = DependentScopeDeclRefExpr::Create(Context,
1922 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00001923 Arg.getTemplateQualifierRange(),
John McCallf7a1a742009-11-24 19:00:30 +00001924 DTN->getIdentifier(),
1925 Arg.getTemplateNameLoc());
Douglas Gregore7526412009-11-11 19:31:23 +00001926
1927 TemplateArgument Result;
1928 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1929 return true;
1930
1931 Converted.Append(Result);
1932 break;
1933 }
1934
1935 // We have a template argument that actually does refer to a class
1936 // template, template alias, or template template parameter, and
1937 // therefore cannot be a non-type template argument.
1938 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1939 << Arg.getSourceRange();
1940
1941 Diag(Param->getLocation(), diag::note_template_param_here);
1942 return true;
1943
1944 case TemplateArgument::Type: {
1945 // We have a non-type template parameter but the template
1946 // argument is a type.
1947
1948 // C++ [temp.arg]p2:
1949 // In a template-argument, an ambiguity between a type-id and
1950 // an expression is resolved to a type-id, regardless of the
1951 // form of the corresponding template-parameter.
1952 //
1953 // We warn specifically about this case, since it can be rather
1954 // confusing for users.
1955 QualType T = Arg.getArgument().getAsType();
1956 SourceRange SR = Arg.getSourceRange();
1957 if (T->isFunctionType())
1958 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1959 else
1960 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1961 Diag(Param->getLocation(), diag::note_template_param_here);
1962 return true;
1963 }
1964
1965 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001966 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00001967 break;
1968 }
1969
1970 return false;
1971 }
1972
1973
1974 // Check template template parameters.
1975 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
1976
1977 // Substitute into the template parameter list of the template
1978 // template parameter, since previously-supplied template arguments
1979 // may appear within the template template parameter.
1980 {
1981 // Set up a template instantiation context.
1982 LocalInstantiationScope Scope(*this);
1983 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1984 TempParm, Converted.getFlatArguments(),
1985 Converted.flatSize(),
1986 SourceRange(TemplateLoc, RAngleLoc));
1987
1988 TemplateArgumentList TemplateArgs(Context, Converted,
1989 /*TakeArgs=*/false);
1990 TempParm = cast_or_null<TemplateTemplateParmDecl>(
1991 SubstDecl(TempParm, CurContext,
1992 MultiLevelTemplateArgumentList(TemplateArgs)));
1993 if (!TempParm)
1994 return true;
1995
1996 // FIXME: TempParam is leaked.
1997 }
1998
1999 switch (Arg.getArgument().getKind()) {
2000 case TemplateArgument::Null:
2001 assert(false && "Should never see a NULL template argument here");
2002 return true;
2003
2004 case TemplateArgument::Template:
2005 if (CheckTemplateArgument(TempParm, Arg))
2006 return true;
2007
2008 Converted.Append(Arg.getArgument());
2009 break;
2010
2011 case TemplateArgument::Expression:
2012 case TemplateArgument::Type:
2013 // We have a template template parameter but the template
2014 // argument does not refer to a template.
2015 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2016 return true;
2017
2018 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002019 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002020 "Declaration argument with template template parameter");
2021 break;
2022 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002023 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002024 "Integral argument with template template parameter");
2025 break;
2026
2027 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002028 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002029 break;
2030 }
2031
2032 return false;
2033}
2034
Douglas Gregorc15cb382009-02-09 23:23:08 +00002035/// \brief Check that the given template argument list is well-formed
2036/// for specializing the given template.
2037bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2038 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002039 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002040 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002041 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002042 TemplateParameterList *Params = Template->getTemplateParameters();
2043 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002044 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002045 bool Invalid = false;
2046
John McCalld5532b62009-11-23 01:53:49 +00002047 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2048
Mike Stump1eb44332009-09-09 15:08:12 +00002049 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002050 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002052 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002053 (NumArgs < Params->getMinRequiredArguments() &&
2054 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002055 // FIXME: point at either the first arg beyond what we can handle,
2056 // or the '>', depending on whether we have too many or too few
2057 // arguments.
2058 SourceRange Range;
2059 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002060 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002061 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2062 << (NumArgs > NumParams)
2063 << (isa<ClassTemplateDecl>(Template)? 0 :
2064 isa<FunctionTemplateDecl>(Template)? 1 :
2065 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2066 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002067 Diag(Template->getLocation(), diag::note_template_decl_here)
2068 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002069 Invalid = true;
2070 }
Mike Stump1eb44332009-09-09 15:08:12 +00002071
2072 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002073 // [...] The type and form of each template-argument specified in
2074 // a template-id shall match the type and form specified for the
2075 // corresponding parameter declared by the template in its
2076 // template-parameter-list.
2077 unsigned ArgIdx = 0;
2078 for (TemplateParameterList::iterator Param = Params->begin(),
2079 ParamEnd = Params->end();
2080 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002081 if (ArgIdx > NumArgs && PartialTemplateArgs)
2082 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002083
Douglas Gregord9e15302009-11-11 19:41:09 +00002084 // If we have a template parameter pack, check every remaining template
2085 // argument against that template parameter pack.
2086 if ((*Param)->isTemplateParameterPack()) {
2087 Converted.BeginPack();
2088 for (; ArgIdx < NumArgs; ++ArgIdx) {
2089 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2090 TemplateLoc, RAngleLoc, Converted)) {
2091 Invalid = true;
2092 break;
2093 }
2094 }
2095 Converted.EndPack();
2096 continue;
2097 }
2098
Douglas Gregorf35f8282009-11-11 21:54:23 +00002099 if (ArgIdx < NumArgs) {
2100 // Check the template argument we were given.
2101 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2102 TemplateLoc, RAngleLoc, Converted))
2103 return true;
2104
2105 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002106 }
Douglas Gregore7526412009-11-11 19:31:23 +00002107
Douglas Gregorf35f8282009-11-11 21:54:23 +00002108 // We have a default template argument that we will use.
2109 TemplateArgumentLoc Arg;
2110
2111 // Retrieve the default template argument from the template
2112 // parameter. For each kind of template parameter, we substitute the
2113 // template arguments provided thus far and any "outer" template arguments
2114 // (when the template parameter was part of a nested template) into
2115 // the default argument.
2116 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2117 if (!TTP->hasDefaultArgument()) {
2118 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2119 break;
2120 }
2121
John McCalla93c9342009-12-07 02:54:59 +00002122 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002123 Template,
2124 TemplateLoc,
2125 RAngleLoc,
2126 TTP,
2127 Converted);
2128 if (!ArgType)
2129 return true;
2130
2131 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2132 ArgType);
2133 } else if (NonTypeTemplateParmDecl *NTTP
2134 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2135 if (!NTTP->hasDefaultArgument()) {
2136 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2137 break;
2138 }
2139
2140 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2141 TemplateLoc,
2142 RAngleLoc,
2143 NTTP,
2144 Converted);
2145 if (E.isInvalid())
2146 return true;
2147
2148 Expr *Ex = E.takeAs<Expr>();
2149 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2150 } else {
2151 TemplateTemplateParmDecl *TempParm
2152 = cast<TemplateTemplateParmDecl>(*Param);
2153
2154 if (!TempParm->hasDefaultArgument()) {
2155 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2156 break;
2157 }
2158
2159 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2160 TemplateLoc,
2161 RAngleLoc,
2162 TempParm,
2163 Converted);
2164 if (Name.isNull())
2165 return true;
2166
2167 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2168 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2169 TempParm->getDefaultArgument().getTemplateNameLoc());
2170 }
2171
2172 // Introduce an instantiation record that describes where we are using
2173 // the default template argument.
2174 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2175 Converted.getFlatArguments(),
2176 Converted.flatSize(),
2177 SourceRange(TemplateLoc, RAngleLoc));
2178
2179 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002180 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002181 RAngleLoc, Converted))
2182 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002183 }
2184
2185 return Invalid;
2186}
2187
2188/// \brief Check a template argument against its corresponding
2189/// template type parameter.
2190///
2191/// This routine implements the semantics of C++ [temp.arg.type]. It
2192/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002193bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002194 TypeSourceInfo *ArgInfo) {
2195 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002196 QualType Arg = ArgInfo->getType();
2197
Douglas Gregorc15cb382009-02-09 23:23:08 +00002198 // C++ [temp.arg.type]p2:
2199 // A local type, a type with no linkage, an unnamed type or a type
2200 // compounded from any of these types shall not be used as a
2201 // template-argument for a template type-parameter.
2202 //
2203 // FIXME: Perform the recursive and no-linkage type checks.
2204 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00002205 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002206 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00002207 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002208 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00002209 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2210 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2211 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2212 << QualType(Tag, 0) << SR;
2213 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00002214 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall833ca992009-10-29 08:12:44 +00002215 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2216 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002217 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2218 return true;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002219 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2220 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2221 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002222 }
2223
2224 return false;
2225}
2226
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002227/// \brief Checks whether the given template argument is the address
2228/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002229bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2230 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002231 bool Invalid = false;
2232
2233 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002234 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002235 Arg = Cast->getSubExpr();
2236
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002237 // C++0x allows nullptr, and there's no further checking to be done for that.
2238 if (Arg->getType()->isNullPtrType())
2239 return false;
2240
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002241 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002242 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002243 // A template-argument for a non-type, non-template
2244 // template-parameter shall be one of: [...]
2245 //
2246 // -- the address of an object or function with external
2247 // linkage, including function templates and function
2248 // template-ids but excluding non-static class members,
2249 // expressed as & id-expression where the & is optional if
2250 // the name refers to a function or array, or if the
2251 // corresponding template-parameter is a reference; or
2252 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002253
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002254 // Ignore (and complain about) any excess parentheses.
2255 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2256 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002257 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002258 diag::err_template_arg_extra_parens)
2259 << Arg->getSourceRange();
2260 Invalid = true;
2261 }
2262
2263 Arg = Parens->getSubExpr();
2264 }
2265
2266 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2267 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2268 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2269 } else
2270 DRE = dyn_cast<DeclRefExpr>(Arg);
2271
2272 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00002273 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002274 diag::err_template_arg_not_object_or_func_form)
2275 << Arg->getSourceRange();
2276
2277 // Cannot refer to non-static data members
2278 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2279 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2280 << Field << Arg->getSourceRange();
2281
2282 // Cannot refer to non-static member functions
2283 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2284 if (!Method->isStatic())
Mike Stump1eb44332009-09-09 15:08:12 +00002285 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002286 diag::err_template_arg_method)
2287 << Method << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002288
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002289 // Functions must have external linkage.
2290 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregord85b5b92009-11-25 22:24:25 +00002291 if (Func->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump1eb44332009-09-09 15:08:12 +00002292 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002293 diag::err_template_arg_function_not_extern)
2294 << Func << Arg->getSourceRange();
2295 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2296 << true;
2297 return true;
2298 }
2299
2300 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002301 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002302 return Invalid;
2303 }
2304
2305 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregord85b5b92009-11-25 22:24:25 +00002306 if (Var->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump1eb44332009-09-09 15:08:12 +00002307 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002308 diag::err_template_arg_object_not_extern)
2309 << Var << Arg->getSourceRange();
2310 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2311 << true;
2312 return true;
2313 }
2314
2315 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002316 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002317 return Invalid;
2318 }
Mike Stump1eb44332009-09-09 15:08:12 +00002319
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002320 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002321 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002322 diag::err_template_arg_not_object_or_func)
2323 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002324 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002325 diag::note_template_arg_refers_here);
2326 return true;
2327}
2328
2329/// \brief Checks whether the given template argument is a pointer to
2330/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002331bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2332 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002333 bool Invalid = false;
2334
2335 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002336 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002337 Arg = Cast->getSubExpr();
2338
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002339 // C++0x allows nullptr, and there's no further checking to be done for that.
2340 if (Arg->getType()->isNullPtrType())
2341 return false;
2342
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002343 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002344 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002345 // A template-argument for a non-type, non-template
2346 // template-parameter shall be one of: [...]
2347 //
2348 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002349 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002350
2351 // Ignore (and complain about) any excess parentheses.
2352 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2353 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002354 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002355 diag::err_template_arg_extra_parens)
2356 << Arg->getSourceRange();
2357 Invalid = true;
2358 }
2359
2360 Arg = Parens->getSubExpr();
2361 }
2362
Douglas Gregorcaddba02009-11-12 18:38:13 +00002363 // A pointer-to-member constant written &Class::member.
2364 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002365 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2366 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2367 if (DRE && !DRE->getQualifier())
2368 DRE = 0;
2369 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002370 }
2371 // A constant of pointer-to-member type.
2372 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2373 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2374 if (VD->getType()->isMemberPointerType()) {
2375 if (isa<NonTypeTemplateParmDecl>(VD) ||
2376 (isa<VarDecl>(VD) &&
2377 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2378 if (Arg->isTypeDependent() || Arg->isValueDependent())
2379 Converted = TemplateArgument(Arg->Retain());
2380 else
2381 Converted = TemplateArgument(VD->getCanonicalDecl());
2382 return Invalid;
2383 }
2384 }
2385 }
2386
2387 DRE = 0;
2388 }
2389
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002390 if (!DRE)
2391 return Diag(Arg->getSourceRange().getBegin(),
2392 diag::err_template_arg_not_pointer_to_member_form)
2393 << Arg->getSourceRange();
2394
2395 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2396 assert((isa<FieldDecl>(DRE->getDecl()) ||
2397 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2398 "Only non-static member pointers can make it here");
2399
2400 // Okay: this is the address of a non-static member, and therefore
2401 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002402 if (Arg->isTypeDependent() || Arg->isValueDependent())
2403 Converted = TemplateArgument(Arg->Retain());
2404 else
2405 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002406 return Invalid;
2407 }
2408
2409 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002410 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002411 diag::err_template_arg_not_pointer_to_member_form)
2412 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002413 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002414 diag::note_template_arg_refers_here);
2415 return true;
2416}
2417
Douglas Gregorc15cb382009-02-09 23:23:08 +00002418/// \brief Check a template argument against its corresponding
2419/// non-type template parameter.
2420///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002421/// This routine implements the semantics of C++ [temp.arg.nontype].
2422/// It returns true if an error occurred, and false otherwise. \p
2423/// InstantiatedParamType is the type of the non-type template
2424/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002425///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002426/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002427bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002428 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002429 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002430 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2431
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002432 // If either the parameter has a dependent type or the argument is
2433 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002434 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00002435 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2436 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002437 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002438 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002439 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002440
2441 // C++ [temp.arg.nontype]p5:
2442 // The following conversions are performed on each expression used
2443 // as a non-type template-argument. If a non-type
2444 // template-argument cannot be converted to the type of the
2445 // corresponding template-parameter then the program is
2446 // ill-formed.
2447 //
2448 // -- for a non-type template-parameter of integral or
2449 // enumeration type, integral promotions (4.5) and integral
2450 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002451 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002452 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002453 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002454 // C++ [temp.arg.nontype]p1:
2455 // A template-argument for a non-type, non-template
2456 // template-parameter shall be one of:
2457 //
2458 // -- an integral constant-expression of integral or enumeration
2459 // type; or
2460 // -- the name of a non-type template-parameter; or
2461 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002462 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002463 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002464 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002465 diag::err_template_arg_not_integral_or_enumeral)
2466 << ArgType << Arg->getSourceRange();
2467 Diag(Param->getLocation(), diag::note_template_param_here);
2468 return true;
2469 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002470 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002471 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2472 << ArgType << Arg->getSourceRange();
2473 return true;
2474 }
2475
2476 // FIXME: We need some way to more easily get the unqualified form
2477 // of the types without going all the way to the
2478 // canonical type.
2479 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2480 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2481 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2482 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2483
2484 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002485 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002486 // Okay: no conversion necessary
2487 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2488 !ParamType->isEnumeralType()) {
2489 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002490 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002491 } else {
2492 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002493 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002494 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002495 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002496 Diag(Param->getLocation(), diag::note_template_param_here);
2497 return true;
2498 }
2499
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002500 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002501 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002502 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002503
2504 if (!Arg->isValueDependent()) {
2505 // Check that an unsigned parameter does not receive a negative
2506 // value.
2507 if (IntegerType->isUnsignedIntegerType()
2508 && (Value.isSigned() && Value.isNegative())) {
2509 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2510 << Value.toString(10) << Param->getType()
2511 << Arg->getSourceRange();
2512 Diag(Param->getLocation(), diag::note_template_param_here);
2513 return true;
2514 }
2515
2516 // Check that we don't overflow the template parameter type.
2517 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Eli Friedman29f89f62009-12-23 18:44:58 +00002518 unsigned RequiredBits;
2519 if (IntegerType->isUnsignedIntegerType())
2520 RequiredBits = Value.getActiveBits();
2521 else if (Value.isUnsigned())
2522 RequiredBits = Value.getActiveBits() + 1;
2523 else
2524 RequiredBits = Value.getMinSignedBits();
2525 if (RequiredBits > AllowedBits) {
Mike Stump1eb44332009-09-09 15:08:12 +00002526 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002527 diag::err_template_arg_too_large)
2528 << Value.toString(10) << Param->getType()
2529 << Arg->getSourceRange();
2530 Diag(Param->getLocation(), diag::note_template_param_here);
2531 return true;
2532 }
2533
2534 if (Value.getBitWidth() != AllowedBits)
2535 Value.extOrTrunc(AllowedBits);
2536 Value.setIsSigned(IntegerType->isSignedIntegerType());
2537 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002538
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002539 // Add the value of this argument to the list of converted
2540 // arguments. We use the bitwidth and signedness of the template
2541 // parameter.
2542 if (Arg->isValueDependent()) {
2543 // The argument is value-dependent. Create a new
2544 // TemplateArgument with the converted expression.
2545 Converted = TemplateArgument(Arg);
2546 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002547 }
2548
John McCall833ca992009-10-29 08:12:44 +00002549 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002550 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002551 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002552 return false;
2553 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002554
Douglas Gregorb86b0572009-02-11 01:18:59 +00002555 // Handle pointer-to-function, reference-to-function, and
2556 // pointer-to-member-function all in (roughly) the same way.
2557 if (// -- For a non-type template-parameter of type pointer to
2558 // function, only the function-to-pointer conversion (4.3) is
2559 // applied. If the template-argument represents a set of
2560 // overloaded functions (or a pointer to such), the matching
2561 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002562 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002563 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002564 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002565 // -- For a non-type template-parameter of type reference to
2566 // function, no conversions apply. If the template-argument
2567 // represents a set of overloaded functions, the matching
2568 // function is selected from the set (13.4).
2569 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002570 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002571 // -- For a non-type template-parameter of type pointer to
2572 // member function, no conversions apply. If the
2573 // template-argument represents a set of overloaded member
2574 // functions, the matching member function is selected from
2575 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002576 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002577 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002578 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002579 ->isFunctionType())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002580 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002581 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002582 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002583 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2584 ParamType->isMemberPointerType())) {
2585 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002586 if (ParamType->isMemberPointerType())
2587 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2588 else
2589 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002590 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002591 ArgType = Context.getPointerType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002592 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump1eb44332009-09-09 15:08:12 +00002593 } else if (FunctionDecl *Fn
Douglas Gregora35284b2009-02-11 00:19:33 +00002594 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002595 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2596 return true;
2597
Anders Carlsson96ad5332009-10-21 17:16:23 +00002598 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00002599 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002600 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002601 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman73c39ab2009-10-20 08:27:19 +00002602 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregora35284b2009-02-11 00:19:33 +00002603 }
2604 }
2605
Mike Stump1eb44332009-09-09 15:08:12 +00002606 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002607 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002608 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002609 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002610 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002611 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002612 Diag(Param->getLocation(), diag::note_template_param_here);
2613 return true;
2614 }
Mike Stump1eb44332009-09-09 15:08:12 +00002615
Douglas Gregorcaddba02009-11-12 18:38:13 +00002616 if (ParamType->isMemberPointerType())
2617 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump1eb44332009-09-09 15:08:12 +00002618
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002619 NamedDecl *Entity = 0;
2620 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2621 return true;
2622
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002623 if (Entity)
2624 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002625 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002626 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00002627 }
2628
Chris Lattnerfe90de72009-02-20 21:37:53 +00002629 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002630 // -- for a non-type template-parameter of type pointer to
2631 // object, qualification conversions (4.4) and the
2632 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002633 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002634 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002635 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002636
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002637 if (ArgType->isNullPtrType()) {
2638 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002639 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002640 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002641 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002642 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002643 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002644
Douglas Gregorb86b0572009-02-11 01:18:59 +00002645 if (IsQualificationConversion(ArgType, ParamType)) {
2646 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002647 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002648 }
Mike Stump1eb44332009-09-09 15:08:12 +00002649
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002650 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002651 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002652 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002653 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002654 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002655 Diag(Param->getLocation(), diag::note_template_param_here);
2656 return true;
2657 }
Mike Stump1eb44332009-09-09 15:08:12 +00002658
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002659 NamedDecl *Entity = 0;
2660 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2661 return true;
2662
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002663 if (Entity)
2664 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002665 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002666 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002667 }
Mike Stump1eb44332009-09-09 15:08:12 +00002668
Ted Kremenek6217b802009-07-29 21:53:49 +00002669 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002670 // -- For a non-type template-parameter of type reference to
2671 // object, no conversions apply. The type referred to by the
2672 // reference may be more cv-qualified than the (otherwise
2673 // identical) type of the template-argument. The
2674 // template-parameter is bound directly to the
2675 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002676 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002677 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002678
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002679 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002680 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002681 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002682 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002683 << Arg->getSourceRange();
2684 Diag(Param->getLocation(), diag::note_template_param_here);
2685 return true;
2686 }
2687
Mike Stump1eb44332009-09-09 15:08:12 +00002688 unsigned ParamQuals
Douglas Gregorb86b0572009-02-11 01:18:59 +00002689 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2690 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00002691
Douglas Gregorb86b0572009-02-11 01:18:59 +00002692 if ((ParamQuals | ArgQuals) != ParamQuals) {
2693 Diag(Arg->getSourceRange().getBegin(),
2694 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002695 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002696 << Arg->getSourceRange();
2697 Diag(Param->getLocation(), diag::note_template_param_here);
2698 return true;
2699 }
Mike Stump1eb44332009-09-09 15:08:12 +00002700
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002701 NamedDecl *Entity = 0;
2702 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2703 return true;
2704
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002705 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002706 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002707 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002708 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002709
2710 // -- For a non-type template-parameter of type pointer to data
2711 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002712 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00002713 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2714
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002715 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002716 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002717 } else if (ArgType->isNullPtrType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002718 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002719 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002720 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002721 } else {
2722 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002723 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00002724 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002725 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00002726 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002727 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00002728 }
2729
Douglas Gregorcaddba02009-11-12 18:38:13 +00002730 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002731}
2732
2733/// \brief Check a template argument against its corresponding
2734/// template template parameter.
2735///
2736/// This routine implements the semantics of C++ [temp.arg.template].
2737/// It returns true if an error occurred, and false otherwise.
2738bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00002739 const TemplateArgumentLoc &Arg) {
2740 TemplateName Name = Arg.getArgument().getAsTemplate();
2741 TemplateDecl *Template = Name.getAsTemplateDecl();
2742 if (!Template) {
2743 // Any dependent template name is fine.
2744 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2745 return false;
2746 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002747
2748 // C++ [temp.arg.template]p1:
2749 // A template-argument for a template template-parameter shall be
2750 // the name of a class template, expressed as id-expression. Only
2751 // primary class templates are considered when matching the
2752 // template template argument with the corresponding parameter;
2753 // partial specializations are not considered even if their
2754 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002755 //
2756 // Note that we also allow template template parameters here, which
2757 // will happen when we are dealing with, e.g., class template
2758 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00002759 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002760 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002761 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00002762 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00002763 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00002764 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002765 << Template;
2766 }
2767
2768 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2769 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00002770 true,
2771 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00002772 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00002773}
2774
Douglas Gregorddc29e12009-02-06 22:42:48 +00002775/// \brief Determine whether the given template parameter lists are
2776/// equivalent.
2777///
Mike Stump1eb44332009-09-09 15:08:12 +00002778/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00002779/// source code as part of a new template declaration.
2780///
2781/// \param Old The old template parameter list, typically found via
2782/// name lookup of the template declared with this template parameter
2783/// list.
2784///
2785/// \param Complain If true, this routine will produce a diagnostic if
2786/// the template parameter lists are not equivalent.
2787///
Douglas Gregorfb898e12009-11-12 16:20:59 +00002788/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00002789///
2790/// \param TemplateArgLoc If this source location is valid, then we
2791/// are actually checking the template parameter list of a template
2792/// argument (New) against the template parameter list of its
2793/// corresponding template template parameter (Old). We produce
2794/// slightly different diagnostics in this scenario.
2795///
Douglas Gregorddc29e12009-02-06 22:42:48 +00002796/// \returns True if the template parameter lists are equal, false
2797/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002798bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00002799Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2800 TemplateParameterList *Old,
2801 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00002802 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002803 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002804 if (Old->size() != New->size()) {
2805 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002806 unsigned NextDiag = diag::err_template_param_list_different_arity;
2807 if (TemplateArgLoc.isValid()) {
2808 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2809 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00002810 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002811 Diag(New->getTemplateLoc(), NextDiag)
2812 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00002813 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002814 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00002815 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002816 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002817 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2818 }
2819
2820 return false;
2821 }
2822
2823 for (TemplateParameterList::iterator OldParm = Old->begin(),
2824 OldParmEnd = Old->end(), NewParm = New->begin();
2825 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2826 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002827 if (Complain) {
2828 unsigned NextDiag = diag::err_template_param_different_kind;
2829 if (TemplateArgLoc.isValid()) {
2830 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2831 NextDiag = diag::note_template_param_different_kind;
2832 }
2833 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002834 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002835 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002836 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00002837 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00002838 return false;
2839 }
2840
2841 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2842 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00002843 // know we're at the same index).
Mike Stump1eb44332009-09-09 15:08:12 +00002844 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002845 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2846 // The types of non-type template parameters must agree.
2847 NonTypeTemplateParmDecl *NewNTTP
2848 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00002849
2850 // If we are matching a template template argument to a template
2851 // template parameter and one of the non-type template parameter types
2852 // is dependent, then we must wait until template instantiation time
2853 // to actually compare the arguments.
2854 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2855 (OldNTTP->getType()->isDependentType() ||
2856 NewNTTP->getType()->isDependentType()))
2857 continue;
2858
Douglas Gregorddc29e12009-02-06 22:42:48 +00002859 if (Context.getCanonicalType(OldNTTP->getType()) !=
2860 Context.getCanonicalType(NewNTTP->getType())) {
2861 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002862 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2863 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002864 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002865 diag::err_template_arg_template_params_mismatch);
2866 NextDiag = diag::note_template_nontype_parm_different_type;
2867 }
2868 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002869 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00002870 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00002871 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00002872 diag::note_template_nontype_parm_prev_declaration)
2873 << OldNTTP->getType();
2874 }
2875 return false;
2876 }
2877 } else {
2878 // The template parameter lists of template template
2879 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00002880 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00002881 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00002882 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002883 = cast<TemplateTemplateParmDecl>(*OldParm);
2884 TemplateTemplateParmDecl *NewTTP
2885 = cast<TemplateTemplateParmDecl>(*NewParm);
2886 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2887 OldTTP->getTemplateParameters(),
2888 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00002889 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00002890 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002891 return false;
2892 }
2893 }
2894
2895 return true;
2896}
2897
2898/// \brief Check whether a template can be declared within this scope.
2899///
2900/// If the template declaration is valid in this scope, returns
2901/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00002902bool
Douglas Gregor05396e22009-08-25 17:23:04 +00002903Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002904 // Find the nearest enclosing declaration scope.
2905 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2906 (S->getFlags() & Scope::TemplateParamScope) != 0)
2907 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002908
Douglas Gregorddc29e12009-02-06 22:42:48 +00002909 // C++ [temp]p2:
2910 // A template-declaration can appear only as a namespace scope or
2911 // class scope declaration.
2912 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00002913 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2914 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00002915 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00002916 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002917
Eli Friedman1503f772009-07-31 01:43:05 +00002918 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002919 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002920
2921 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2922 return false;
2923
Mike Stump1eb44332009-09-09 15:08:12 +00002924 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002925 diag::err_template_outside_namespace_or_class_scope)
2926 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002927}
Douglas Gregorcc636682009-02-17 23:15:12 +00002928
Douglas Gregord5cb8762009-10-07 00:13:32 +00002929/// \brief Determine what kind of template specialization the given declaration
2930/// is.
2931static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2932 if (!D)
2933 return TSK_Undeclared;
2934
Douglas Gregorf6b11852009-10-08 15:14:33 +00002935 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2936 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00002937 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2938 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002939 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2940 return Var->getTemplateSpecializationKind();
2941
Douglas Gregord5cb8762009-10-07 00:13:32 +00002942 return TSK_Undeclared;
2943}
2944
Douglas Gregor9302da62009-10-14 23:50:59 +00002945/// \brief Check whether a specialization is well-formed in the current
2946/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00002947///
Douglas Gregor9302da62009-10-14 23:50:59 +00002948/// This routine determines whether a template specialization can be declared
2949/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00002950///
2951/// \param S the semantic analysis object for which this check is being
2952/// performed.
2953///
2954/// \param Specialized the entity being specialized or instantiated, which
2955/// may be a kind of template (class template, function template, etc.) or
2956/// a member of a class template (member function, static data member,
2957/// member class).
2958///
2959/// \param PrevDecl the previous declaration of this entity, if any.
2960///
2961/// \param Loc the location of the explicit specialization or instantiation of
2962/// this entity.
2963///
2964/// \param IsPartialSpecialization whether this is a partial specialization of
2965/// a class template.
2966///
Douglas Gregord5cb8762009-10-07 00:13:32 +00002967/// \returns true if there was an error that we cannot recover from, false
2968/// otherwise.
2969static bool CheckTemplateSpecializationScope(Sema &S,
2970 NamedDecl *Specialized,
2971 NamedDecl *PrevDecl,
2972 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00002973 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002974 // Keep these "kind" numbers in sync with the %select statements in the
2975 // various diagnostics emitted by this routine.
2976 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002977 bool isTemplateSpecialization = false;
2978 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002979 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002980 isTemplateSpecialization = true;
2981 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002982 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002983 isTemplateSpecialization = true;
2984 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00002985 EntityKind = 3;
2986 else if (isa<VarDecl>(Specialized))
2987 EntityKind = 4;
2988 else if (isa<RecordDecl>(Specialized))
2989 EntityKind = 5;
2990 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00002991 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2992 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00002993 return true;
2994 }
2995
Douglas Gregor88b70942009-02-25 22:02:03 +00002996 // C++ [temp.expl.spec]p2:
2997 // An explicit specialization shall be declared in the namespace
2998 // of which the template is a member, or, for member templates, in
2999 // the namespace of which the enclosing class or enclosing class
3000 // template is a member. An explicit specialization of a member
3001 // function, member class or static data member of a class
3002 // template shall be declared in the namespace of which the class
3003 // template is a member. Such a declaration may also be a
3004 // definition. If the declaration is not a definition, the
3005 // specialization may be defined later in the name- space in which
3006 // the explicit specialization was declared, or in a namespace
3007 // that encloses the one in which the explicit specialization was
3008 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003009 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3010 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003011 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003012 return true;
3013 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003014
Douglas Gregor0a407472009-10-07 17:30:37 +00003015 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3016 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003017 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003018 return true;
3019 }
3020
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003021 // C++ [temp.class.spec]p6:
3022 // A class template partial specialization may be declared or redeclared
3023 // in any namespace scope in which its definition may be defined (14.5.1
3024 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003025 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003026 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003027 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003028 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003029 if ((!PrevDecl ||
3030 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3031 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3032 // There is no prior declaration of this entity, so this
3033 // specialization must be in the same context as the template
3034 // itself.
3035 if (!DC->Equals(SpecializedContext)) {
3036 if (isa<TranslationUnitDecl>(SpecializedContext))
3037 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3038 << EntityKind << Specialized;
3039 else if (isa<NamespaceDecl>(SpecializedContext))
3040 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3041 << EntityKind << Specialized
3042 << cast<NamedDecl>(SpecializedContext);
3043
3044 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3045 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003046 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003047 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003048
3049 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003050 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003051 // Note that HandleDeclarator() performs this check for explicit
3052 // specializations of function templates, static data members, and member
3053 // functions, so we skip the check here for those kinds of entities.
3054 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003055 // Should we refactor that check, so that it occurs later?
3056 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003057 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3058 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003059 if (isa<TranslationUnitDecl>(SpecializedContext))
3060 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3061 << EntityKind << Specialized;
3062 else if (isa<NamespaceDecl>(SpecializedContext))
3063 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3064 << EntityKind << Specialized
3065 << cast<NamedDecl>(SpecializedContext);
3066
Douglas Gregor9302da62009-10-14 23:50:59 +00003067 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003068 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003069
3070 // FIXME: check for specialization-after-instantiation errors and such.
3071
Douglas Gregor88b70942009-02-25 22:02:03 +00003072 return false;
3073}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003074
Douglas Gregore94866f2009-06-12 21:21:02 +00003075/// \brief Check the non-type template arguments of a class template
3076/// partial specialization according to C++ [temp.class.spec]p9.
3077///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003078/// \param TemplateParams the template parameters of the primary class
3079/// template.
3080///
3081/// \param TemplateArg the template arguments of the class template
3082/// partial specialization.
3083///
3084/// \param MirrorsPrimaryTemplate will be set true if the class
3085/// template partial specialization arguments are identical to the
3086/// implicit template arguments of the primary template. This is not
3087/// necessarily an error (C++0x), and it is left to the caller to diagnose
3088/// this condition when it is an error.
3089///
Douglas Gregore94866f2009-06-12 21:21:02 +00003090/// \returns true if there was an error, false otherwise.
3091bool Sema::CheckClassTemplatePartialSpecializationArgs(
3092 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00003093 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003094 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003095 // FIXME: the interface to this function will have to change to
3096 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003097 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003098
Anders Carlssonfb250522009-06-23 01:26:57 +00003099 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00003100
Douglas Gregore94866f2009-06-12 21:21:02 +00003101 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003102 // Determine whether the template argument list of the partial
3103 // specialization is identical to the implicit argument list of
3104 // the primary template. The caller may need to diagnostic this as
3105 // an error per C++ [temp.class.spec]p9b3.
3106 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003107 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003108 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3109 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003110 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003111 MirrorsPrimaryTemplate = false;
3112 } else if (TemplateTemplateParmDecl *TTP
3113 = dyn_cast<TemplateTemplateParmDecl>(
3114 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003115 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003116 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003117 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003118 if (!ArgDecl ||
3119 ArgDecl->getIndex() != TTP->getIndex() ||
3120 ArgDecl->getDepth() != TTP->getDepth())
3121 MirrorsPrimaryTemplate = false;
3122 }
3123 }
3124
Mike Stump1eb44332009-09-09 15:08:12 +00003125 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003126 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003127 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003128 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003129 }
3130
Anders Carlsson6360be72009-06-13 18:20:51 +00003131 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003132 if (!ArgExpr) {
3133 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003134 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003135 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003136
3137 // C++ [temp.class.spec]p8:
3138 // A non-type argument is non-specialized if it is the name of a
3139 // non-type parameter. All other non-type arguments are
3140 // specialized.
3141 //
3142 // Below, we check the two conditions that only apply to
3143 // specialized non-type arguments, so skip any non-specialized
3144 // arguments.
3145 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003146 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003147 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003148 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003149 (Param->getIndex() != NTTP->getIndex() ||
3150 Param->getDepth() != NTTP->getDepth()))
3151 MirrorsPrimaryTemplate = false;
3152
Douglas Gregore94866f2009-06-12 21:21:02 +00003153 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003154 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003155
3156 // C++ [temp.class.spec]p9:
3157 // Within the argument list of a class template partial
3158 // specialization, the following restrictions apply:
3159 // -- A partially specialized non-type argument expression
3160 // shall not involve a template parameter of the partial
3161 // specialization except when the argument expression is a
3162 // simple identifier.
3163 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003164 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003165 diag::err_dependent_non_type_arg_in_partial_spec)
3166 << ArgExpr->getSourceRange();
3167 return true;
3168 }
3169
3170 // -- The type of a template parameter corresponding to a
3171 // specialized non-type argument shall not be dependent on a
3172 // parameter of the specialization.
3173 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003174 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003175 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3176 << Param->getType()
3177 << ArgExpr->getSourceRange();
3178 Diag(Param->getLocation(), diag::note_template_param_here);
3179 return true;
3180 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003181
3182 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003183 }
3184
3185 return false;
3186}
3187
Douglas Gregor212e81c2009-03-25 00:13:59 +00003188Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003189Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3190 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00003191 SourceLocation KWLoc,
Douglas Gregorcc636682009-02-17 23:15:12 +00003192 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003193 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00003194 SourceLocation TemplateNameLoc,
3195 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00003196 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00003197 SourceLocation RAngleLoc,
3198 AttributeList *Attr,
3199 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003200 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00003201
Douglas Gregorcc636682009-02-17 23:15:12 +00003202 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00003203 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003204 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00003205 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3206
3207 if (!ClassTemplate) {
3208 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3209 << (Name.getAsTemplateDecl() &&
3210 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3211 return true;
3212 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003213
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003214 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003215 bool isPartialSpecialization = false;
3216
Douglas Gregor88b70942009-02-25 22:02:03 +00003217 // Check the validity of the template headers that introduce this
3218 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003219 // FIXME: We probably shouldn't complain about these headers for
3220 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00003221 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00003222 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3223 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003224 TemplateParameterLists.size(),
3225 isExplicitSpecialization);
Douglas Gregor05396e22009-08-25 17:23:04 +00003226 if (TemplateParams && TemplateParams->size() > 0) {
3227 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003228
Douglas Gregor05396e22009-08-25 17:23:04 +00003229 // C++ [temp.class.spec]p10:
3230 // The template parameter list of a specialization shall not
3231 // contain default template argument values.
3232 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3233 Decl *Param = TemplateParams->getParam(I);
3234 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3235 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003236 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003237 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00003238 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003239 }
3240 } else if (NonTypeTemplateParmDecl *NTTP
3241 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3242 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003243 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003244 diag::err_default_arg_in_partial_spec)
3245 << DefArg->getSourceRange();
3246 NTTP->setDefaultArgument(0);
3247 DefArg->Destroy(Context);
3248 }
3249 } else {
3250 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003251 if (TTP->hasDefaultArgument()) {
3252 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003253 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003254 << TTP->getDefaultArgument().getSourceRange();
3255 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003256 }
3257 }
3258 }
Douglas Gregora735b202009-10-13 14:39:41 +00003259 } else if (TemplateParams) {
3260 if (TUK == TUK_Friend)
3261 Diag(KWLoc, diag::err_template_spec_friend)
3262 << CodeModificationHint::CreateRemoval(
3263 SourceRange(TemplateParams->getTemplateLoc(),
3264 TemplateParams->getRAngleLoc()))
3265 << SourceRange(LAngleLoc, RAngleLoc);
3266 else
3267 isExplicitSpecialization = true;
3268 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003269 Diag(KWLoc, diag::err_template_spec_needs_header)
3270 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003271 isExplicitSpecialization = true;
3272 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003273
Douglas Gregorcc636682009-02-17 23:15:12 +00003274 // Check that the specialization uses the same tag kind as the
3275 // original template.
3276 TagDecl::TagKind Kind;
3277 switch (TagSpec) {
3278 default: assert(0 && "Unknown tag type!");
3279 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3280 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3281 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3282 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003283 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003284 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003285 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003286 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003287 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00003288 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003289 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003290 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003291 diag::note_previous_use);
3292 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3293 }
3294
Douglas Gregor40808ce2009-03-09 23:48:35 +00003295 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00003296 TemplateArgumentListInfo TemplateArgs;
3297 TemplateArgs.setLAngleLoc(LAngleLoc);
3298 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00003299 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003300
Douglas Gregorcc636682009-02-17 23:15:12 +00003301 // Check that the template argument list is well-formed for this
3302 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003303 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3304 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00003305 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3306 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003307 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003308
Mike Stump1eb44332009-09-09 15:08:12 +00003309 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003310 ClassTemplate->getTemplateParameters()->size()) &&
3311 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003312
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003313 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003314 // corresponds to these arguments.
3315 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003316 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003317 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003318 if (CheckClassTemplatePartialSpecializationArgs(
3319 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003320 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003321 return true;
3322
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003323 if (MirrorsPrimaryTemplate) {
3324 // C++ [temp.class.spec]p9b3:
3325 //
Mike Stump1eb44332009-09-09 15:08:12 +00003326 // -- The argument list of the specialization shall not be identical
3327 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003328 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003329 << (TUK == TUK_Definition)
Mike Stump1eb44332009-09-09 15:08:12 +00003330 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003331 RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003332 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003333 ClassTemplate->getIdentifier(),
3334 TemplateNameLoc,
3335 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003336 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003337 AS_none);
3338 }
3339
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003340 // FIXME: Diagnose friend partial specializations
3341
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003342 // FIXME: Template parameter list matters, too
Mike Stump1eb44332009-09-09 15:08:12 +00003343 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003344 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003345 Converted.flatSize(),
3346 Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003347 } else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00003348 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003349 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003350 Converted.flatSize(),
3351 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00003352 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003353 ClassTemplateSpecializationDecl *PrevDecl = 0;
3354
3355 if (isPartialSpecialization)
3356 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00003357 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003358 InsertPos);
3359 else
3360 PrevDecl
3361 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003362
3363 ClassTemplateSpecializationDecl *Specialization = 0;
3364
Douglas Gregor88b70942009-02-25 22:02:03 +00003365 // Check whether we can declare a class template specialization in
3366 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003367 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003368 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003369 TemplateNameLoc,
3370 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003371 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003372
Douglas Gregorb88e8882009-07-30 17:40:51 +00003373 // The canonical type
3374 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003375 if (PrevDecl &&
3376 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3377 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003378 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003379 // arguments was referenced but not declared, or we're only
3380 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003381 // declaration node as our own, updating its source location to
3382 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003383 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003384 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003385 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003386 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003387 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003388 // Build the canonical type that describes the converted template
3389 // arguments of the class template partial specialization.
3390 CanonType = Context.getTemplateSpecializationType(
3391 TemplateName(ClassTemplate),
3392 Converted.getFlatArguments(),
3393 Converted.flatSize());
3394
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003395 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003396 ClassTemplatePartialSpecializationDecl *PrevPartial
3397 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00003398 ClassTemplatePartialSpecializationDecl *Partial
3399 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003400 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003401 TemplateNameLoc,
3402 TemplateParams,
3403 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003404 Converted,
John McCalld5532b62009-11-23 01:53:49 +00003405 TemplateArgs,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003406 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003407
3408 if (PrevPartial) {
3409 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3410 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3411 } else {
3412 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3413 }
3414 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003415
Douglas Gregored9c0f92009-10-29 00:04:11 +00003416 // If we are providing an explicit specialization of a member class
3417 // template specialization, make a note of that.
3418 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3419 PrevPartial->setMemberSpecialization();
3420
Douglas Gregor031a5882009-06-13 00:26:55 +00003421 // Check that all of the template parameters of the class template
3422 // partial specialization are deducible from the template
3423 // arguments. If not, this class template partial specialization
3424 // will never be used.
3425 llvm::SmallVector<bool, 8> DeducibleParams;
3426 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003427 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003428 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003429 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003430 unsigned NumNonDeducible = 0;
3431 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3432 if (!DeducibleParams[I])
3433 ++NumNonDeducible;
3434
3435 if (NumNonDeducible) {
3436 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3437 << (NumNonDeducible > 1)
3438 << SourceRange(TemplateNameLoc, RAngleLoc);
3439 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3440 if (!DeducibleParams[I]) {
3441 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3442 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003443 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003444 diag::note_partial_spec_unused_parameter)
3445 << Param->getDeclName();
3446 else
Mike Stump1eb44332009-09-09 15:08:12 +00003447 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003448 diag::note_partial_spec_unused_parameter)
3449 << std::string("<anonymous>");
3450 }
3451 }
3452 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003453 } else {
3454 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003455 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003456 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00003457 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorcc636682009-02-17 23:15:12 +00003458 ClassTemplate->getDeclContext(),
3459 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003460 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003461 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003462 PrevDecl);
3463
3464 if (PrevDecl) {
3465 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3466 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3467 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003468 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00003469 InsertPos);
3470 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00003471
3472 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003473 }
3474
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003475 // C++ [temp.expl.spec]p6:
3476 // If a template, a member template or the member of a class template is
3477 // explicitly specialized then that specialization shall be declared
3478 // before the first use of that specialization that would cause an implicit
3479 // instantiation to take place, in every translation unit in which such a
3480 // use occurs; no diagnostic is required.
3481 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3482 SourceRange Range(TemplateNameLoc, RAngleLoc);
3483 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3484 << Context.getTypeDeclType(Specialization) << Range;
3485
3486 Diag(PrevDecl->getPointOfInstantiation(),
3487 diag::note_instantiation_required_here)
3488 << (PrevDecl->getTemplateSpecializationKind()
3489 != TSK_ImplicitInstantiation);
3490 return true;
3491 }
3492
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003493 // If this is not a friend, note that this is an explicit specialization.
3494 if (TUK != TUK_Friend)
3495 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003496
3497 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003498 if (TUK == TUK_Definition) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003499 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003500 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003501 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003502 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003503 Diag(Def->getLocation(), diag::note_previous_definition);
3504 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003505 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003506 }
3507 }
3508
Douglas Gregorfc705b82009-02-26 22:19:44 +00003509 // Build the fully-sugared type for this class template
3510 // specialization as the user wrote in the specialization
3511 // itself. This means that we'll pretty-print the type retrieved
3512 // from the specialization's declaration the way that the user
3513 // actually wrote the specialization, rather than formatting the
3514 // name based on the "canonical" representation used to store the
3515 // template arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003516 QualType WrittenTy
John McCalld5532b62009-11-23 01:53:49 +00003517 = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003518 if (TUK != TUK_Friend)
3519 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003520 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00003521
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003522 // C++ [temp.expl.spec]p9:
3523 // A template explicit specialization is in the scope of the
3524 // namespace in which the template was defined.
3525 //
3526 // We actually implement this paragraph where we set the semantic
3527 // context (in the creation of the ClassTemplateSpecializationDecl),
3528 // but we also maintain the lexical context where the actual
3529 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00003530 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003531
Douglas Gregorcc636682009-02-17 23:15:12 +00003532 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003533 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00003534 Specialization->startDefinition();
3535
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003536 if (TUK == TUK_Friend) {
3537 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3538 TemplateNameLoc,
3539 WrittenTy.getTypePtr(),
3540 /*FIXME:*/KWLoc);
3541 Friend->setAccess(AS_public);
3542 CurContext->addDecl(Friend);
3543 } else {
3544 // Add the specialization into its lexical context, so that it can
3545 // be seen when iterating through the list of declarations in that
3546 // context. However, specializations are not found by name lookup.
3547 CurContext->addDecl(Specialization);
3548 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003549 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003550}
Douglas Gregord57959a2009-03-27 23:10:48 +00003551
Mike Stump1eb44332009-09-09 15:08:12 +00003552Sema::DeclPtrTy
3553Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00003554 MultiTemplateParamsArg TemplateParameterLists,
3555 Declarator &D) {
3556 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3557}
3558
Mike Stump1eb44332009-09-09 15:08:12 +00003559Sema::DeclPtrTy
3560Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003561 MultiTemplateParamsArg TemplateParameterLists,
3562 Declarator &D) {
3563 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3564 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3565 "Not a function declarator!");
3566 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00003567
Douglas Gregor52591bf2009-06-24 00:54:41 +00003568 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00003569 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00003570 }
Mike Stump1eb44332009-09-09 15:08:12 +00003571
Douglas Gregor52591bf2009-06-24 00:54:41 +00003572 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003573
3574 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003575 move(TemplateParameterLists),
3576 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003577 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003578 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00003579 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00003580 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003581 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3582 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00003583 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00003584}
3585
Douglas Gregor454885e2009-10-15 15:54:05 +00003586/// \brief Diagnose cases where we have an explicit template specialization
3587/// before/after an explicit template instantiation, producing diagnostics
3588/// for those cases where they are required and determining whether the
3589/// new specialization/instantiation will have any effect.
3590///
Douglas Gregor454885e2009-10-15 15:54:05 +00003591/// \param NewLoc the location of the new explicit specialization or
3592/// instantiation.
3593///
3594/// \param NewTSK the kind of the new explicit specialization or instantiation.
3595///
3596/// \param PrevDecl the previous declaration of the entity.
3597///
3598/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3599///
3600/// \param PrevPointOfInstantiation if valid, indicates where the previus
3601/// declaration was instantiated (either implicitly or explicitly).
3602///
3603/// \param SuppressNew will be set to true to indicate that the new
3604/// specialization or instantiation has no effect and should be ignored.
3605///
3606/// \returns true if there was an error that should prevent the introduction of
3607/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00003608bool
3609Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3610 TemplateSpecializationKind NewTSK,
3611 NamedDecl *PrevDecl,
3612 TemplateSpecializationKind PrevTSK,
3613 SourceLocation PrevPointOfInstantiation,
3614 bool &SuppressNew) {
Douglas Gregor454885e2009-10-15 15:54:05 +00003615 SuppressNew = false;
3616
3617 switch (NewTSK) {
3618 case TSK_Undeclared:
3619 case TSK_ImplicitInstantiation:
3620 assert(false && "Don't check implicit instantiations here");
3621 return false;
3622
3623 case TSK_ExplicitSpecialization:
3624 switch (PrevTSK) {
3625 case TSK_Undeclared:
3626 case TSK_ExplicitSpecialization:
3627 // Okay, we're just specializing something that is either already
3628 // explicitly specialized or has merely been mentioned without any
3629 // instantiation.
3630 return false;
3631
3632 case TSK_ImplicitInstantiation:
3633 if (PrevPointOfInstantiation.isInvalid()) {
3634 // The declaration itself has not actually been instantiated, so it is
3635 // still okay to specialize it.
3636 return false;
3637 }
3638 // Fall through
3639
3640 case TSK_ExplicitInstantiationDeclaration:
3641 case TSK_ExplicitInstantiationDefinition:
3642 assert((PrevTSK == TSK_ImplicitInstantiation ||
3643 PrevPointOfInstantiation.isValid()) &&
3644 "Explicit instantiation without point of instantiation?");
3645
3646 // C++ [temp.expl.spec]p6:
3647 // If a template, a member template or the member of a class template
3648 // is explicitly specialized then that specialization shall be declared
3649 // before the first use of that specialization that would cause an
3650 // implicit instantiation to take place, in every translation unit in
3651 // which such a use occurs; no diagnostic is required.
Douglas Gregor0d035142009-10-27 18:42:08 +00003652 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00003653 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003654 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00003655 << (PrevTSK != TSK_ImplicitInstantiation);
3656
3657 return true;
3658 }
3659 break;
3660
3661 case TSK_ExplicitInstantiationDeclaration:
3662 switch (PrevTSK) {
3663 case TSK_ExplicitInstantiationDeclaration:
3664 // This explicit instantiation declaration is redundant (that's okay).
3665 SuppressNew = true;
3666 return false;
3667
3668 case TSK_Undeclared:
3669 case TSK_ImplicitInstantiation:
3670 // We're explicitly instantiating something that may have already been
3671 // implicitly instantiated; that's fine.
3672 return false;
3673
3674 case TSK_ExplicitSpecialization:
3675 // C++0x [temp.explicit]p4:
3676 // For a given set of template parameters, if an explicit instantiation
3677 // of a template appears after a declaration of an explicit
3678 // specialization for that template, the explicit instantiation has no
3679 // effect.
3680 return false;
3681
3682 case TSK_ExplicitInstantiationDefinition:
3683 // C++0x [temp.explicit]p10:
3684 // If an entity is the subject of both an explicit instantiation
3685 // declaration and an explicit instantiation definition in the same
3686 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00003687 Diag(NewLoc,
3688 diag::err_explicit_instantiation_declaration_after_definition);
3689 Diag(PrevPointOfInstantiation,
3690 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00003691 assert(PrevPointOfInstantiation.isValid() &&
3692 "Explicit instantiation without point of instantiation?");
3693 SuppressNew = true;
3694 return false;
3695 }
3696 break;
3697
3698 case TSK_ExplicitInstantiationDefinition:
3699 switch (PrevTSK) {
3700 case TSK_Undeclared:
3701 case TSK_ImplicitInstantiation:
3702 // We're explicitly instantiating something that may have already been
3703 // implicitly instantiated; that's fine.
3704 return false;
3705
3706 case TSK_ExplicitSpecialization:
3707 // C++ DR 259, C++0x [temp.explicit]p4:
3708 // For a given set of template parameters, if an explicit
3709 // instantiation of a template appears after a declaration of
3710 // an explicit specialization for that template, the explicit
3711 // instantiation has no effect.
3712 //
3713 // In C++98/03 mode, we only give an extension warning here, because it
3714 // is not not harmful to try to explicitly instantiate something that
3715 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00003716 if (!getLangOptions().CPlusPlus0x) {
3717 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00003718 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003719 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00003720 diag::note_previous_template_specialization);
3721 }
3722 SuppressNew = true;
3723 return false;
3724
3725 case TSK_ExplicitInstantiationDeclaration:
3726 // We're explicity instantiating a definition for something for which we
3727 // were previously asked to suppress instantiations. That's fine.
3728 return false;
3729
3730 case TSK_ExplicitInstantiationDefinition:
3731 // C++0x [temp.spec]p5:
3732 // For a given template and a given set of template-arguments,
3733 // - an explicit instantiation definition shall appear at most once
3734 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00003735 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00003736 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003737 Diag(PrevPointOfInstantiation,
3738 diag::note_previous_explicit_instantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00003739 SuppressNew = true;
3740 return false;
3741 }
3742 break;
3743 }
3744
3745 assert(false && "Missing specialization/instantiation case?");
3746
3747 return false;
3748}
3749
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003750/// \brief Perform semantic analysis for the given function template
3751/// specialization.
3752///
3753/// This routine performs all of the semantic analysis required for an
3754/// explicit function template specialization. On successful completion,
3755/// the function declaration \p FD will become a function template
3756/// specialization.
3757///
3758/// \param FD the function declaration, which will be updated to become a
3759/// function template specialization.
3760///
3761/// \param HasExplicitTemplateArgs whether any template arguments were
3762/// explicitly provided.
3763///
3764/// \param LAngleLoc the location of the left angle bracket ('<'), if
3765/// template arguments were explicitly provided.
3766///
3767/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3768/// if any.
3769///
3770/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3771/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3772/// true as in, e.g., \c void sort<>(char*, char*);
3773///
3774/// \param RAngleLoc the location of the right angle bracket ('>'), if
3775/// template arguments were explicitly provided.
3776///
3777/// \param PrevDecl the set of declarations that
3778bool
3779Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00003780 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00003781 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003782 // The set of function template specializations that could match this
3783 // explicit function template specialization.
3784 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3785 CandidateSet Candidates;
3786
3787 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall68263142009-11-18 22:49:29 +00003788 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3789 I != E; ++I) {
3790 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3791 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003792 // Only consider templates found within the same semantic lookup scope as
3793 // FD.
3794 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3795 continue;
3796
3797 // C++ [temp.expl.spec]p11:
3798 // A trailing template-argument can be left unspecified in the
3799 // template-id naming an explicit function template specialization
3800 // provided it can be deduced from the function argument type.
3801 // Perform template argument deduction to determine whether we may be
3802 // specializing this template.
3803 // FIXME: It is somewhat wasteful to build
3804 TemplateDeductionInfo Info(Context);
3805 FunctionDecl *Specialization = 0;
3806 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00003807 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003808 FD->getType(),
3809 Specialization,
3810 Info)) {
3811 // FIXME: Template argument deduction failed; record why it failed, so
3812 // that we can provide nifty diagnostics.
3813 (void)TDK;
3814 continue;
3815 }
3816
3817 // Record this candidate.
3818 Candidates.push_back(Specialization);
3819 }
3820 }
3821
Douglas Gregorc5df30f2009-09-26 03:41:46 +00003822 // Find the most specialized function template.
3823 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3824 Candidates.size(),
3825 TPOC_Other,
3826 FD->getLocation(),
3827 PartialDiagnostic(diag::err_function_template_spec_no_match)
3828 << FD->getDeclName(),
3829 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00003830 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorc5df30f2009-09-26 03:41:46 +00003831 PartialDiagnostic(diag::note_function_template_spec_matched));
3832 if (!Specialization)
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003833 return true;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003834
3835 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003836 // If so, we have run afoul of .
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003837
Douglas Gregord5cb8762009-10-07 00:13:32 +00003838 // Check the scope of this explicit specialization.
3839 if (CheckTemplateSpecializationScope(*this,
3840 Specialization->getPrimaryTemplate(),
3841 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003842 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003843 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003844
3845 // C++ [temp.expl.spec]p6:
3846 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00003847 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003848 // before the first use of that specialization that would cause an implicit
3849 // instantiation to take place, in every translation unit in which such a
3850 // use occurs; no diagnostic is required.
3851 FunctionTemplateSpecializationInfo *SpecInfo
3852 = Specialization->getTemplateSpecializationInfo();
3853 assert(SpecInfo && "Function template specialization info missing?");
3854 if (SpecInfo->getPointOfInstantiation().isValid()) {
3855 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3856 << FD;
3857 Diag(SpecInfo->getPointOfInstantiation(),
3858 diag::note_instantiation_required_here)
3859 << (Specialization->getTemplateSpecializationKind()
3860 != TSK_ImplicitInstantiation);
3861 return true;
3862 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003863
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003864 // Mark the prior declaration as an explicit specialization, so that later
3865 // clients know that this is an explicit specialization.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003866 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003867
3868 // Turn the given function declaration into a function template
3869 // specialization, with the template arguments from the previous
3870 // specialization.
3871 FD->setFunctionTemplateSpecialization(Context,
3872 Specialization->getPrimaryTemplate(),
3873 new (Context) TemplateArgumentList(
3874 *Specialization->getTemplateSpecializationArgs()),
3875 /*InsertPos=*/0,
3876 TSK_ExplicitSpecialization);
3877
3878 // The "previous declaration" for this function template specialization is
3879 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00003880 Previous.clear();
3881 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003882 return false;
3883}
3884
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003885/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003886/// specialization.
3887///
3888/// This routine performs all of the semantic analysis required for an
3889/// explicit member function specialization. On successful completion,
3890/// the function declaration \p FD will become a member function
3891/// specialization.
3892///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003893/// \param Member the member declaration, which will be updated to become a
3894/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003895///
John McCall68263142009-11-18 22:49:29 +00003896/// \param Previous the set of declarations, one of which may be specialized
3897/// by this function specialization; the set will be modified to contain the
3898/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003899bool
John McCall68263142009-11-18 22:49:29 +00003900Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003901 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3902
3903 // Try to find the member we are instantiating.
3904 NamedDecl *Instantiation = 0;
3905 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003906 MemberSpecializationInfo *MSInfo = 0;
3907
John McCall68263142009-11-18 22:49:29 +00003908 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003909 // Nowhere to look anyway.
3910 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00003911 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3912 I != E; ++I) {
3913 NamedDecl *D = (*I)->getUnderlyingDecl();
3914 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003915 if (Context.hasSameType(Function->getType(), Method->getType())) {
3916 Instantiation = Method;
3917 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003918 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003919 break;
3920 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003921 }
3922 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003923 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00003924 VarDecl *PrevVar;
3925 if (Previous.isSingleResult() &&
3926 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003927 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00003928 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003929 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003930 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003931 }
3932 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00003933 CXXRecordDecl *PrevRecord;
3934 if (Previous.isSingleResult() &&
3935 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
3936 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003937 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003938 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003939 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003940 }
3941
3942 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003943 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003944 // specializations are always out-of-line, the caller will complain about
3945 // this mismatch later.
3946 return false;
3947 }
3948
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003949 // Make sure that this is a specialization of a member.
3950 if (!InstantiatedFrom) {
3951 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3952 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003953 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3954 return true;
3955 }
3956
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003957 // C++ [temp.expl.spec]p6:
3958 // If a template, a member template or the member of a class template is
3959 // explicitly specialized then that spe- cialization shall be declared
3960 // before the first use of that specialization that would cause an implicit
3961 // instantiation to take place, in every translation unit in which such a
3962 // use occurs; no diagnostic is required.
3963 assert(MSInfo && "Member specialization info missing?");
3964 if (MSInfo->getPointOfInstantiation().isValid()) {
3965 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3966 << Member;
3967 Diag(MSInfo->getPointOfInstantiation(),
3968 diag::note_instantiation_required_here)
3969 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3970 return true;
3971 }
3972
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003973 // Check the scope of this explicit specialization.
3974 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003975 InstantiatedFrom,
3976 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003977 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003978 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00003979
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003980 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00003981 // the original declaration to note that it is an explicit specialization
3982 // (if it was previously an implicit instantiation). This latter step
3983 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003984 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00003985 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3986 if (InstantiationFunction->getTemplateSpecializationKind() ==
3987 TSK_ImplicitInstantiation) {
3988 InstantiationFunction->setTemplateSpecializationKind(
3989 TSK_ExplicitSpecialization);
3990 InstantiationFunction->setLocation(Member->getLocation());
3991 }
3992
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003993 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3994 cast<CXXMethodDecl>(InstantiatedFrom),
3995 TSK_ExplicitSpecialization);
3996 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00003997 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3998 if (InstantiationVar->getTemplateSpecializationKind() ==
3999 TSK_ImplicitInstantiation) {
4000 InstantiationVar->setTemplateSpecializationKind(
4001 TSK_ExplicitSpecialization);
4002 InstantiationVar->setLocation(Member->getLocation());
4003 }
4004
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004005 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4006 cast<VarDecl>(InstantiatedFrom),
4007 TSK_ExplicitSpecialization);
4008 } else {
4009 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004010 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4011 if (InstantiationClass->getTemplateSpecializationKind() ==
4012 TSK_ImplicitInstantiation) {
4013 InstantiationClass->setTemplateSpecializationKind(
4014 TSK_ExplicitSpecialization);
4015 InstantiationClass->setLocation(Member->getLocation());
4016 }
4017
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004018 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004019 cast<CXXRecordDecl>(InstantiatedFrom),
4020 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004021 }
4022
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004023 // Save the caller the trouble of having to figure out which declaration
4024 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004025 Previous.clear();
4026 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004027 return false;
4028}
4029
Douglas Gregor558c0322009-10-14 23:41:34 +00004030/// \brief Check the scope of an explicit instantiation.
4031static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4032 SourceLocation InstLoc,
4033 bool WasQualifiedName) {
4034 DeclContext *ExpectedContext
4035 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4036 DeclContext *CurContext = S.CurContext->getLookupContext();
4037
4038 // C++0x [temp.explicit]p2:
4039 // An explicit instantiation shall appear in an enclosing namespace of its
4040 // template.
4041 //
4042 // This is DR275, which we do not retroactively apply to C++98/03.
4043 if (S.getLangOptions().CPlusPlus0x &&
4044 !CurContext->Encloses(ExpectedContext)) {
4045 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4046 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4047 << D << NS;
4048 else
4049 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4050 << D;
4051 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4052 return;
4053 }
4054
4055 // C++0x [temp.explicit]p2:
4056 // If the name declared in the explicit instantiation is an unqualified
4057 // name, the explicit instantiation shall appear in the namespace where
4058 // its template is declared or, if that namespace is inline (7.3.1), any
4059 // namespace from its enclosing namespace set.
4060 if (WasQualifiedName)
4061 return;
4062
4063 if (CurContext->Equals(ExpectedContext))
4064 return;
4065
4066 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4067 << D << ExpectedContext;
4068 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4069}
4070
4071/// \brief Determine whether the given scope specifier has a template-id in it.
4072static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4073 if (!SS.isSet())
4074 return false;
4075
4076 // C++0x [temp.explicit]p2:
4077 // If the explicit instantiation is for a member function, a member class
4078 // or a static data member of a class template specialization, the name of
4079 // the class template specialization in the qualified-id for the member
4080 // name shall be a simple-template-id.
4081 //
4082 // C++98 has the same restriction, just worded differently.
4083 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4084 NNS; NNS = NNS->getPrefix())
4085 if (Type *T = NNS->getAsType())
4086 if (isa<TemplateSpecializationType>(T))
4087 return true;
4088
4089 return false;
4090}
4091
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004092// Explicit instantiation of a class template specialization
Douglas Gregor45f96552009-09-04 06:33:52 +00004093// FIXME: Implement extern template semantics
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004094Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004095Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004096 SourceLocation ExternLoc,
4097 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004098 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004099 SourceLocation KWLoc,
4100 const CXXScopeSpec &SS,
4101 TemplateTy TemplateD,
4102 SourceLocation TemplateNameLoc,
4103 SourceLocation LAngleLoc,
4104 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004105 SourceLocation RAngleLoc,
4106 AttributeList *Attr) {
4107 // Find the class template we're specializing
4108 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004109 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004110 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4111
4112 // Check that the specialization uses the same tag kind as the
4113 // original template.
4114 TagDecl::TagKind Kind;
4115 switch (TagSpec) {
4116 default: assert(0 && "Unknown tag type!");
4117 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4118 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4119 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4120 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004121 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004122 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004123 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004124 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004125 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00004126 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004127 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004128 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004129 diag::note_previous_use);
4130 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4131 }
4132
Douglas Gregor558c0322009-10-14 23:41:34 +00004133 // C++0x [temp.explicit]p2:
4134 // There are two forms of explicit instantiation: an explicit instantiation
4135 // definition and an explicit instantiation declaration. An explicit
4136 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00004137 TemplateSpecializationKind TSK
4138 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4139 : TSK_ExplicitInstantiationDeclaration;
4140
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004141 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004142 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004143 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004144
4145 // Check that the template argument list is well-formed for this
4146 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00004147 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4148 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00004149 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4150 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004151 return true;
4152
Mike Stump1eb44332009-09-09 15:08:12 +00004153 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004154 ClassTemplate->getTemplateParameters()->size()) &&
4155 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004156
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004157 // Find the class template specialization declaration that
4158 // corresponds to these arguments.
4159 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00004160 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00004161 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00004162 Converted.flatSize(),
4163 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004164 void *InsertPos = 0;
4165 ClassTemplateSpecializationDecl *PrevDecl
4166 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4167
Douglas Gregord5cb8762009-10-07 00:13:32 +00004168 // C++0x [temp.explicit]p2:
4169 // [...] An explicit instantiation shall appear in an enclosing
4170 // namespace of its template. [...]
4171 //
4172 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004173 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4174 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00004175
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004176 ClassTemplateSpecializationDecl *Specialization = 0;
4177
Douglas Gregord78f5982009-11-25 06:01:46 +00004178 bool ReusedDecl = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004179 if (PrevDecl) {
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004180 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004181 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004182 PrevDecl,
4183 PrevDecl->getSpecializationKind(),
4184 PrevDecl->getPointOfInstantiation(),
4185 SuppressNew))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004186 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004187
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004188 if (SuppressNew)
Douglas Gregor52604ab2009-09-11 21:19:12 +00004189 return DeclPtrTy::make(PrevDecl);
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004190
Douglas Gregor52604ab2009-09-11 21:19:12 +00004191 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4192 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4193 // Since the only prior class template specialization with these
4194 // arguments was referenced but not declared, reuse that
4195 // declaration node as our own, updating its source location to
4196 // reflect our new declaration.
4197 Specialization = PrevDecl;
4198 Specialization->setLocation(TemplateNameLoc);
4199 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00004200 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00004201 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004202 }
Douglas Gregor52604ab2009-09-11 21:19:12 +00004203
4204 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004205 // Create a new class template specialization declaration node for
4206 // this explicit specialization.
4207 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00004208 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004209 ClassTemplate->getDeclContext(),
4210 TemplateNameLoc,
4211 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00004212 Converted, PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004213
Douglas Gregor52604ab2009-09-11 21:19:12 +00004214 if (PrevDecl) {
4215 // Remove the previous declaration from the folding set, since we want
4216 // to introduce a new declaration.
4217 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4218 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4219 }
4220
4221 // Insert the new specialization.
4222 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004223 }
4224
4225 // Build the fully-sugared type for this explicit instantiation as
4226 // the user wrote in the explicit instantiation itself. This means
4227 // that we'll pretty-print the type retrieved from the
4228 // specialization's declaration the way that the user actually wrote
4229 // the explicit instantiation, rather than formatting the name based
4230 // on the "canonical" representation used to store the template
4231 // arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004232 QualType WrittenTy
John McCalld5532b62009-11-23 01:53:49 +00004233 = Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004234 Context.getTypeDeclType(Specialization));
4235 Specialization->setTypeAsWritten(WrittenTy);
4236 TemplateArgsIn.release();
4237
Douglas Gregord78f5982009-11-25 06:01:46 +00004238 if (!ReusedDecl) {
4239 // Add the explicit instantiation into its lexical context. However,
4240 // since explicit instantiations are never found by name lookup, we
4241 // just put it into the declaration context directly.
4242 Specialization->setLexicalDeclContext(CurContext);
4243 CurContext->addDecl(Specialization);
4244 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004245
4246 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004247 // A definition of a class template or class member template
4248 // shall be in scope at the point of the explicit instantiation of
4249 // the class template or class member template.
4250 //
4251 // This check comes when we actually try to perform the
4252 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004253 ClassTemplateSpecializationDecl *Def
4254 = cast_or_null<ClassTemplateSpecializationDecl>(
4255 Specialization->getDefinition(Context));
4256 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004257 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor0d035142009-10-27 18:42:08 +00004258
4259 // Instantiate the members of this class template specialization.
4260 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4261 Specialization->getDefinition(Context));
4262 if (Def)
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004263 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004264
4265 return DeclPtrTy::make(Specialization);
4266}
4267
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004268// Explicit instantiation of a member class of a class template.
4269Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004270Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004271 SourceLocation ExternLoc,
4272 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004273 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004274 SourceLocation KWLoc,
4275 const CXXScopeSpec &SS,
4276 IdentifierInfo *Name,
4277 SourceLocation NameLoc,
4278 AttributeList *Attr) {
4279
Douglas Gregor402abb52009-05-28 23:31:59 +00004280 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004281 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00004282 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004283 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00004284 MultiTemplateParamsArg(*this, 0, 0),
4285 Owned, IsDependent);
4286 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4287
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004288 if (!TagD)
4289 return true;
4290
4291 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4292 if (Tag->isEnum()) {
4293 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4294 << Context.getTypeDeclType(Tag);
4295 return true;
4296 }
4297
Douglas Gregord0c87372009-05-27 17:30:49 +00004298 if (Tag->isInvalidDecl())
4299 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004300
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004301 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4302 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4303 if (!Pattern) {
4304 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4305 << Context.getTypeDeclType(Record);
4306 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4307 return true;
4308 }
4309
Douglas Gregor558c0322009-10-14 23:41:34 +00004310 // C++0x [temp.explicit]p2:
4311 // If the explicit instantiation is for a class or member class, the
4312 // elaborated-type-specifier in the declaration shall include a
4313 // simple-template-id.
4314 //
4315 // C++98 has the same restriction, just worded differently.
4316 if (!ScopeSpecifierHasTemplateId(SS))
4317 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4318 << Record << SS.getRange();
4319
4320 // C++0x [temp.explicit]p2:
4321 // There are two forms of explicit instantiation: an explicit instantiation
4322 // definition and an explicit instantiation declaration. An explicit
4323 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004324 TemplateSpecializationKind TSK
4325 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4326 : TSK_ExplicitInstantiationDeclaration;
4327
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004328 // C++0x [temp.explicit]p2:
4329 // [...] An explicit instantiation shall appear in an enclosing
4330 // namespace of its template. [...]
4331 //
4332 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004333 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004334
4335 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004336 CXXRecordDecl *PrevDecl
4337 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4338 if (!PrevDecl && Record->getDefinition(Context))
4339 PrevDecl = Record;
4340 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004341 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4342 bool SuppressNew = false;
4343 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004344 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004345 PrevDecl,
4346 MSInfo->getTemplateSpecializationKind(),
4347 MSInfo->getPointOfInstantiation(),
4348 SuppressNew))
4349 return true;
4350 if (SuppressNew)
4351 return TagD;
4352 }
4353
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004354 CXXRecordDecl *RecordDef
4355 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4356 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004357 // C++ [temp.explicit]p3:
4358 // A definition of a member class of a class template shall be in scope
4359 // at the point of an explicit instantiation of the member class.
4360 CXXRecordDecl *Def
4361 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4362 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004363 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4364 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004365 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4366 << Pattern;
4367 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004368 } else {
4369 if (InstantiateClass(NameLoc, Record, Def,
4370 getTemplateInstantiationArgs(Record),
4371 TSK))
4372 return true;
4373
4374 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4375 if (!RecordDef)
4376 return true;
4377 }
4378 }
4379
4380 // Instantiate all of the members of the class.
4381 InstantiateClassMembers(NameLoc, RecordDef,
4382 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004383
Mike Stump390b4cc2009-05-16 07:39:55 +00004384 // FIXME: We don't have any representation for explicit instantiations of
4385 // member classes. Such a representation is not needed for compilation, but it
4386 // should be available for clients that want to see all of the declarations in
4387 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004388 return TagD;
4389}
4390
Douglas Gregord5a423b2009-09-25 18:43:00 +00004391Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4392 SourceLocation ExternLoc,
4393 SourceLocation TemplateLoc,
4394 Declarator &D) {
4395 // Explicit instantiations always require a name.
4396 DeclarationName Name = GetNameForDeclarator(D);
4397 if (!Name) {
4398 if (!D.isInvalidType())
4399 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4400 diag::err_explicit_instantiation_requires_name)
4401 << D.getDeclSpec().getSourceRange()
4402 << D.getSourceRange();
4403
4404 return true;
4405 }
4406
4407 // The scope passed in may not be a decl scope. Zip up the scope tree until
4408 // we find one that is.
4409 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4410 (S->getFlags() & Scope::TemplateParamScope) != 0)
4411 S = S->getParent();
4412
4413 // Determine the type of the declaration.
4414 QualType R = GetTypeForDeclarator(D, S, 0);
4415 if (R.isNull())
4416 return true;
4417
4418 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4419 // Cannot explicitly instantiate a typedef.
4420 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4421 << Name;
4422 return true;
4423 }
4424
Douglas Gregor663b5a02009-10-14 20:14:33 +00004425 // C++0x [temp.explicit]p1:
4426 // [...] An explicit instantiation of a function template shall not use the
4427 // inline or constexpr specifiers.
4428 // Presumably, this also applies to member functions of class templates as
4429 // well.
4430 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4431 Diag(D.getDeclSpec().getInlineSpecLoc(),
4432 diag::err_explicit_instantiation_inline)
Chris Lattner29d9c1a2009-12-06 17:36:05 +00004433 <<CodeModificationHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00004434
4435 // FIXME: check for constexpr specifier.
4436
Douglas Gregor558c0322009-10-14 23:41:34 +00004437 // C++0x [temp.explicit]p2:
4438 // There are two forms of explicit instantiation: an explicit instantiation
4439 // definition and an explicit instantiation declaration. An explicit
4440 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00004441 TemplateSpecializationKind TSK
4442 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4443 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00004444
John McCalla24dc2e2009-11-17 02:14:36 +00004445 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4446 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004447
4448 if (!R->isFunctionType()) {
4449 // C++ [temp.explicit]p1:
4450 // A [...] static data member of a class template can be explicitly
4451 // instantiated from the member definition associated with its class
4452 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00004453 if (Previous.isAmbiguous())
4454 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004455
John McCall1bcee0a2009-12-02 08:25:40 +00004456 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004457 if (!Prev || !Prev->isStaticDataMember()) {
4458 // We expect to see a data data member here.
4459 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4460 << Name;
4461 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4462 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00004463 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004464 return true;
4465 }
4466
4467 if (!Prev->getInstantiatedFromStaticDataMember()) {
4468 // FIXME: Check for explicit specialization?
4469 Diag(D.getIdentifierLoc(),
4470 diag::err_explicit_instantiation_data_member_not_instantiated)
4471 << Prev;
4472 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4473 // FIXME: Can we provide a note showing where this was declared?
4474 return true;
4475 }
4476
Douglas Gregor558c0322009-10-14 23:41:34 +00004477 // C++0x [temp.explicit]p2:
4478 // If the explicit instantiation is for a member function, a member class
4479 // or a static data member of a class template specialization, the name of
4480 // the class template specialization in the qualified-id for the member
4481 // name shall be a simple-template-id.
4482 //
4483 // C++98 has the same restriction, just worded differently.
4484 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4485 Diag(D.getIdentifierLoc(),
4486 diag::err_explicit_instantiation_without_qualified_id)
4487 << Prev << D.getCXXScopeSpec().getRange();
4488
4489 // Check the scope of this explicit instantiation.
4490 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4491
Douglas Gregor454885e2009-10-15 15:54:05 +00004492 // Verify that it is okay to explicitly instantiate here.
4493 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4494 assert(MSInfo && "Missing static data member specialization info?");
4495 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004496 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00004497 MSInfo->getTemplateSpecializationKind(),
4498 MSInfo->getPointOfInstantiation(),
4499 SuppressNew))
4500 return true;
4501 if (SuppressNew)
4502 return DeclPtrTy();
4503
Douglas Gregord5a423b2009-09-25 18:43:00 +00004504 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004505 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004506 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004507 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4508 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004509
4510 // FIXME: Create an ExplicitInstantiation node?
4511 return DeclPtrTy();
4512 }
4513
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004514 // If the declarator is a template-id, translate the parser's template
4515 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00004516 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00004517 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004518 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4519 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00004520 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4521 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00004522 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4523 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00004524 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00004525 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00004526 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00004527 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00004528 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004529
Douglas Gregord5a423b2009-09-25 18:43:00 +00004530 // C++ [temp.explicit]p1:
4531 // A [...] function [...] can be explicitly instantiated from its template.
4532 // A member function [...] of a class template can be explicitly
4533 // instantiated from the member definition associated with its class
4534 // template.
Douglas Gregord5a423b2009-09-25 18:43:00 +00004535 llvm::SmallVector<FunctionDecl *, 8> Matches;
4536 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4537 P != PEnd; ++P) {
4538 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00004539 if (!HasExplicitTemplateArgs) {
4540 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4541 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4542 Matches.clear();
4543 Matches.push_back(Method);
4544 break;
4545 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00004546 }
4547 }
4548
4549 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4550 if (!FunTmpl)
4551 continue;
4552
4553 TemplateDeductionInfo Info(Context);
4554 FunctionDecl *Specialization = 0;
4555 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004556 = DeduceTemplateArguments(FunTmpl,
4557 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00004558 R, Specialization, Info)) {
4559 // FIXME: Keep track of almost-matches?
4560 (void)TDK;
4561 continue;
4562 }
4563
4564 Matches.push_back(Specialization);
4565 }
4566
4567 // Find the most specialized function template specialization.
4568 FunctionDecl *Specialization
4569 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4570 D.getIdentifierLoc(),
4571 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4572 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4573 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4574
4575 if (!Specialization)
4576 return true;
4577
Douglas Gregor0a897e32009-10-15 17:21:20 +00004578 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00004579 Diag(D.getIdentifierLoc(),
4580 diag::err_explicit_instantiation_member_function_not_instantiated)
4581 << Specialization
4582 << (Specialization->getTemplateSpecializationKind() ==
4583 TSK_ExplicitSpecialization);
4584 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4585 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00004586 }
Douglas Gregor558c0322009-10-14 23:41:34 +00004587
Douglas Gregor0a897e32009-10-15 17:21:20 +00004588 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00004589 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4590 PrevDecl = Specialization;
4591
Douglas Gregor0a897e32009-10-15 17:21:20 +00004592 if (PrevDecl) {
4593 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004594 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00004595 PrevDecl,
4596 PrevDecl->getTemplateSpecializationKind(),
4597 PrevDecl->getPointOfInstantiation(),
4598 SuppressNew))
4599 return true;
4600
4601 // FIXME: We may still want to build some representation of this
4602 // explicit specialization.
4603 if (SuppressNew)
4604 return DeclPtrTy();
4605 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00004606
4607 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00004608
4609 if (TSK == TSK_ExplicitInstantiationDefinition)
4610 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4611 false, /*DefinitionRequired=*/true);
Douglas Gregor0a897e32009-10-15 17:21:20 +00004612
Douglas Gregor558c0322009-10-14 23:41:34 +00004613 // C++0x [temp.explicit]p2:
4614 // If the explicit instantiation is for a member function, a member class
4615 // or a static data member of a class template specialization, the name of
4616 // the class template specialization in the qualified-id for the member
4617 // name shall be a simple-template-id.
4618 //
4619 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004620 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004621 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00004622 D.getCXXScopeSpec().isSet() &&
4623 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4624 Diag(D.getIdentifierLoc(),
4625 diag::err_explicit_instantiation_without_qualified_id)
4626 << Specialization << D.getCXXScopeSpec().getRange();
4627
4628 CheckExplicitInstantiationScope(*this,
4629 FunTmpl? (NamedDecl *)FunTmpl
4630 : Specialization->getInstantiatedFromMemberFunction(),
4631 D.getIdentifierLoc(),
4632 D.getCXXScopeSpec().isSet());
4633
Douglas Gregord5a423b2009-09-25 18:43:00 +00004634 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4635 return DeclPtrTy();
4636}
4637
Douglas Gregord57959a2009-03-27 23:10:48 +00004638Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00004639Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4640 const CXXScopeSpec &SS, IdentifierInfo *Name,
4641 SourceLocation TagLoc, SourceLocation NameLoc) {
4642 // This has to hold, because SS is expected to be defined.
4643 assert(Name && "Expected a name in a dependent tag");
4644
4645 NestedNameSpecifier *NNS
4646 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4647 if (!NNS)
4648 return true;
4649
4650 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4651 if (T.isNull())
4652 return true;
4653
4654 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4655 QualType ElabType = Context.getElaboratedType(T, TagKind);
4656
4657 return ElabType.getAsOpaquePtr();
4658}
4659
4660Sema::TypeResult
Douglas Gregord57959a2009-03-27 23:10:48 +00004661Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4662 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00004663 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00004664 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4665 if (!NNS)
4666 return true;
4667
4668 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00004669 if (T.isNull())
4670 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00004671 return T.getAsOpaquePtr();
4672}
4673
Douglas Gregor17343172009-04-01 00:28:59 +00004674Sema::TypeResult
4675Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4676 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00004677 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004678 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00004679 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +00004680 const TemplateSpecializationType *TemplateId
John McCall183700f2009-09-21 23:43:11 +00004681 = T->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00004682 assert(TemplateId && "Expected a template specialization type");
4683
Douglas Gregor6946baf2009-09-02 13:05:45 +00004684 if (computeDeclContext(SS, false)) {
4685 // If we can compute a declaration context, then the "typename"
4686 // keyword was superfluous. Just build a QualifiedNameType to keep
4687 // track of the nested-name-specifier.
Mike Stump1eb44332009-09-09 15:08:12 +00004688
Douglas Gregor6946baf2009-09-02 13:05:45 +00004689 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4690 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4691 }
Mike Stump1eb44332009-09-09 15:08:12 +00004692
Douglas Gregor6946baf2009-09-02 13:05:45 +00004693 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00004694}
4695
Douglas Gregord57959a2009-03-27 23:10:48 +00004696/// \brief Build the type that describes a C++ typename specifier,
4697/// e.g., "typename T::type".
4698QualType
4699Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4700 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00004701 CXXRecordDecl *CurrentInstantiation = 0;
4702 if (NNS->isDependent()) {
4703 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00004704
Douglas Gregor42af25f2009-05-11 19:58:34 +00004705 // If the nested-name-specifier does not refer to the current
4706 // instantiation, then build a typename type.
4707 if (!CurrentInstantiation)
4708 return Context.getTypenameType(NNS, &II);
Mike Stump1eb44332009-09-09 15:08:12 +00004709
Douglas Gregorde18d122009-09-02 13:12:51 +00004710 // The nested-name-specifier refers to the current instantiation, so the
4711 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump1eb44332009-09-09 15:08:12 +00004712 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorde18d122009-09-02 13:12:51 +00004713 // extraneous "typename" keywords, and we retroactively apply this DR to
4714 // C++03 code.
Douglas Gregor42af25f2009-05-11 19:58:34 +00004715 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004716
Douglas Gregor42af25f2009-05-11 19:58:34 +00004717 DeclContext *Ctx = 0;
4718
4719 if (CurrentInstantiation)
4720 Ctx = CurrentInstantiation;
4721 else {
4722 CXXScopeSpec SS;
4723 SS.setScopeRep(NNS);
4724 SS.setRange(Range);
4725 if (RequireCompleteDeclContext(SS))
4726 return QualType();
4727
4728 Ctx = computeDeclContext(SS);
4729 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004730 assert(Ctx && "No declaration context?");
4731
4732 DeclarationName Name(&II);
John McCalla24dc2e2009-11-17 02:14:36 +00004733 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4734 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00004735 unsigned DiagID = 0;
4736 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00004737 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00004738 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00004739 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00004740 break;
4741
4742 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +00004743 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregord57959a2009-03-27 23:10:48 +00004744 // We found a type. Build a QualifiedNameType, since the
4745 // typename-specifier was just sugar. FIXME: Tell
4746 // QualifiedNameType that it has a "typename" prefix.
4747 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4748 }
4749
4750 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00004751 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00004752 break;
4753
John McCall7ba107a2009-11-18 02:36:19 +00004754 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004755 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00004756 return QualType();
4757
Douglas Gregord57959a2009-03-27 23:10:48 +00004758 case LookupResult::FoundOverloaded:
4759 DiagID = diag::err_typename_nested_not_type;
4760 Referenced = *Result.begin();
4761 break;
4762
John McCall6e247262009-10-10 05:48:19 +00004763 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00004764 return QualType();
4765 }
4766
4767 // If we get here, it's because name lookup did not find a
4768 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor3f093272009-10-13 21:16:44 +00004769 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00004770 if (Referenced)
4771 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4772 << Name;
4773 return QualType();
4774}
Douglas Gregor4a959d82009-08-06 16:20:37 +00004775
4776namespace {
4777 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00004778 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00004779 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00004780 SourceLocation Loc;
4781 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00004782
Douglas Gregor4a959d82009-08-06 16:20:37 +00004783 public:
Mike Stump1eb44332009-09-09 15:08:12 +00004784 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00004785 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00004786 DeclarationName Entity)
4787 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00004788 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00004789
4790 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00004791 /// transformed.
4792 ///
4793 /// For the purposes of type reconstruction, a type has already been
4794 /// transformed if it is NULL or if it is not dependent.
4795 bool AlreadyTransformed(QualType T) {
4796 return T.isNull() || !T->isDependentType();
4797 }
Mike Stump1eb44332009-09-09 15:08:12 +00004798
4799 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00004800 /// rebuilt.
4801 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00004802
Douglas Gregor4a959d82009-08-06 16:20:37 +00004803 /// \brief Returns the name of the entity whose type is being rebuilt.
4804 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00004805
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004806 /// \brief Sets the "base" location and entity when that
4807 /// information is known based on another transformation.
4808 void setBase(SourceLocation Loc, DeclarationName Entity) {
4809 this->Loc = Loc;
4810 this->Entity = Entity;
4811 }
4812
Douglas Gregor4a959d82009-08-06 16:20:37 +00004813 /// \brief Transforms an expression by returning the expression itself
4814 /// (an identity function).
4815 ///
4816 /// FIXME: This is completely unsafe; we will need to actually clone the
4817 /// expressions.
4818 Sema::OwningExprResult TransformExpr(Expr *E) {
4819 return getSema().Owned(E);
4820 }
Mike Stump1eb44332009-09-09 15:08:12 +00004821
Douglas Gregor4a959d82009-08-06 16:20:37 +00004822 /// \brief Transforms a typename type by determining whether the type now
4823 /// refers to a member of the current instantiation, and then
4824 /// type-checking and building a QualifiedNameType (when possible).
John McCalla2becad2009-10-21 00:40:46 +00004825 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor4a959d82009-08-06 16:20:37 +00004826 };
4827}
4828
Mike Stump1eb44332009-09-09 15:08:12 +00004829QualType
John McCalla2becad2009-10-21 00:40:46 +00004830CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4831 TypenameTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00004832 TypenameType *T = TL.getTypePtr();
John McCalla2becad2009-10-21 00:40:46 +00004833
Douglas Gregor4a959d82009-08-06 16:20:37 +00004834 NestedNameSpecifier *NNS
4835 = TransformNestedNameSpecifier(T->getQualifier(),
4836 /*FIXME:*/SourceRange(getBaseLocation()));
4837 if (!NNS)
4838 return QualType();
4839
4840 // If the nested-name-specifier did not change, and we cannot compute the
4841 // context corresponding to the nested-name-specifier, then this
4842 // typename type will not change; exit early.
4843 CXXScopeSpec SS;
4844 SS.setRange(SourceRange(getBaseLocation()));
4845 SS.setScopeRep(NNS);
John McCall833ca992009-10-29 08:12:44 +00004846
4847 QualType Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004848 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall833ca992009-10-29 08:12:44 +00004849 Result = QualType(T, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004850
4851 // Rebuild the typename type, which will probably turn into a
Douglas Gregor4a959d82009-08-06 16:20:37 +00004852 // QualifiedNameType.
John McCall833ca992009-10-29 08:12:44 +00004853 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004854 QualType NewTemplateId
Douglas Gregor4a959d82009-08-06 16:20:37 +00004855 = TransformType(QualType(TemplateId, 0));
4856 if (NewTemplateId.isNull())
4857 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004858
Douglas Gregor4a959d82009-08-06 16:20:37 +00004859 if (NNS == T->getQualifier() &&
4860 NewTemplateId == QualType(TemplateId, 0))
John McCall833ca992009-10-29 08:12:44 +00004861 Result = QualType(T, 0);
4862 else
4863 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4864 } else
4865 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4866 SourceRange(TL.getNameLoc()));
Mike Stump1eb44332009-09-09 15:08:12 +00004867
John McCall833ca992009-10-29 08:12:44 +00004868 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4869 NewTL.setNameLoc(TL.getNameLoc());
4870 return Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004871}
4872
4873/// \brief Rebuilds a type within the context of the current instantiation.
4874///
Mike Stump1eb44332009-09-09 15:08:12 +00004875/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00004876/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00004877/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00004878/// partial specialization thereof). This routine will rebuild that type now
4879/// that we have entered the declarator's scope, which may produce different
4880/// canonical types, e.g.,
4881///
4882/// \code
4883/// template<typename T>
4884/// struct X {
4885/// typedef T* pointer;
4886/// pointer data();
4887/// };
4888///
4889/// template<typename T>
4890/// typename X<T>::pointer X<T>::data() { ... }
4891/// \endcode
4892///
4893/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4894/// since we do not know that we can look into X<T> when we parsed the type.
4895/// This function will rebuild the type, performing the lookup of "pointer"
4896/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4897/// as the canonical type of T*, allowing the return types of the out-of-line
4898/// definition and the declaration to match.
4899QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4900 DeclarationName Name) {
4901 if (T.isNull() || !T->isDependentType())
4902 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00004903
Douglas Gregor4a959d82009-08-06 16:20:37 +00004904 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4905 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00004906}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004907
4908/// \brief Produces a formatted string that describes the binding of
4909/// template parameters to template arguments.
4910std::string
4911Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4912 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004913 // FIXME: For variadic templates, we'll need to get the structured list.
4914 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4915 Args.flat_size());
4916}
4917
4918std::string
4919Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4920 const TemplateArgument *Args,
4921 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004922 std::string Result;
4923
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004924 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004925 return Result;
4926
4927 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004928 if (I >= NumArgs)
4929 break;
4930
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004931 if (I == 0)
4932 Result += "[with ";
4933 else
4934 Result += ", ";
4935
4936 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4937 Result += Id->getName();
4938 } else {
4939 Result += '$';
4940 Result += llvm::utostr(I);
4941 }
4942
4943 Result += " = ";
4944
4945 switch (Args[I].getKind()) {
4946 case TemplateArgument::Null:
4947 Result += "<no value>";
4948 break;
4949
4950 case TemplateArgument::Type: {
4951 std::string TypeStr;
4952 Args[I].getAsType().getAsStringInternal(TypeStr,
4953 Context.PrintingPolicy);
4954 Result += TypeStr;
4955 break;
4956 }
4957
4958 case TemplateArgument::Declaration: {
4959 bool Unnamed = true;
4960 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4961 if (ND->getDeclName()) {
4962 Unnamed = false;
4963 Result += ND->getNameAsString();
4964 }
4965 }
4966
4967 if (Unnamed) {
4968 Result += "<anonymous>";
4969 }
4970 break;
4971 }
4972
Douglas Gregor788cd062009-11-11 01:00:40 +00004973 case TemplateArgument::Template: {
4974 std::string Str;
4975 llvm::raw_string_ostream OS(Str);
4976 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
4977 Result += OS.str();
4978 break;
4979 }
4980
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004981 case TemplateArgument::Integral: {
4982 Result += Args[I].getAsIntegral()->toString(10);
4983 break;
4984 }
4985
4986 case TemplateArgument::Expression: {
4987 assert(false && "No expressions in deduced template arguments!");
4988 Result += "<expression>";
4989 break;
4990 }
4991
4992 case TemplateArgument::Pack:
4993 // FIXME: Format template argument packs
4994 Result += "<template argument pack>";
4995 break;
4996 }
4997 }
4998
4999 Result += ']';
5000 return Result;
5001}