blob: 3dd024309193abaa31f01f5c3c3610efe4c0bf43 [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
John McCallf7a1a742009-11-24 19:00:30 +0000105 LookupResult R(*this, TName, SourceLocation(), LookupOrdinaryName);
106 R.suppressDiagnostics();
107 LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
108 if (R.empty())
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000109 return TNK_Non_template;
110
John McCall0bd6feb2009-12-02 08:04:21 +0000111 TemplateName Template;
112 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000113
John McCall0bd6feb2009-12-02 08:04:21 +0000114 unsigned ResultCount = R.end() - R.begin();
115 if (ResultCount > 1) {
116 // We assume that we'll preserve the qualifier from a function
117 // template name in other ways.
118 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
119 TemplateKind = TNK_Function_template;
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000120 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000121 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
122
123 if (SS.isSet() && !SS.isInvalid()) {
124 NestedNameSpecifier *Qualifier
125 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
126 Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
127 } else {
128 Template = TemplateName(TD);
129 }
130
131 if (isa<FunctionTemplateDecl>(TD))
132 TemplateKind = TNK_Function_template;
133 else {
134 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
135 TemplateKind = TNK_Type_template;
136 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000137 }
Mike Stump1eb44332009-09-09 15:08:12 +0000138
John McCall0bd6feb2009-12-02 08:04:21 +0000139 TemplateResult = TemplateTy::make(Template);
140 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000141}
142
143void Sema::LookupTemplateName(LookupResult &Found,
144 Scope *S, const CXXScopeSpec &SS,
145 QualType ObjectType,
146 bool EnteringContext) {
147 // Determine where to perform name lookup
148 DeclContext *LookupCtx = 0;
149 bool isDependent = false;
150 if (!ObjectType.isNull()) {
151 // This nested-name-specifier occurs in a member access expression, e.g.,
152 // x->B::f, and we are looking into the type of the object.
153 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
154 LookupCtx = computeDeclContext(ObjectType);
155 isDependent = ObjectType->isDependentType();
156 assert((isDependent || !ObjectType->isIncompleteType()) &&
157 "Caller should have completed object type");
158 } else if (SS.isSet()) {
159 // This nested-name-specifier occurs after another nested-name-specifier,
160 // so long into the context associated with the prior nested-name-specifier.
161 LookupCtx = computeDeclContext(SS, EnteringContext);
162 isDependent = isDependentScopeSpecifier(SS);
163
164 // The declaration context must be complete.
165 if (LookupCtx && RequireCompleteDeclContext(SS))
166 return;
167 }
168
169 bool ObjectTypeSearchedInScope = false;
170 if (LookupCtx) {
171 // Perform "qualified" name lookup into the declaration context we
172 // computed, which is either the type of the base of a member access
173 // expression or the declaration context associated with a prior
174 // nested-name-specifier.
175 LookupQualifiedName(Found, LookupCtx);
176
177 if (!ObjectType.isNull() && Found.empty()) {
178 // C++ [basic.lookup.classref]p1:
179 // In a class member access expression (5.2.5), if the . or -> token is
180 // immediately followed by an identifier followed by a <, the
181 // identifier must be looked up to determine whether the < is the
182 // beginning of a template argument list (14.2) or a less-than operator.
183 // The identifier is first looked up in the class of the object
184 // expression. If the identifier is not found, it is then looked up in
185 // the context of the entire postfix-expression and shall name a class
186 // or function template.
187 //
188 // FIXME: When we're instantiating a template, do we actually have to
189 // look in the scope of the template? Seems fishy...
190 if (S) LookupName(Found, S);
191 ObjectTypeSearchedInScope = true;
192 }
193 } else if (isDependent) {
194 // We cannot look into a dependent object type or
195 return;
196 } else {
197 // Perform unqualified name lookup in the current scope.
198 LookupName(Found, S);
199 }
200
201 // FIXME: Cope with ambiguous name-lookup results.
202 assert(!Found.isAmbiguous() &&
203 "Cannot handle template name-lookup ambiguities");
204
205 FilterAcceptableTemplateNames(Context, Found);
206 if (Found.empty())
207 return;
208
209 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
210 // C++ [basic.lookup.classref]p1:
211 // [...] If the lookup in the class of the object expression finds a
212 // template, the name is also looked up in the context of the entire
213 // postfix-expression and [...]
214 //
215 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
216 LookupOrdinaryName);
217 LookupName(FoundOuter, S);
218 FilterAcceptableTemplateNames(Context, FoundOuter);
219 // FIXME: Handle ambiguities in this lookup better
220
221 if (FoundOuter.empty()) {
222 // - if the name is not found, the name found in the class of the
223 // object expression is used, otherwise
224 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
225 // - if the name is found in the context of the entire
226 // postfix-expression and does not name a class template, the name
227 // found in the class of the object expression is used, otherwise
228 } else {
229 // - if the name found is a class template, it must refer to the same
230 // entity as the one found in the class of the object expression,
231 // otherwise the program is ill-formed.
232 if (!Found.isSingleResult() ||
233 Found.getFoundDecl()->getCanonicalDecl()
234 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
235 Diag(Found.getNameLoc(),
236 diag::err_nested_name_member_ref_lookup_ambiguous)
237 << Found.getLookupName();
238 Diag(Found.getRepresentativeDecl()->getLocation(),
239 diag::note_ambig_member_ref_object_type)
240 << ObjectType;
241 Diag(FoundOuter.getFoundDecl()->getLocation(),
242 diag::note_ambig_member_ref_scope);
243
244 // Recover by taking the template that we found in the object
245 // expression's type.
246 }
247 }
248 }
249}
250
John McCall2f841ba2009-12-02 03:53:29 +0000251/// ActOnDependentIdExpression - Handle a dependent id-expression that
252/// was just parsed. This is only possible with an explicit scope
253/// specifier naming a dependent type.
John McCallf7a1a742009-11-24 19:00:30 +0000254Sema::OwningExprResult
255Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
256 DeclarationName Name,
257 SourceLocation NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +0000258 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000259 const TemplateArgumentListInfo *TemplateArgs) {
260 NestedNameSpecifier *Qualifier
261 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
262
John McCall2f841ba2009-12-02 03:53:29 +0000263 if (!isAddressOfOperand &&
264 isa<CXXMethodDecl>(CurContext) &&
265 cast<CXXMethodDecl>(CurContext)->isInstance()) {
266 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
267
John McCallf7a1a742009-11-24 19:00:30 +0000268 // Since the 'this' expression is synthesized, we don't need to
269 // perform the double-lookup check.
270 NamedDecl *FirstQualifierInScope = 0;
271
John McCallaa81e162009-12-01 22:10:20 +0000272 return Owned(CXXDependentScopeMemberExpr::Create(Context,
273 /*This*/ 0, ThisType,
274 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000275 /*Op*/ SourceLocation(),
276 Qualifier, SS.getRange(),
277 FirstQualifierInScope,
278 Name, NameLoc,
279 TemplateArgs));
280 }
281
282 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
283}
284
285Sema::OwningExprResult
286Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
287 DeclarationName Name,
288 SourceLocation NameLoc,
289 const TemplateArgumentListInfo *TemplateArgs) {
290 return Owned(DependentScopeDeclRefExpr::Create(Context,
291 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
292 SS.getRange(),
293 Name, NameLoc,
294 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000295}
296
Douglas Gregor72c3f312008-12-05 18:15:24 +0000297/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
298/// that the template parameter 'PrevDecl' is being shadowed by a new
299/// declaration at location Loc. Returns true to indicate that this is
300/// an error, and false otherwise.
301bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000302 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000303
304 // Microsoft Visual C++ permits template parameters to be shadowed.
305 if (getLangOptions().Microsoft)
306 return false;
307
308 // C++ [temp.local]p4:
309 // A template-parameter shall not be redeclared within its
310 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000311 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000312 << cast<NamedDecl>(PrevDecl)->getDeclName();
313 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
314 return true;
315}
316
Douglas Gregor2943aed2009-03-03 04:44:36 +0000317/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000318/// the parameter D to reference the templated declaration and return a pointer
319/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000320TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor13d2d6c2009-10-06 21:27:51 +0000321 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000322 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000323 return Temp;
324 }
325 return 0;
326}
327
Douglas Gregor788cd062009-11-11 01:00:40 +0000328static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
329 const ParsedTemplateArgument &Arg) {
330
331 switch (Arg.getKind()) {
332 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000333 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000334 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
335 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000336 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000337 return TemplateArgumentLoc(TemplateArgument(T), DI);
338 }
339
340 case ParsedTemplateArgument::NonType: {
341 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
342 return TemplateArgumentLoc(TemplateArgument(E), E);
343 }
344
345 case ParsedTemplateArgument::Template: {
346 TemplateName Template
347 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
348 return TemplateArgumentLoc(TemplateArgument(Template),
349 Arg.getScopeSpec().getRange(),
350 Arg.getLocation());
351 }
352 }
353
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000354 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000355 return TemplateArgumentLoc();
356}
357
358/// \brief Translates template arguments as provided by the parser
359/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000360void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
361 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000362 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000363 TemplateArgs.addArgument(translateTemplateArgument(*this,
364 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000365}
366
Douglas Gregor72c3f312008-12-05 18:15:24 +0000367/// ActOnTypeParameter - Called when a C++ template type parameter
368/// (e.g., "typename T") has been parsed. Typename specifies whether
369/// the keyword "typename" was used to declare the type parameter
370/// (otherwise, "class" was used), and KeyLoc is the location of the
371/// "class" or "typename" keyword. ParamName is the name of the
372/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump1eb44332009-09-09 15:08:12 +0000373/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000374/// If the type parameter has a default argument, it will be added
375/// later via ActOnTypeParameterDefault.
Mike Stump1eb44332009-09-09 15:08:12 +0000376Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson941df7d2009-06-12 19:58:00 +0000377 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000378 SourceLocation KeyLoc,
379 IdentifierInfo *ParamName,
380 SourceLocation ParamNameLoc,
381 unsigned Depth, unsigned Position) {
Mike Stump1eb44332009-09-09 15:08:12 +0000382 assert(S->isTemplateParamScope() &&
383 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000384 bool Invalid = false;
385
386 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000387 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000388 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000389 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000390 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000391 }
392
Douglas Gregorddc29e12009-02-06 22:42:48 +0000393 SourceLocation Loc = ParamNameLoc;
394 if (!ParamName)
395 Loc = KeyLoc;
396
Douglas Gregor72c3f312008-12-05 18:15:24 +0000397 TemplateTypeParmDecl *Param
Mike Stump1eb44332009-09-09 15:08:12 +0000398 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
399 Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000400 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000401 if (Invalid)
402 Param->setInvalidDecl();
403
404 if (ParamName) {
405 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000406 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000407 IdResolver.AddDecl(Param);
408 }
409
Chris Lattnerb28317a2009-03-28 19:18:32 +0000410 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000411}
412
Douglas Gregord684b002009-02-10 19:49:53 +0000413/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump1eb44332009-09-09 15:08:12 +0000414/// Default) to the given template type parameter (TypeParam).
415void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000416 SourceLocation EqualLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000417 SourceLocation DefaultLoc,
Douglas Gregord684b002009-02-10 19:49:53 +0000418 TypeTy *DefaultT) {
Mike Stump1eb44332009-09-09 15:08:12 +0000419 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000420 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall833ca992009-10-29 08:12:44 +0000421
John McCalla93c9342009-12-07 02:54:59 +0000422 TypeSourceInfo *DefaultTInfo;
423 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall833ca992009-10-29 08:12:44 +0000424
John McCalla93c9342009-12-07 02:54:59 +0000425 assert(DefaultTInfo && "expected source information for type");
Douglas Gregord684b002009-02-10 19:49:53 +0000426
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000427 // C++0x [temp.param]p9:
428 // A default template-argument may be specified for any kind of
Mike Stump1eb44332009-09-09 15:08:12 +0000429 // template-parameter that is not a template parameter pack.
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000430 if (Parm->isParameterPack()) {
431 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000432 return;
433 }
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Douglas Gregord684b002009-02-10 19:49:53 +0000435 // C++ [temp.param]p14:
436 // A template-parameter shall not be used in its own default argument.
437 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Douglas Gregord684b002009-02-10 19:49:53 +0000439 // Check the template argument itself.
John McCalla93c9342009-12-07 02:54:59 +0000440 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000441 Parm->setInvalidDecl();
442 return;
443 }
444
John McCalla93c9342009-12-07 02:54:59 +0000445 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000446}
447
Douglas Gregor2943aed2009-03-03 04:44:36 +0000448/// \brief Check that the type of a non-type template parameter is
449/// well-formed.
450///
451/// \returns the (possibly-promoted) parameter type if valid;
452/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000453QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000454Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
455 // C++ [temp.param]p4:
456 //
457 // A non-type template-parameter shall have one of the following
458 // (optionally cv-qualified) types:
459 //
460 // -- integral or enumeration type,
461 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000462 // -- pointer to object or pointer to function,
463 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000464 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
465 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000466 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000467 T->isReferenceType() ||
468 // -- pointer to member.
469 T->isMemberPointerType() ||
470 // If T is a dependent type, we can't do the check now, so we
471 // assume that it is well-formed.
472 T->isDependentType())
473 return T;
474 // C++ [temp.param]p8:
475 //
476 // A non-type template-parameter of type "array of T" or
477 // "function returning T" is adjusted to be of type "pointer to
478 // T" or "pointer to function returning T", respectively.
479 else if (T->isArrayType())
480 // FIXME: Keep the type prior to promotion?
481 return Context.getArrayDecayedType(T);
482 else if (T->isFunctionType())
483 // FIXME: Keep the type prior to promotion?
484 return Context.getPointerType(T);
485
486 Diag(Loc, diag::err_template_nontype_parm_bad_type)
487 << T;
488
489 return QualType();
490}
491
Douglas Gregor72c3f312008-12-05 18:15:24 +0000492/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
493/// template parameter (e.g., "int Size" in "template<int Size>
494/// class Array") has been parsed. S is the current scope and D is
495/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000496Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump1eb44332009-09-09 15:08:12 +0000497 unsigned Depth,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000498 unsigned Position) {
John McCalla93c9342009-12-07 02:54:59 +0000499 TypeSourceInfo *TInfo = 0;
500 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000501
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000502 assert(S->isTemplateParamScope() &&
503 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000504 bool Invalid = false;
505
506 IdentifierInfo *ParamName = D.getIdentifier();
507 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000508 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000509 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000510 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000511 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000512 }
513
Douglas Gregor2943aed2009-03-03 04:44:36 +0000514 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000515 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000516 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000517 Invalid = true;
518 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000519
Douglas Gregor72c3f312008-12-05 18:15:24 +0000520 NonTypeTemplateParmDecl *Param
521 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
John McCalla93c9342009-12-07 02:54:59 +0000522 Depth, Position, ParamName, T, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000523 if (Invalid)
524 Param->setInvalidDecl();
525
526 if (D.getIdentifier()) {
527 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000528 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000529 IdResolver.AddDecl(Param);
530 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000531 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000532}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000533
Douglas Gregord684b002009-02-10 19:49:53 +0000534/// \brief Adds a default argument to the given non-type template
535/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000536void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000537 SourceLocation EqualLoc,
538 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000539 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000540 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000541 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Douglas Gregord684b002009-02-10 19:49:53 +0000543 // C++ [temp.param]p14:
544 // A template-parameter shall not be used in its own default argument.
545 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000546
Douglas Gregord684b002009-02-10 19:49:53 +0000547 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000548 TemplateArgument Converted;
549 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
550 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000551 TemplateParm->setInvalidDecl();
552 return;
553 }
554
Anders Carlssone9146f22009-05-01 19:49:17 +0000555 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000556}
557
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000558
559/// ActOnTemplateTemplateParameter - Called when a C++ template template
560/// parameter (e.g. T in template <template <typename> class T> class array)
561/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000562Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
563 SourceLocation TmpLoc,
564 TemplateParamsTy *Params,
565 IdentifierInfo *Name,
566 SourceLocation NameLoc,
567 unsigned Depth,
Mike Stump1eb44332009-09-09 15:08:12 +0000568 unsigned Position) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000569 assert(S->isTemplateParamScope() &&
570 "Template template parameter not in template parameter scope!");
571
572 // Construct the parameter object.
573 TemplateTemplateParmDecl *Param =
574 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
575 Position, Name,
576 (TemplateParameterList*)Params);
577
578 // Make sure the parameter is valid.
579 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
580 // do anything yet. However, if the template parameter list or (eventual)
581 // default value is ever invalidated, that will propagate here.
582 bool Invalid = false;
583 if (Invalid) {
584 Param->setInvalidDecl();
585 }
586
587 // If the tt-param has a name, then link the identifier into the scope
588 // and lookup mechanisms.
589 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000590 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000591 IdResolver.AddDecl(Param);
592 }
593
Chris Lattnerb28317a2009-03-28 19:18:32 +0000594 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000595}
596
Douglas Gregord684b002009-02-10 19:49:53 +0000597/// \brief Adds a default argument to the given template template
598/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000599void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000600 SourceLocation EqualLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +0000601 const ParsedTemplateArgument &Default) {
Mike Stump1eb44332009-09-09 15:08:12 +0000602 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000603 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor788cd062009-11-11 01:00:40 +0000604
Douglas Gregord684b002009-02-10 19:49:53 +0000605 // C++ [temp.param]p14:
606 // A template-parameter shall not be used in its own default argument.
607 // FIXME: Implement this check! Needs a recursive walk over the types.
608
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000609 // Check only that we have a template template argument. We don't want to
610 // try to check well-formedness now, because our template template parameter
611 // might have dependent types in its template parameters, which we wouldn't
612 // be able to match now.
613 //
614 // If none of the template template parameter's template arguments mention
615 // other template parameters, we could actually perform more checking here.
616 // However, it isn't worth doing.
Douglas Gregor788cd062009-11-11 01:00:40 +0000617 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000618 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
619 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
620 << DefaultArg.getSourceRange();
Douglas Gregord684b002009-02-10 19:49:53 +0000621 return;
622 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000623
Douglas Gregor788cd062009-11-11 01:00:40 +0000624 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregord684b002009-02-10 19:49:53 +0000625}
626
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000627/// ActOnTemplateParameterList - Builds a TemplateParameterList that
628/// contains the template parameters in Params/NumParams.
629Sema::TemplateParamsTy *
630Sema::ActOnTemplateParameterList(unsigned Depth,
631 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000632 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000633 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000634 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000635 SourceLocation RAngleLoc) {
636 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000637 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000638
Douglas Gregorddc29e12009-02-06 22:42:48 +0000639 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000640 (NamedDecl**)Params, NumParams,
641 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000642}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000643
Douglas Gregor212e81c2009-03-25 00:13:59 +0000644Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000645Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000646 SourceLocation KWLoc, const CXXScopeSpec &SS,
647 IdentifierInfo *Name, SourceLocation NameLoc,
648 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000649 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000650 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000651 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000652 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000653 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000654 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000655
656 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000657 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000658 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000659
John McCall05b23ea2009-09-14 21:59:20 +0000660 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
661 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000662
663 // There is no such thing as an unnamed class template.
664 if (!Name) {
665 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000666 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000667 }
668
669 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000670 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000671 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000672 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000673 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregorf0510d42009-10-12 23:11:44 +0000674 if (RequireCompleteDeclContext(SS))
675 return true;
676
Douglas Gregor05396e22009-08-25 17:23:04 +0000677 SemanticContext = computeDeclContext(SS, true);
678 if (!SemanticContext) {
679 // FIXME: Produce a reasonable diagnostic here
680 return true;
681 }
Mike Stump1eb44332009-09-09 15:08:12 +0000682
John McCalla24dc2e2009-11-17 02:14:36 +0000683 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000684 } else {
685 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000686 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000687 }
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Douglas Gregorddc29e12009-02-06 22:42:48 +0000689 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
690 NamedDecl *PrevDecl = 0;
691 if (Previous.begin() != Previous.end())
692 PrevDecl = *Previous.begin();
693
Douglas Gregorddc29e12009-02-06 22:42:48 +0000694 // If there is a previous declaration with the same name, check
695 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000696 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000697 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000698
699 // We may have found the injected-class-name of a class template,
700 // class template partial specialization, or class template specialization.
701 // In these cases, grab the template that is being defined or specialized.
702 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
703 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
704 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
705 PrevClassTemplate
706 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
707 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
708 PrevClassTemplate
709 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
710 ->getSpecializedTemplate();
711 }
712 }
713
John McCall65c49462009-12-18 11:25:59 +0000714 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000715 // C++ [namespace.memdef]p3:
716 // [...] When looking for a prior declaration of a class or a function
717 // declared as a friend, and when the name of the friend class or
718 // function is neither a qualified name nor a template-id, scopes outside
719 // the innermost enclosing namespace scope are not considered.
720 DeclContext *OutermostContext = CurContext;
721 while (!OutermostContext->isFileContext())
722 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000723
724 if (PrevDecl &&
725 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
726 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
John McCalle129d442009-12-17 23:21:11 +0000727 SemanticContext = PrevDecl->getDeclContext();
728 } else {
729 // Declarations in outer scopes don't matter. However, the outermost
730 // context we computed is the semantic context for our new
731 // declaration.
732 PrevDecl = PrevClassTemplate = 0;
733 SemanticContext = OutermostContext;
734 }
735
736 if (CurContext->isDependentContext()) {
737 // If this is a dependent context, we don't want to link the friend
738 // class template to the template in scope, because that would perform
739 // checking of the template parameter lists that can't be performed
740 // until the outer context is instantiated.
741 PrevDecl = PrevClassTemplate = 0;
742 }
743 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
744 PrevDecl = PrevClassTemplate = 0;
745
Douglas Gregorddc29e12009-02-06 22:42:48 +0000746 if (PrevClassTemplate) {
747 // Ensure that the template parameter lists are compatible.
748 if (!TemplateParameterListsAreEqual(TemplateParams,
749 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000750 /*Complain=*/true,
751 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000752 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000753
754 // C++ [temp.class]p4:
755 // In a redeclaration, partial specialization, explicit
756 // specialization or explicit instantiation of a class template,
757 // the class-key shall agree in kind with the original class
758 // template declaration (7.1.5.3).
759 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000760 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000761 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000762 << Name
Mike Stump1eb44332009-09-09 15:08:12 +0000763 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +0000764 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000765 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000766 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000767 }
768
Douglas Gregorddc29e12009-02-06 22:42:48 +0000769 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000770 if (TUK == TUK_Definition) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000771 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
772 Diag(NameLoc, diag::err_redefinition) << Name;
773 Diag(Def->getLocation(), diag::note_previous_definition);
774 // FIXME: Would it make sense to try to "forget" the previous
775 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000776 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000777 }
778 }
779 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
780 // Maybe we will complain about the shadowed template parameter.
781 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
782 // Just pretend that we didn't see the previous declaration.
783 PrevDecl = 0;
784 } else if (PrevDecl) {
785 // C++ [temp]p5:
786 // A class template shall not have the same name as any other
787 // template, class, function, object, enumeration, enumerator,
788 // namespace, or type in the same scope (3.3), except as specified
789 // in (14.5.4).
790 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
791 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000792 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000793 }
794
Douglas Gregord684b002009-02-10 19:49:53 +0000795 // Check the template parameter list of this declaration, possibly
796 // merging in the template parameter list from the previous class
797 // template declaration.
798 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000799 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
800 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000801 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Douglas Gregor7da97d02009-05-10 22:57:19 +0000803 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000804 // declaration!
805
Mike Stump1eb44332009-09-09 15:08:12 +0000806 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000807 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000808 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000809 PrevClassTemplate->getTemplatedDecl() : 0,
810 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000811
812 ClassTemplateDecl *NewTemplate
813 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
814 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000815 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000816 NewClass->setDescribedClassTemplate(NewTemplate);
817
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000818 // Build the type for the class template declaration now.
Mike Stump1eb44332009-09-09 15:08:12 +0000819 QualType T =
820 Context.getTypeDeclType(NewClass,
821 PrevClassTemplate?
822 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000823 assert(T->isDependentType() && "Class template type is not dependent?");
824 (void)T;
825
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000826 // If we are providing an explicit specialization of a member that is a
827 // class template, make a note of that.
828 if (PrevClassTemplate &&
829 PrevClassTemplate->getInstantiatedFromMemberTemplate())
830 PrevClassTemplate->setMemberSpecialization();
831
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000832 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000833 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000834 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Douglas Gregorddc29e12009-02-06 22:42:48 +0000836 // Set the lexical context of these templates
837 NewClass->setLexicalDeclContext(CurContext);
838 NewTemplate->setLexicalDeclContext(CurContext);
839
John McCall0f434ec2009-07-31 02:45:11 +0000840 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000841 NewClass->startDefinition();
842
843 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000844 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000845
John McCall05b23ea2009-09-14 21:59:20 +0000846 if (TUK != TUK_Friend)
847 PushOnScopeChains(NewTemplate, S);
848 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000849 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000850 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000851 NewClass->setAccess(PrevClassTemplate->getAccess());
852 }
John McCall05b23ea2009-09-14 21:59:20 +0000853
Douglas Gregord85bea22009-09-26 06:47:28 +0000854 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
855 PrevClassTemplate != NULL);
856
John McCall05b23ea2009-09-14 21:59:20 +0000857 // Friend templates are visible in fairly strange ways.
858 if (!CurContext->isDependentContext()) {
859 DeclContext *DC = SemanticContext->getLookupContext();
860 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
861 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
862 PushOnScopeChains(NewTemplate, EnclosingScope,
863 /* AddToContext = */ false);
864 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000865
866 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
867 NewClass->getLocation(),
868 NewTemplate,
869 /*FIXME:*/NewClass->getLocation());
870 Friend->setAccess(AS_public);
871 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000872 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000873
Douglas Gregord684b002009-02-10 19:49:53 +0000874 if (Invalid) {
875 NewTemplate->setInvalidDecl();
876 NewClass->setInvalidDecl();
877 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000878 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000879}
880
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000881/// \brief Diagnose the presence of a default template argument on a
882/// template parameter, which is ill-formed in certain contexts.
883///
884/// \returns true if the default template argument should be dropped.
885static bool DiagnoseDefaultTemplateArgument(Sema &S,
886 Sema::TemplateParamListContext TPC,
887 SourceLocation ParamLoc,
888 SourceRange DefArgRange) {
889 switch (TPC) {
890 case Sema::TPC_ClassTemplate:
891 return false;
892
893 case Sema::TPC_FunctionTemplate:
894 // C++ [temp.param]p9:
895 // A default template-argument shall not be specified in a
896 // function template declaration or a function template
897 // definition [...]
898 // (This sentence is not in C++0x, per DR226).
899 if (!S.getLangOptions().CPlusPlus0x)
900 S.Diag(ParamLoc,
901 diag::err_template_parameter_default_in_function_template)
902 << DefArgRange;
903 return false;
904
905 case Sema::TPC_ClassTemplateMember:
906 // C++0x [temp.param]p9:
907 // A default template-argument shall not be specified in the
908 // template-parameter-lists of the definition of a member of a
909 // class template that appears outside of the member's class.
910 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
911 << DefArgRange;
912 return true;
913
914 case Sema::TPC_FriendFunctionTemplate:
915 // C++ [temp.param]p9:
916 // A default template-argument shall not be specified in a
917 // friend template declaration.
918 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
919 << DefArgRange;
920 return true;
921
922 // FIXME: C++0x [temp.param]p9 allows default template-arguments
923 // for friend function templates if there is only a single
924 // declaration (and it is a definition). Strange!
925 }
926
927 return false;
928}
929
Douglas Gregord684b002009-02-10 19:49:53 +0000930/// \brief Checks the validity of a template parameter list, possibly
931/// considering the template parameter list from a previous
932/// declaration.
933///
934/// If an "old" template parameter list is provided, it must be
935/// equivalent (per TemplateParameterListsAreEqual) to the "new"
936/// template parameter list.
937///
938/// \param NewParams Template parameter list for a new template
939/// declaration. This template parameter list will be updated with any
940/// default arguments that are carried through from the previous
941/// template parameter list.
942///
943/// \param OldParams If provided, template parameter list from a
944/// previous declaration of the same template. Default template
945/// arguments will be merged from the old template parameter list to
946/// the new template parameter list.
947///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000948/// \param TPC Describes the context in which we are checking the given
949/// template parameter list.
950///
Douglas Gregord684b002009-02-10 19:49:53 +0000951/// \returns true if an error occurred, false otherwise.
952bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000953 TemplateParameterList *OldParams,
954 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +0000955 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Douglas Gregord684b002009-02-10 19:49:53 +0000957 // C++ [temp.param]p10:
958 // The set of default template-arguments available for use with a
959 // template declaration or definition is obtained by merging the
960 // default arguments from the definition (if in scope) and all
961 // declarations in scope in the same way default function
962 // arguments are (8.3.6).
963 bool SawDefaultArgument = false;
964 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000965
Anders Carlsson49d25572009-06-12 23:20:15 +0000966 bool SawParameterPack = false;
967 SourceLocation ParameterPackLoc;
968
Mike Stump1a35fde2009-02-11 23:03:27 +0000969 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000970 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000971 if (OldParams)
972 OldParam = OldParams->begin();
973
974 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
975 NewParamEnd = NewParams->end();
976 NewParam != NewParamEnd; ++NewParam) {
977 // Variables used to diagnose redundant default arguments
978 bool RedundantDefaultArg = false;
979 SourceLocation OldDefaultLoc;
980 SourceLocation NewDefaultLoc;
981
982 // Variables used to diagnose missing default arguments
983 bool MissingDefaultArg = false;
984
Anders Carlsson49d25572009-06-12 23:20:15 +0000985 // C++0x [temp.param]p11:
986 // If a template parameter of a class template is a template parameter pack,
987 // it must be the last template parameter.
988 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +0000989 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +0000990 diag::err_template_param_pack_must_be_last_template_parameter);
991 Invalid = true;
992 }
993
Douglas Gregord684b002009-02-10 19:49:53 +0000994 if (TemplateTypeParmDecl *NewTypeParm
995 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000996 // Check the presence of a default argument here.
997 if (NewTypeParm->hasDefaultArgument() &&
998 DiagnoseDefaultTemplateArgument(*this, TPC,
999 NewTypeParm->getLocation(),
1000 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1001 .getFullSourceRange()))
1002 NewTypeParm->removeDefaultArgument();
1003
1004 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001005 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001006 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Anders Carlsson49d25572009-06-12 23:20:15 +00001008 if (NewTypeParm->isParameterPack()) {
1009 assert(!NewTypeParm->hasDefaultArgument() &&
1010 "Parameter packs can't have a default argument!");
1011 SawParameterPack = true;
1012 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001013 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001014 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001015 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1016 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1017 SawDefaultArgument = true;
1018 RedundantDefaultArg = true;
1019 PreviousDefaultArgLoc = NewDefaultLoc;
1020 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1021 // Merge the default argument from the old declaration to the
1022 // new declaration.
1023 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001024 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001025 true);
1026 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1027 } else if (NewTypeParm->hasDefaultArgument()) {
1028 SawDefaultArgument = true;
1029 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1030 } else if (SawDefaultArgument)
1031 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001032 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001033 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001034 // Check the presence of a default argument here.
1035 if (NewNonTypeParm->hasDefaultArgument() &&
1036 DiagnoseDefaultTemplateArgument(*this, TPC,
1037 NewNonTypeParm->getLocation(),
1038 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1039 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1040 NewNonTypeParm->setDefaultArgument(0);
1041 }
1042
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001043 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001044 NonTypeTemplateParmDecl *OldNonTypeParm
1045 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001046 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001047 NewNonTypeParm->hasDefaultArgument()) {
1048 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1049 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1050 SawDefaultArgument = true;
1051 RedundantDefaultArg = true;
1052 PreviousDefaultArgLoc = NewDefaultLoc;
1053 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1054 // Merge the default argument from the old declaration to the
1055 // new declaration.
1056 SawDefaultArgument = true;
1057 // FIXME: We need to create a new kind of "default argument"
1058 // expression that points to a previous template template
1059 // parameter.
1060 NewNonTypeParm->setDefaultArgument(
1061 OldNonTypeParm->getDefaultArgument());
1062 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1063 } else if (NewNonTypeParm->hasDefaultArgument()) {
1064 SawDefaultArgument = true;
1065 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1066 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001067 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001068 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001069 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001070 TemplateTemplateParmDecl *NewTemplateParm
1071 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001072 if (NewTemplateParm->hasDefaultArgument() &&
1073 DiagnoseDefaultTemplateArgument(*this, TPC,
1074 NewTemplateParm->getLocation(),
1075 NewTemplateParm->getDefaultArgument().getSourceRange()))
1076 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1077
1078 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001079 TemplateTemplateParmDecl *OldTemplateParm
1080 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001081 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001082 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001083 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1084 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001085 SawDefaultArgument = true;
1086 RedundantDefaultArg = true;
1087 PreviousDefaultArgLoc = NewDefaultLoc;
1088 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1089 // Merge the default argument from the old declaration to the
1090 // new declaration.
1091 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001092 // FIXME: We need to create a new kind of "default argument" expression
1093 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001094 NewTemplateParm->setDefaultArgument(
1095 OldTemplateParm->getDefaultArgument());
Douglas Gregor788cd062009-11-11 01:00:40 +00001096 PreviousDefaultArgLoc
1097 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001098 } else if (NewTemplateParm->hasDefaultArgument()) {
1099 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001100 PreviousDefaultArgLoc
1101 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001102 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001103 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001104 }
1105
1106 if (RedundantDefaultArg) {
1107 // C++ [temp.param]p12:
1108 // A template-parameter shall not be given default arguments
1109 // by two different declarations in the same scope.
1110 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1111 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1112 Invalid = true;
1113 } else if (MissingDefaultArg) {
1114 // C++ [temp.param]p11:
1115 // If a template-parameter has a default template-argument,
1116 // all subsequent template-parameters shall have a default
1117 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001118 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001119 diag::err_template_param_default_arg_missing);
1120 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1121 Invalid = true;
1122 }
1123
1124 // If we have an old template parameter list that we're merging
1125 // in, move on to the next parameter.
1126 if (OldParams)
1127 ++OldParam;
1128 }
1129
1130 return Invalid;
1131}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001132
Mike Stump1eb44332009-09-09 15:08:12 +00001133/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001134/// specifier, returning the template parameter list that applies to the
1135/// name.
1136///
1137/// \param DeclStartLoc the start of the declaration that has a scope
1138/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001139///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001140/// \param SS the scope specifier that will be matched to the given template
1141/// parameter lists. This scope specifier precedes a qualified name that is
1142/// being declared.
1143///
1144/// \param ParamLists the template parameter lists, from the outermost to the
1145/// innermost template parameter lists.
1146///
1147/// \param NumParamLists the number of template parameter lists in ParamLists.
1148///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001149/// \param IsExplicitSpecialization will be set true if the entity being
1150/// declared is an explicit specialization, false otherwise.
1151///
Mike Stump1eb44332009-09-09 15:08:12 +00001152/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001153/// name that is preceded by the scope specifier @p SS. This template
1154/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001155/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001156/// template specialization), or may be NULL (if we were's declaring isn't
1157/// itself a template).
1158TemplateParameterList *
1159Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1160 const CXXScopeSpec &SS,
1161 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001162 unsigned NumParamLists,
1163 bool &IsExplicitSpecialization) {
1164 IsExplicitSpecialization = false;
1165
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001166 // Find the template-ids that occur within the nested-name-specifier. These
1167 // template-ids will match up with the template parameter lists.
1168 llvm::SmallVector<const TemplateSpecializationType *, 4>
1169 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001170 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1171 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001172 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1173 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001174 const Type *T = NNS->getAsType();
1175 if (!T) break;
1176
1177 // C++0x [temp.expl.spec]p17:
1178 // A member or a member template may be nested within many
1179 // enclosing class templates. In an explicit specialization for
1180 // such a member, the member declaration shall be preceded by a
1181 // template<> for each enclosing class template that is
1182 // explicitly specialized.
1183 // We interpret this as forbidding typedefs of template
1184 // specializations in the scope specifiers of out-of-line decls.
1185 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) {
1186 const Type *UnderlyingT = TT->LookThroughTypedefs().getTypePtr();
1187 if (isa<TemplateSpecializationType>(UnderlyingT))
1188 // FIXME: better source location information.
1189 Diag(DeclStartLoc, diag::err_typedef_in_def_scope) << QualType(T,0);
1190 T = UnderlyingT;
1191 }
1192
Mike Stump1eb44332009-09-09 15:08:12 +00001193 if (const TemplateSpecializationType *SpecType
John McCall4b2b02b2009-12-15 02:19:47 +00001194 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001195 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1196 if (!Template)
1197 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Ted Kremenek6217b802009-07-29 21:53:49 +00001199 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001200 ClassTemplateSpecializationDecl *SpecDecl
1201 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1202 // If the nested name specifier refers to an explicit specialization,
1203 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001204 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1205 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001206 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001207 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001208 }
Mike Stump1eb44332009-09-09 15:08:12 +00001209
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001210 TemplateIdsInSpecifier.push_back(SpecType);
1211 }
1212 }
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001214 // Reverse the list of template-ids in the scope specifier, so that we can
1215 // more easily match up the template-ids and the template parameter lists.
1216 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001218 SourceLocation FirstTemplateLoc = DeclStartLoc;
1219 if (NumParamLists)
1220 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001222 // Match the template-ids found in the specifier to the template parameter
1223 // lists.
1224 unsigned Idx = 0;
1225 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1226 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001227 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1228 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001229 if (Idx >= NumParamLists) {
1230 // We have a template-id without a corresponding template parameter
1231 // list.
1232 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001233 // FIXME: the location information here isn't great.
1234 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001235 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001236 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001237 << SS.getRange();
1238 } else {
1239 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1240 << SS.getRange()
1241 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1242 "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001243 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001244 }
1245 return 0;
1246 }
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001248 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001249 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001250 TemplateDecl *Template
Douglas Gregorb88e8882009-07-30 17:40:51 +00001251 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1252
Mike Stump1eb44332009-09-09 15:08:12 +00001253 if (ClassTemplateDecl *ClassTemplate
Douglas Gregorb88e8882009-07-30 17:40:51 +00001254 = dyn_cast<ClassTemplateDecl>(Template)) {
1255 TemplateParameterList *ExpectedTemplateParams = 0;
1256 // Is this template-id naming the primary template?
1257 if (Context.hasSameType(TemplateId,
1258 ClassTemplate->getInjectedClassNameType(Context)))
1259 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1260 // ... or a partial specialization?
1261 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1262 = ClassTemplate->findPartialSpecialization(TemplateId))
1263 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1264
1265 if (ExpectedTemplateParams)
Mike Stump1eb44332009-09-09 15:08:12 +00001266 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregorb88e8882009-07-30 17:40:51 +00001267 ExpectedTemplateParams,
Douglas Gregorfb898e12009-11-12 16:20:59 +00001268 true, TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00001269 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001270
1271 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregorb88e8882009-07-30 17:40:51 +00001272 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001273 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001274 diag::err_template_param_list_matches_nontemplate)
1275 << TemplateId
1276 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001277 else
1278 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001279 }
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001281 // If there were at least as many template-ids as there were template
1282 // parameter lists, then there are no template parameter lists remaining for
1283 // the declaration itself.
1284 if (Idx >= NumParamLists)
1285 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001287 // If there were too many template parameter lists, complain about that now.
1288 if (Idx != NumParamLists - 1) {
1289 while (Idx < NumParamLists - 1) {
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001290 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001291 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001292 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1293 : diag::err_template_spec_extra_headers)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001294 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1295 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001296
1297 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1298 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1299 diag::note_explicit_template_spec_does_not_need_header)
1300 << ExplicitSpecializationsInSpecifier.back();
1301 ExplicitSpecializationsInSpecifier.pop_back();
1302 }
1303
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001304 ++Idx;
1305 }
1306 }
Mike Stump1eb44332009-09-09 15:08:12 +00001307
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001308 // Return the last template parameter list, which corresponds to the
1309 // entity being declared.
1310 return ParamLists[NumParamLists - 1];
1311}
1312
Douglas Gregor7532dc62009-03-30 22:58:21 +00001313QualType Sema::CheckTemplateIdType(TemplateName Name,
1314 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001315 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001316 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001317 if (!Template) {
1318 // The template name does not resolve to a template, so we just
1319 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001320 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001321 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001322
Douglas Gregor40808ce2009-03-09 23:48:35 +00001323 // Check that the template argument list is well-formed for this
1324 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001325 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCalld5532b62009-11-23 01:53:49 +00001326 TemplateArgs.size());
1327 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001328 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001329 return QualType();
1330
Mike Stump1eb44332009-09-09 15:08:12 +00001331 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001332 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001333 "Converted template argument list is too short!");
1334
1335 QualType CanonType;
1336
Douglas Gregorcaddba02009-11-12 18:38:13 +00001337 if (Name.isDependent() ||
1338 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001339 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001340 // This class template specialization is a dependent
1341 // type. Therefore, its canonical type is another class template
1342 // specialization type that contains all of the converted
1343 // arguments in canonical form. This ensures that, e.g., A<T> and
1344 // A<T, T> have identical types when A is declared as:
1345 //
1346 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001347 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001348 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001349 Converted.getFlatArguments(),
1350 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Douglas Gregor1275ae02009-07-28 23:00:59 +00001352 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001353 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001354 // In the future, we need to teach getTemplateSpecializationType to only
1355 // build the canonical type and return that to us.
1356 CanonType = Context.getCanonicalType(CanonType);
Mike Stump1eb44332009-09-09 15:08:12 +00001357 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001358 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001359 // Find the class template specialization declaration that
1360 // corresponds to these arguments.
1361 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001362 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001363 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001364 Converted.flatSize(),
1365 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001366 void *InsertPos = 0;
1367 ClassTemplateSpecializationDecl *Decl
1368 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1369 if (!Decl) {
1370 // This is the first time we have referenced this class template
1371 // specialization. Create the canonical declaration and add it to
1372 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001373 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001374 ClassTemplate->getDeclContext(),
John McCall9cc78072009-09-11 07:25:08 +00001375 ClassTemplate->getLocation(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001376 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00001377 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001378 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1379 Decl->setLexicalDeclContext(CurContext);
1380 }
1381
1382 CanonType = Context.getTypeDeclType(Decl);
1383 }
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Douglas Gregor40808ce2009-03-09 23:48:35 +00001385 // Build the fully-sugared type for this class template
1386 // specialization, which refers back to the class template
1387 // specialization we created or found.
John McCalld5532b62009-11-23 01:53:49 +00001388 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001389}
1390
Douglas Gregorcc636682009-02-17 23:15:12 +00001391Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001392Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001393 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001394 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001395 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001396 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001397
Douglas Gregor40808ce2009-03-09 23:48:35 +00001398 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001399 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001400 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001401
John McCalld5532b62009-11-23 01:53:49 +00001402 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001403 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001404
1405 if (Result.isNull())
1406 return true;
1407
John McCalla93c9342009-12-07 02:54:59 +00001408 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001409 TemplateSpecializationTypeLoc TL
1410 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1411 TL.setTemplateNameLoc(TemplateLoc);
1412 TL.setLAngleLoc(LAngleLoc);
1413 TL.setRAngleLoc(RAngleLoc);
1414 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1415 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1416
1417 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCall6b2becf2009-09-08 17:47:29 +00001418}
John McCallf1bbbb42009-09-04 01:14:41 +00001419
John McCall6b2becf2009-09-08 17:47:29 +00001420Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1421 TagUseKind TUK,
1422 DeclSpec::TST TagSpec,
1423 SourceLocation TagLoc) {
1424 if (TypeResult.isInvalid())
1425 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001426
John McCall833ca992009-10-29 08:12:44 +00001427 // FIXME: preserve source info, ideally without copying the DI.
John McCalla93c9342009-12-07 02:54:59 +00001428 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001429 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001430
John McCall6b2becf2009-09-08 17:47:29 +00001431 // Verify the tag specifier.
1432 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001433
John McCall6b2becf2009-09-08 17:47:29 +00001434 if (const RecordType *RT = Type->getAs<RecordType>()) {
1435 RecordDecl *D = RT->getDecl();
1436
1437 IdentifierInfo *Id = D->getIdentifier();
1438 assert(Id && "templated class must have an identifier");
1439
1440 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1441 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001442 << Type
John McCall6b2becf2009-09-08 17:47:29 +00001443 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1444 D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001445 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001446 }
1447 }
1448
John McCall6b2becf2009-09-08 17:47:29 +00001449 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1450
1451 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001452}
1453
John McCallf7a1a742009-11-24 19:00:30 +00001454Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1455 LookupResult &R,
1456 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001457 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001458 // FIXME: Can we do any checking at this point? I guess we could check the
1459 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001460 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001461 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001462
1463 // These should be filtered out by our callers.
1464 assert(!R.empty() && "empty lookup results when building templateid");
1465 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1466
1467 NestedNameSpecifier *Qualifier = 0;
1468 SourceRange QualifierRange;
1469 if (SS.isSet()) {
1470 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1471 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001472 }
1473
John McCallf7a1a742009-11-24 19:00:30 +00001474 bool Dependent
1475 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1476 &TemplateArgs);
1477 UnresolvedLookupExpr *ULE
1478 = UnresolvedLookupExpr::Create(Context, Dependent,
1479 Qualifier, QualifierRange,
1480 R.getLookupName(), R.getNameLoc(),
1481 RequiresADL, TemplateArgs);
1482 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1483 ULE->addDecl(*I);
1484
1485 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001486}
1487
John McCallf7a1a742009-11-24 19:00:30 +00001488// We actually only call this from template instantiation.
1489Sema::OwningExprResult
1490Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1491 DeclarationName Name,
1492 SourceLocation NameLoc,
1493 const TemplateArgumentListInfo &TemplateArgs) {
1494 DeclContext *DC;
1495 if (!(DC = computeDeclContext(SS, false)) ||
1496 DC->isDependentContext() ||
1497 RequireCompleteDeclContext(SS))
1498 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001499
John McCallf7a1a742009-11-24 19:00:30 +00001500 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1501 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00001502
John McCallf7a1a742009-11-24 19:00:30 +00001503 if (R.isAmbiguous())
1504 return ExprError();
1505
1506 if (R.empty()) {
1507 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1508 << Name << SS.getRange();
1509 return ExprError();
1510 }
1511
1512 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1513 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1514 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1515 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1516 return ExprError();
1517 }
1518
1519 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001520}
1521
Douglas Gregorc45c2322009-03-31 00:43:58 +00001522/// \brief Form a dependent template name.
1523///
1524/// This action forms a dependent template name given the template
1525/// name and its (presumably dependent) scope specifier. For
1526/// example, given "MetaFun::template apply", the scope specifier \p
1527/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1528/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump1eb44332009-09-09 15:08:12 +00001529Sema::TemplateTy
Douglas Gregorc45c2322009-03-31 00:43:58 +00001530Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001531 const CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +00001532 UnqualifiedId &Name,
Douglas Gregora481edb2009-11-20 23:39:24 +00001533 TypeTy *ObjectType,
1534 bool EnteringContext) {
Mike Stump1eb44332009-09-09 15:08:12 +00001535 if ((ObjectType &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001536 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
Douglas Gregora481edb2009-11-20 23:39:24 +00001537 (SS.isSet() && computeDeclContext(SS, EnteringContext))) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001538 // C++0x [temp.names]p5:
1539 // If a name prefixed by the keyword template is not the name of
1540 // a template, the program is ill-formed. [Note: the keyword
1541 // template may not be applied to non-template members of class
1542 // templates. -end note ] [ Note: as is the case with the
1543 // typename prefix, the template prefix is allowed in cases
1544 // where it is not strictly necessary; i.e., when the
1545 // nested-name-specifier or the expression on the left of the ->
1546 // or . is not dependent on a template-parameter, or the use
1547 // does not appear in the scope of a template. -end note]
1548 //
1549 // Note: C++03 was more strict here, because it banned the use of
1550 // the "template" keyword prior to a template-name that was not a
1551 // dependent name. C++ DR468 relaxed this requirement (the
1552 // "template" keyword is now permitted). We follow the C++0x
1553 // rules, even in C++03 mode, retroactively applying the DR.
1554 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001555 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregora481edb2009-11-20 23:39:24 +00001556 EnteringContext, Template);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001557 if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001558 Diag(Name.getSourceRange().getBegin(),
1559 diag::err_template_kw_refers_to_non_template)
1560 << GetNameFromUnqualifiedId(Name)
1561 << Name.getSourceRange();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001562 return TemplateTy();
1563 }
1564
1565 return Template;
1566 }
1567
Mike Stump1eb44332009-09-09 15:08:12 +00001568 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001569 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001570
1571 switch (Name.getKind()) {
1572 case UnqualifiedId::IK_Identifier:
1573 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1574 Name.Identifier));
1575
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001576 case UnqualifiedId::IK_OperatorFunctionId:
1577 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1578 Name.OperatorFunctionId.Operator));
Sean Hunte6252d12009-11-28 08:58:14 +00001579
1580 case UnqualifiedId::IK_LiteralOperatorId:
1581 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1582
Douglas Gregor014e88d2009-11-03 23:16:33 +00001583 default:
1584 break;
1585 }
1586
1587 Diag(Name.getSourceRange().getBegin(),
1588 diag::err_template_kw_refers_to_non_template)
1589 << GetNameFromUnqualifiedId(Name)
1590 << Name.getSourceRange();
1591 return TemplateTy();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001592}
1593
Mike Stump1eb44332009-09-09 15:08:12 +00001594bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001595 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001596 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001597 const TemplateArgument &Arg = AL.getArgument();
1598
Anders Carlsson436b1562009-06-13 00:33:33 +00001599 // Check template type parameter.
1600 if (Arg.getKind() != TemplateArgument::Type) {
1601 // C++ [temp.arg.type]p1:
1602 // A template-argument for a template-parameter which is a
1603 // type shall be a type-id.
1604
1605 // We have a template type parameter but the template argument
1606 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001607 SourceRange SR = AL.getSourceRange();
1608 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001609 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001610
Anders Carlsson436b1562009-06-13 00:33:33 +00001611 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001612 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001613
John McCalla93c9342009-12-07 02:54:59 +00001614 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001615 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Anders Carlsson436b1562009-06-13 00:33:33 +00001617 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001618 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001619 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001620 return false;
1621}
1622
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001623/// \brief Substitute template arguments into the default template argument for
1624/// the given template type parameter.
1625///
1626/// \param SemaRef the semantic analysis object for which we are performing
1627/// the substitution.
1628///
1629/// \param Template the template that we are synthesizing template arguments
1630/// for.
1631///
1632/// \param TemplateLoc the location of the template name that started the
1633/// template-id we are checking.
1634///
1635/// \param RAngleLoc the location of the right angle bracket ('>') that
1636/// terminates the template-id.
1637///
1638/// \param Param the template template parameter whose default we are
1639/// substituting into.
1640///
1641/// \param Converted the list of template arguments provided for template
1642/// parameters that precede \p Param in the template parameter list.
1643///
1644/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001645static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001646SubstDefaultTemplateArgument(Sema &SemaRef,
1647 TemplateDecl *Template,
1648 SourceLocation TemplateLoc,
1649 SourceLocation RAngleLoc,
1650 TemplateTypeParmDecl *Param,
1651 TemplateArgumentListBuilder &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001652 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001653
1654 // If the argument type is dependent, instantiate it now based
1655 // on the previously-computed template arguments.
1656 if (ArgType->getType()->isDependentType()) {
1657 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1658 /*TakeArgs=*/false);
1659
1660 MultiLevelTemplateArgumentList AllTemplateArgs
1661 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1662
1663 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1664 Template, Converted.getFlatArguments(),
1665 Converted.flatSize(),
1666 SourceRange(TemplateLoc, RAngleLoc));
1667
1668 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1669 Param->getDefaultArgumentLoc(),
1670 Param->getDeclName());
1671 }
1672
1673 return ArgType;
1674}
1675
1676/// \brief Substitute template arguments into the default template argument for
1677/// the given non-type template parameter.
1678///
1679/// \param SemaRef the semantic analysis object for which we are performing
1680/// the substitution.
1681///
1682/// \param Template the template that we are synthesizing template arguments
1683/// for.
1684///
1685/// \param TemplateLoc the location of the template name that started the
1686/// template-id we are checking.
1687///
1688/// \param RAngleLoc the location of the right angle bracket ('>') that
1689/// terminates the template-id.
1690///
Douglas Gregor788cd062009-11-11 01:00:40 +00001691/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001692/// substituting into.
1693///
1694/// \param Converted the list of template arguments provided for template
1695/// parameters that precede \p Param in the template parameter list.
1696///
1697/// \returns the substituted template argument, or NULL if an error occurred.
1698static Sema::OwningExprResult
1699SubstDefaultTemplateArgument(Sema &SemaRef,
1700 TemplateDecl *Template,
1701 SourceLocation TemplateLoc,
1702 SourceLocation RAngleLoc,
1703 NonTypeTemplateParmDecl *Param,
1704 TemplateArgumentListBuilder &Converted) {
1705 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1706 /*TakeArgs=*/false);
1707
1708 MultiLevelTemplateArgumentList AllTemplateArgs
1709 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1710
1711 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1712 Template, Converted.getFlatArguments(),
1713 Converted.flatSize(),
1714 SourceRange(TemplateLoc, RAngleLoc));
1715
1716 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1717}
1718
Douglas Gregor788cd062009-11-11 01:00:40 +00001719/// \brief Substitute template arguments into the default template argument for
1720/// the given template template parameter.
1721///
1722/// \param SemaRef the semantic analysis object for which we are performing
1723/// the substitution.
1724///
1725/// \param Template the template that we are synthesizing template arguments
1726/// for.
1727///
1728/// \param TemplateLoc the location of the template name that started the
1729/// template-id we are checking.
1730///
1731/// \param RAngleLoc the location of the right angle bracket ('>') that
1732/// terminates the template-id.
1733///
1734/// \param Param the template template parameter whose default we are
1735/// substituting into.
1736///
1737/// \param Converted the list of template arguments provided for template
1738/// parameters that precede \p Param in the template parameter list.
1739///
1740/// \returns the substituted template argument, or NULL if an error occurred.
1741static TemplateName
1742SubstDefaultTemplateArgument(Sema &SemaRef,
1743 TemplateDecl *Template,
1744 SourceLocation TemplateLoc,
1745 SourceLocation RAngleLoc,
1746 TemplateTemplateParmDecl *Param,
1747 TemplateArgumentListBuilder &Converted) {
1748 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1749 /*TakeArgs=*/false);
1750
1751 MultiLevelTemplateArgumentList AllTemplateArgs
1752 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1753
1754 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1755 Template, Converted.getFlatArguments(),
1756 Converted.flatSize(),
1757 SourceRange(TemplateLoc, RAngleLoc));
1758
1759 return SemaRef.SubstTemplateName(
1760 Param->getDefaultArgument().getArgument().getAsTemplate(),
1761 Param->getDefaultArgument().getTemplateNameLoc(),
1762 AllTemplateArgs);
1763}
1764
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001765/// \brief If the given template parameter has a default template
1766/// argument, substitute into that default template argument and
1767/// return the corresponding template argument.
1768TemplateArgumentLoc
1769Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1770 SourceLocation TemplateLoc,
1771 SourceLocation RAngleLoc,
1772 Decl *Param,
1773 TemplateArgumentListBuilder &Converted) {
1774 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1775 if (!TypeParm->hasDefaultArgument())
1776 return TemplateArgumentLoc();
1777
John McCalla93c9342009-12-07 02:54:59 +00001778 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001779 TemplateLoc,
1780 RAngleLoc,
1781 TypeParm,
1782 Converted);
1783 if (DI)
1784 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1785
1786 return TemplateArgumentLoc();
1787 }
1788
1789 if (NonTypeTemplateParmDecl *NonTypeParm
1790 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1791 if (!NonTypeParm->hasDefaultArgument())
1792 return TemplateArgumentLoc();
1793
1794 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1795 TemplateLoc,
1796 RAngleLoc,
1797 NonTypeParm,
1798 Converted);
1799 if (Arg.isInvalid())
1800 return TemplateArgumentLoc();
1801
1802 Expr *ArgE = Arg.takeAs<Expr>();
1803 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1804 }
1805
1806 TemplateTemplateParmDecl *TempTempParm
1807 = cast<TemplateTemplateParmDecl>(Param);
1808 if (!TempTempParm->hasDefaultArgument())
1809 return TemplateArgumentLoc();
1810
1811 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1812 TemplateLoc,
1813 RAngleLoc,
1814 TempTempParm,
1815 Converted);
1816 if (TName.isNull())
1817 return TemplateArgumentLoc();
1818
1819 return TemplateArgumentLoc(TemplateArgument(TName),
1820 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1821 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1822}
1823
Douglas Gregore7526412009-11-11 19:31:23 +00001824/// \brief Check that the given template argument corresponds to the given
1825/// template parameter.
1826bool Sema::CheckTemplateArgument(NamedDecl *Param,
1827 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00001828 TemplateDecl *Template,
1829 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00001830 SourceLocation RAngleLoc,
1831 TemplateArgumentListBuilder &Converted) {
Douglas Gregord9e15302009-11-11 19:41:09 +00001832 // Check template type parameters.
1833 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00001834 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00001835
Douglas Gregord9e15302009-11-11 19:41:09 +00001836 // Check non-type template parameters.
1837 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00001838 // Do substitution on the type of the non-type template parameter
1839 // with the template arguments we've seen thus far.
1840 QualType NTTPType = NTTP->getType();
1841 if (NTTPType->isDependentType()) {
1842 // Do substitution on the type of the non-type template parameter.
1843 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1844 NTTP, Converted.getFlatArguments(),
1845 Converted.flatSize(),
1846 SourceRange(TemplateLoc, RAngleLoc));
1847
1848 TemplateArgumentList TemplateArgs(Context, Converted,
1849 /*TakeArgs=*/false);
1850 NTTPType = SubstType(NTTPType,
1851 MultiLevelTemplateArgumentList(TemplateArgs),
1852 NTTP->getLocation(),
1853 NTTP->getDeclName());
1854 // If that worked, check the non-type template parameter type
1855 // for validity.
1856 if (!NTTPType.isNull())
1857 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1858 NTTP->getLocation());
1859 if (NTTPType.isNull())
1860 return true;
1861 }
1862
1863 switch (Arg.getArgument().getKind()) {
1864 case TemplateArgument::Null:
1865 assert(false && "Should never see a NULL template argument here");
1866 return true;
1867
1868 case TemplateArgument::Expression: {
1869 Expr *E = Arg.getArgument().getAsExpr();
1870 TemplateArgument Result;
1871 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1872 return true;
1873
1874 Converted.Append(Result);
1875 break;
1876 }
1877
1878 case TemplateArgument::Declaration:
1879 case TemplateArgument::Integral:
1880 // We've already checked this template argument, so just copy
1881 // it to the list of converted arguments.
1882 Converted.Append(Arg.getArgument());
1883 break;
1884
1885 case TemplateArgument::Template:
1886 // We were given a template template argument. It may not be ill-formed;
1887 // see below.
1888 if (DependentTemplateName *DTN
1889 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1890 // We have a template argument such as \c T::template X, which we
1891 // parsed as a template template argument. However, since we now
1892 // know that we need a non-type template argument, convert this
1893 // template name into an expression.
John McCallf7a1a742009-11-24 19:00:30 +00001894 Expr *E = DependentScopeDeclRefExpr::Create(Context,
1895 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00001896 Arg.getTemplateQualifierRange(),
John McCallf7a1a742009-11-24 19:00:30 +00001897 DTN->getIdentifier(),
1898 Arg.getTemplateNameLoc());
Douglas Gregore7526412009-11-11 19:31:23 +00001899
1900 TemplateArgument Result;
1901 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1902 return true;
1903
1904 Converted.Append(Result);
1905 break;
1906 }
1907
1908 // We have a template argument that actually does refer to a class
1909 // template, template alias, or template template parameter, and
1910 // therefore cannot be a non-type template argument.
1911 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1912 << Arg.getSourceRange();
1913
1914 Diag(Param->getLocation(), diag::note_template_param_here);
1915 return true;
1916
1917 case TemplateArgument::Type: {
1918 // We have a non-type template parameter but the template
1919 // argument is a type.
1920
1921 // C++ [temp.arg]p2:
1922 // In a template-argument, an ambiguity between a type-id and
1923 // an expression is resolved to a type-id, regardless of the
1924 // form of the corresponding template-parameter.
1925 //
1926 // We warn specifically about this case, since it can be rather
1927 // confusing for users.
1928 QualType T = Arg.getArgument().getAsType();
1929 SourceRange SR = Arg.getSourceRange();
1930 if (T->isFunctionType())
1931 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1932 else
1933 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1934 Diag(Param->getLocation(), diag::note_template_param_here);
1935 return true;
1936 }
1937
1938 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001939 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00001940 break;
1941 }
1942
1943 return false;
1944 }
1945
1946
1947 // Check template template parameters.
1948 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
1949
1950 // Substitute into the template parameter list of the template
1951 // template parameter, since previously-supplied template arguments
1952 // may appear within the template template parameter.
1953 {
1954 // Set up a template instantiation context.
1955 LocalInstantiationScope Scope(*this);
1956 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1957 TempParm, Converted.getFlatArguments(),
1958 Converted.flatSize(),
1959 SourceRange(TemplateLoc, RAngleLoc));
1960
1961 TemplateArgumentList TemplateArgs(Context, Converted,
1962 /*TakeArgs=*/false);
1963 TempParm = cast_or_null<TemplateTemplateParmDecl>(
1964 SubstDecl(TempParm, CurContext,
1965 MultiLevelTemplateArgumentList(TemplateArgs)));
1966 if (!TempParm)
1967 return true;
1968
1969 // FIXME: TempParam is leaked.
1970 }
1971
1972 switch (Arg.getArgument().getKind()) {
1973 case TemplateArgument::Null:
1974 assert(false && "Should never see a NULL template argument here");
1975 return true;
1976
1977 case TemplateArgument::Template:
1978 if (CheckTemplateArgument(TempParm, Arg))
1979 return true;
1980
1981 Converted.Append(Arg.getArgument());
1982 break;
1983
1984 case TemplateArgument::Expression:
1985 case TemplateArgument::Type:
1986 // We have a template template parameter but the template
1987 // argument does not refer to a template.
1988 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1989 return true;
1990
1991 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001992 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00001993 "Declaration argument with template template parameter");
1994 break;
1995 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00001996 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00001997 "Integral argument with template template parameter");
1998 break;
1999
2000 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002001 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002002 break;
2003 }
2004
2005 return false;
2006}
2007
Douglas Gregorc15cb382009-02-09 23:23:08 +00002008/// \brief Check that the given template argument list is well-formed
2009/// for specializing the given template.
2010bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2011 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002012 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002013 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002014 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002015 TemplateParameterList *Params = Template->getTemplateParameters();
2016 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002017 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002018 bool Invalid = false;
2019
John McCalld5532b62009-11-23 01:53:49 +00002020 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2021
Mike Stump1eb44332009-09-09 15:08:12 +00002022 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002023 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002025 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002026 (NumArgs < Params->getMinRequiredArguments() &&
2027 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002028 // FIXME: point at either the first arg beyond what we can handle,
2029 // or the '>', depending on whether we have too many or too few
2030 // arguments.
2031 SourceRange Range;
2032 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002033 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002034 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2035 << (NumArgs > NumParams)
2036 << (isa<ClassTemplateDecl>(Template)? 0 :
2037 isa<FunctionTemplateDecl>(Template)? 1 :
2038 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2039 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002040 Diag(Template->getLocation(), diag::note_template_decl_here)
2041 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002042 Invalid = true;
2043 }
Mike Stump1eb44332009-09-09 15:08:12 +00002044
2045 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002046 // [...] The type and form of each template-argument specified in
2047 // a template-id shall match the type and form specified for the
2048 // corresponding parameter declared by the template in its
2049 // template-parameter-list.
2050 unsigned ArgIdx = 0;
2051 for (TemplateParameterList::iterator Param = Params->begin(),
2052 ParamEnd = Params->end();
2053 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002054 if (ArgIdx > NumArgs && PartialTemplateArgs)
2055 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Douglas Gregord9e15302009-11-11 19:41:09 +00002057 // If we have a template parameter pack, check every remaining template
2058 // argument against that template parameter pack.
2059 if ((*Param)->isTemplateParameterPack()) {
2060 Converted.BeginPack();
2061 for (; ArgIdx < NumArgs; ++ArgIdx) {
2062 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2063 TemplateLoc, RAngleLoc, Converted)) {
2064 Invalid = true;
2065 break;
2066 }
2067 }
2068 Converted.EndPack();
2069 continue;
2070 }
2071
Douglas Gregorf35f8282009-11-11 21:54:23 +00002072 if (ArgIdx < NumArgs) {
2073 // Check the template argument we were given.
2074 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2075 TemplateLoc, RAngleLoc, Converted))
2076 return true;
2077
2078 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002079 }
Douglas Gregore7526412009-11-11 19:31:23 +00002080
Douglas Gregorf35f8282009-11-11 21:54:23 +00002081 // We have a default template argument that we will use.
2082 TemplateArgumentLoc Arg;
2083
2084 // Retrieve the default template argument from the template
2085 // parameter. For each kind of template parameter, we substitute the
2086 // template arguments provided thus far and any "outer" template arguments
2087 // (when the template parameter was part of a nested template) into
2088 // the default argument.
2089 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2090 if (!TTP->hasDefaultArgument()) {
2091 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2092 break;
2093 }
2094
John McCalla93c9342009-12-07 02:54:59 +00002095 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002096 Template,
2097 TemplateLoc,
2098 RAngleLoc,
2099 TTP,
2100 Converted);
2101 if (!ArgType)
2102 return true;
2103
2104 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2105 ArgType);
2106 } else if (NonTypeTemplateParmDecl *NTTP
2107 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2108 if (!NTTP->hasDefaultArgument()) {
2109 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2110 break;
2111 }
2112
2113 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2114 TemplateLoc,
2115 RAngleLoc,
2116 NTTP,
2117 Converted);
2118 if (E.isInvalid())
2119 return true;
2120
2121 Expr *Ex = E.takeAs<Expr>();
2122 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2123 } else {
2124 TemplateTemplateParmDecl *TempParm
2125 = cast<TemplateTemplateParmDecl>(*Param);
2126
2127 if (!TempParm->hasDefaultArgument()) {
2128 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2129 break;
2130 }
2131
2132 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2133 TemplateLoc,
2134 RAngleLoc,
2135 TempParm,
2136 Converted);
2137 if (Name.isNull())
2138 return true;
2139
2140 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2141 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2142 TempParm->getDefaultArgument().getTemplateNameLoc());
2143 }
2144
2145 // Introduce an instantiation record that describes where we are using
2146 // the default template argument.
2147 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2148 Converted.getFlatArguments(),
2149 Converted.flatSize(),
2150 SourceRange(TemplateLoc, RAngleLoc));
2151
2152 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002153 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002154 RAngleLoc, Converted))
2155 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002156 }
2157
2158 return Invalid;
2159}
2160
2161/// \brief Check a template argument against its corresponding
2162/// template type parameter.
2163///
2164/// This routine implements the semantics of C++ [temp.arg.type]. It
2165/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002166bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002167 TypeSourceInfo *ArgInfo) {
2168 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002169 QualType Arg = ArgInfo->getType();
2170
Douglas Gregorc15cb382009-02-09 23:23:08 +00002171 // C++ [temp.arg.type]p2:
2172 // A local type, a type with no linkage, an unnamed type or a type
2173 // compounded from any of these types shall not be used as a
2174 // template-argument for a template type-parameter.
2175 //
2176 // FIXME: Perform the recursive and no-linkage type checks.
2177 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00002178 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002179 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00002180 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002181 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00002182 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2183 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2184 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2185 << QualType(Tag, 0) << SR;
2186 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00002187 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall833ca992009-10-29 08:12:44 +00002188 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2189 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002190 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2191 return true;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002192 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2193 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2194 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002195 }
2196
2197 return false;
2198}
2199
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002200/// \brief Checks whether the given template argument is the address
2201/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002202bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2203 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002204 bool Invalid = false;
2205
2206 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002207 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002208 Arg = Cast->getSubExpr();
2209
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002210 // C++0x allows nullptr, and there's no further checking to be done for that.
2211 if (Arg->getType()->isNullPtrType())
2212 return false;
2213
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002214 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002215 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002216 // A template-argument for a non-type, non-template
2217 // template-parameter shall be one of: [...]
2218 //
2219 // -- the address of an object or function with external
2220 // linkage, including function templates and function
2221 // template-ids but excluding non-static class members,
2222 // expressed as & id-expression where the & is optional if
2223 // the name refers to a function or array, or if the
2224 // corresponding template-parameter is a reference; or
2225 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002226
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002227 // Ignore (and complain about) any excess parentheses.
2228 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2229 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002230 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002231 diag::err_template_arg_extra_parens)
2232 << Arg->getSourceRange();
2233 Invalid = true;
2234 }
2235
2236 Arg = Parens->getSubExpr();
2237 }
2238
2239 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2240 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2241 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2242 } else
2243 DRE = dyn_cast<DeclRefExpr>(Arg);
2244
2245 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00002246 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002247 diag::err_template_arg_not_object_or_func_form)
2248 << Arg->getSourceRange();
2249
2250 // Cannot refer to non-static data members
2251 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2252 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2253 << Field << Arg->getSourceRange();
2254
2255 // Cannot refer to non-static member functions
2256 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2257 if (!Method->isStatic())
Mike Stump1eb44332009-09-09 15:08:12 +00002258 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002259 diag::err_template_arg_method)
2260 << Method << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002262 // Functions must have external linkage.
2263 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregord85b5b92009-11-25 22:24:25 +00002264 if (Func->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump1eb44332009-09-09 15:08:12 +00002265 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002266 diag::err_template_arg_function_not_extern)
2267 << Func << Arg->getSourceRange();
2268 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2269 << true;
2270 return true;
2271 }
2272
2273 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002274 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002275 return Invalid;
2276 }
2277
2278 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregord85b5b92009-11-25 22:24:25 +00002279 if (Var->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump1eb44332009-09-09 15:08:12 +00002280 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002281 diag::err_template_arg_object_not_extern)
2282 << Var << Arg->getSourceRange();
2283 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2284 << true;
2285 return true;
2286 }
2287
2288 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002289 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002290 return Invalid;
2291 }
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002293 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002294 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002295 diag::err_template_arg_not_object_or_func)
2296 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002297 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002298 diag::note_template_arg_refers_here);
2299 return true;
2300}
2301
2302/// \brief Checks whether the given template argument is a pointer to
2303/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002304bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2305 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002306 bool Invalid = false;
2307
2308 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002309 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002310 Arg = Cast->getSubExpr();
2311
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002312 // C++0x allows nullptr, and there's no further checking to be done for that.
2313 if (Arg->getType()->isNullPtrType())
2314 return false;
2315
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002316 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002317 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002318 // A template-argument for a non-type, non-template
2319 // template-parameter shall be one of: [...]
2320 //
2321 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002322 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002323
2324 // Ignore (and complain about) any excess parentheses.
2325 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2326 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002327 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002328 diag::err_template_arg_extra_parens)
2329 << Arg->getSourceRange();
2330 Invalid = true;
2331 }
2332
2333 Arg = Parens->getSubExpr();
2334 }
2335
Douglas Gregorcaddba02009-11-12 18:38:13 +00002336 // A pointer-to-member constant written &Class::member.
2337 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002338 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2339 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2340 if (DRE && !DRE->getQualifier())
2341 DRE = 0;
2342 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002343 }
2344 // A constant of pointer-to-member type.
2345 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2346 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2347 if (VD->getType()->isMemberPointerType()) {
2348 if (isa<NonTypeTemplateParmDecl>(VD) ||
2349 (isa<VarDecl>(VD) &&
2350 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2351 if (Arg->isTypeDependent() || Arg->isValueDependent())
2352 Converted = TemplateArgument(Arg->Retain());
2353 else
2354 Converted = TemplateArgument(VD->getCanonicalDecl());
2355 return Invalid;
2356 }
2357 }
2358 }
2359
2360 DRE = 0;
2361 }
2362
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002363 if (!DRE)
2364 return Diag(Arg->getSourceRange().getBegin(),
2365 diag::err_template_arg_not_pointer_to_member_form)
2366 << Arg->getSourceRange();
2367
2368 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2369 assert((isa<FieldDecl>(DRE->getDecl()) ||
2370 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2371 "Only non-static member pointers can make it here");
2372
2373 // Okay: this is the address of a non-static member, and therefore
2374 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002375 if (Arg->isTypeDependent() || Arg->isValueDependent())
2376 Converted = TemplateArgument(Arg->Retain());
2377 else
2378 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002379 return Invalid;
2380 }
2381
2382 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002383 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002384 diag::err_template_arg_not_pointer_to_member_form)
2385 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002386 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002387 diag::note_template_arg_refers_here);
2388 return true;
2389}
2390
Douglas Gregorc15cb382009-02-09 23:23:08 +00002391/// \brief Check a template argument against its corresponding
2392/// non-type template parameter.
2393///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002394/// This routine implements the semantics of C++ [temp.arg.nontype].
2395/// It returns true if an error occurred, and false otherwise. \p
2396/// InstantiatedParamType is the type of the non-type template
2397/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002398///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002399/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002400bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002401 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002402 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002403 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2404
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002405 // If either the parameter has a dependent type or the argument is
2406 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002407 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00002408 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2409 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002410 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002411 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002412 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002413
2414 // C++ [temp.arg.nontype]p5:
2415 // The following conversions are performed on each expression used
2416 // as a non-type template-argument. If a non-type
2417 // template-argument cannot be converted to the type of the
2418 // corresponding template-parameter then the program is
2419 // ill-formed.
2420 //
2421 // -- for a non-type template-parameter of integral or
2422 // enumeration type, integral promotions (4.5) and integral
2423 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002424 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002425 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002426 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002427 // C++ [temp.arg.nontype]p1:
2428 // A template-argument for a non-type, non-template
2429 // template-parameter shall be one of:
2430 //
2431 // -- an integral constant-expression of integral or enumeration
2432 // type; or
2433 // -- the name of a non-type template-parameter; or
2434 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002435 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002436 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002437 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002438 diag::err_template_arg_not_integral_or_enumeral)
2439 << ArgType << Arg->getSourceRange();
2440 Diag(Param->getLocation(), diag::note_template_param_here);
2441 return true;
2442 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002443 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002444 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2445 << ArgType << Arg->getSourceRange();
2446 return true;
2447 }
2448
2449 // FIXME: We need some way to more easily get the unqualified form
2450 // of the types without going all the way to the
2451 // canonical type.
2452 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2453 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2454 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2455 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2456
2457 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002458 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002459 // Okay: no conversion necessary
2460 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2461 !ParamType->isEnumeralType()) {
2462 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002463 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002464 } else {
2465 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002466 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002467 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002468 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002469 Diag(Param->getLocation(), diag::note_template_param_here);
2470 return true;
2471 }
2472
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002473 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002474 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002475 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002476
2477 if (!Arg->isValueDependent()) {
2478 // Check that an unsigned parameter does not receive a negative
2479 // value.
2480 if (IntegerType->isUnsignedIntegerType()
2481 && (Value.isSigned() && Value.isNegative())) {
2482 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2483 << Value.toString(10) << Param->getType()
2484 << Arg->getSourceRange();
2485 Diag(Param->getLocation(), diag::note_template_param_here);
2486 return true;
2487 }
2488
2489 // Check that we don't overflow the template parameter type.
2490 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Eli Friedman29f89f62009-12-23 18:44:58 +00002491 unsigned RequiredBits;
2492 if (IntegerType->isUnsignedIntegerType())
2493 RequiredBits = Value.getActiveBits();
2494 else if (Value.isUnsigned())
2495 RequiredBits = Value.getActiveBits() + 1;
2496 else
2497 RequiredBits = Value.getMinSignedBits();
2498 if (RequiredBits > AllowedBits) {
Mike Stump1eb44332009-09-09 15:08:12 +00002499 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002500 diag::err_template_arg_too_large)
2501 << Value.toString(10) << Param->getType()
2502 << Arg->getSourceRange();
2503 Diag(Param->getLocation(), diag::note_template_param_here);
2504 return true;
2505 }
2506
2507 if (Value.getBitWidth() != AllowedBits)
2508 Value.extOrTrunc(AllowedBits);
2509 Value.setIsSigned(IntegerType->isSignedIntegerType());
2510 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002511
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002512 // Add the value of this argument to the list of converted
2513 // arguments. We use the bitwidth and signedness of the template
2514 // parameter.
2515 if (Arg->isValueDependent()) {
2516 // The argument is value-dependent. Create a new
2517 // TemplateArgument with the converted expression.
2518 Converted = TemplateArgument(Arg);
2519 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002520 }
2521
John McCall833ca992009-10-29 08:12:44 +00002522 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002523 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002524 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002525 return false;
2526 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002527
Douglas Gregorb86b0572009-02-11 01:18:59 +00002528 // Handle pointer-to-function, reference-to-function, and
2529 // pointer-to-member-function all in (roughly) the same way.
2530 if (// -- For a non-type template-parameter of type pointer to
2531 // function, only the function-to-pointer conversion (4.3) is
2532 // applied. If the template-argument represents a set of
2533 // overloaded functions (or a pointer to such), the matching
2534 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002535 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002536 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002537 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002538 // -- For a non-type template-parameter of type reference to
2539 // function, no conversions apply. If the template-argument
2540 // represents a set of overloaded functions, the matching
2541 // function is selected from the set (13.4).
2542 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002543 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002544 // -- For a non-type template-parameter of type pointer to
2545 // member function, no conversions apply. If the
2546 // template-argument represents a set of overloaded member
2547 // functions, the matching member function is selected from
2548 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002549 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002550 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002551 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002552 ->isFunctionType())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002553 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002554 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002555 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002556 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2557 ParamType->isMemberPointerType())) {
2558 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002559 if (ParamType->isMemberPointerType())
2560 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2561 else
2562 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002563 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002564 ArgType = Context.getPointerType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002565 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump1eb44332009-09-09 15:08:12 +00002566 } else if (FunctionDecl *Fn
Douglas Gregora35284b2009-02-11 00:19:33 +00002567 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002568 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2569 return true;
2570
Anders Carlsson96ad5332009-10-21 17:16:23 +00002571 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00002572 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002573 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002574 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman73c39ab2009-10-20 08:27:19 +00002575 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregora35284b2009-02-11 00:19:33 +00002576 }
2577 }
2578
Mike Stump1eb44332009-09-09 15:08:12 +00002579 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002580 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002581 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002582 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002583 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002584 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002585 Diag(Param->getLocation(), diag::note_template_param_here);
2586 return true;
2587 }
Mike Stump1eb44332009-09-09 15:08:12 +00002588
Douglas Gregorcaddba02009-11-12 18:38:13 +00002589 if (ParamType->isMemberPointerType())
2590 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump1eb44332009-09-09 15:08:12 +00002591
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002592 NamedDecl *Entity = 0;
2593 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2594 return true;
2595
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002596 if (Entity)
2597 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002598 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002599 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00002600 }
2601
Chris Lattnerfe90de72009-02-20 21:37:53 +00002602 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002603 // -- for a non-type template-parameter of type pointer to
2604 // object, qualification conversions (4.4) and the
2605 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002606 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002607 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002608 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002609
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002610 if (ArgType->isNullPtrType()) {
2611 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002612 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002613 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002614 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002615 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002616 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002617
Douglas Gregorb86b0572009-02-11 01:18:59 +00002618 if (IsQualificationConversion(ArgType, ParamType)) {
2619 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002620 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002621 }
Mike Stump1eb44332009-09-09 15:08:12 +00002622
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002623 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002624 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002625 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002626 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002627 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002628 Diag(Param->getLocation(), diag::note_template_param_here);
2629 return true;
2630 }
Mike Stump1eb44332009-09-09 15:08:12 +00002631
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002632 NamedDecl *Entity = 0;
2633 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2634 return true;
2635
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002636 if (Entity)
2637 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002638 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002639 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002640 }
Mike Stump1eb44332009-09-09 15:08:12 +00002641
Ted Kremenek6217b802009-07-29 21:53:49 +00002642 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002643 // -- For a non-type template-parameter of type reference to
2644 // object, no conversions apply. The type referred to by the
2645 // reference may be more cv-qualified than the (otherwise
2646 // identical) type of the template-argument. The
2647 // template-parameter is bound directly to the
2648 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002649 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002650 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002651
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002652 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002653 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002654 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002655 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002656 << Arg->getSourceRange();
2657 Diag(Param->getLocation(), diag::note_template_param_here);
2658 return true;
2659 }
2660
Mike Stump1eb44332009-09-09 15:08:12 +00002661 unsigned ParamQuals
Douglas Gregorb86b0572009-02-11 01:18:59 +00002662 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2663 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00002664
Douglas Gregorb86b0572009-02-11 01:18:59 +00002665 if ((ParamQuals | ArgQuals) != ParamQuals) {
2666 Diag(Arg->getSourceRange().getBegin(),
2667 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002668 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002669 << Arg->getSourceRange();
2670 Diag(Param->getLocation(), diag::note_template_param_here);
2671 return true;
2672 }
Mike Stump1eb44332009-09-09 15:08:12 +00002673
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002674 NamedDecl *Entity = 0;
2675 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2676 return true;
2677
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002678 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002679 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002680 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002681 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002682
2683 // -- For a non-type template-parameter of type pointer to data
2684 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002685 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00002686 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2687
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002688 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002689 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002690 } else if (ArgType->isNullPtrType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002691 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002692 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002693 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002694 } else {
2695 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002696 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00002697 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002698 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00002699 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002700 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00002701 }
2702
Douglas Gregorcaddba02009-11-12 18:38:13 +00002703 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002704}
2705
2706/// \brief Check a template argument against its corresponding
2707/// template template parameter.
2708///
2709/// This routine implements the semantics of C++ [temp.arg.template].
2710/// It returns true if an error occurred, and false otherwise.
2711bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00002712 const TemplateArgumentLoc &Arg) {
2713 TemplateName Name = Arg.getArgument().getAsTemplate();
2714 TemplateDecl *Template = Name.getAsTemplateDecl();
2715 if (!Template) {
2716 // Any dependent template name is fine.
2717 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2718 return false;
2719 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002720
2721 // C++ [temp.arg.template]p1:
2722 // A template-argument for a template template-parameter shall be
2723 // the name of a class template, expressed as id-expression. Only
2724 // primary class templates are considered when matching the
2725 // template template argument with the corresponding parameter;
2726 // partial specializations are not considered even if their
2727 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002728 //
2729 // Note that we also allow template template parameters here, which
2730 // will happen when we are dealing with, e.g., class template
2731 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00002732 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002733 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002734 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00002735 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00002736 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00002737 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002738 << Template;
2739 }
2740
2741 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2742 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00002743 true,
2744 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00002745 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00002746}
2747
Douglas Gregorddc29e12009-02-06 22:42:48 +00002748/// \brief Determine whether the given template parameter lists are
2749/// equivalent.
2750///
Mike Stump1eb44332009-09-09 15:08:12 +00002751/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00002752/// source code as part of a new template declaration.
2753///
2754/// \param Old The old template parameter list, typically found via
2755/// name lookup of the template declared with this template parameter
2756/// list.
2757///
2758/// \param Complain If true, this routine will produce a diagnostic if
2759/// the template parameter lists are not equivalent.
2760///
Douglas Gregorfb898e12009-11-12 16:20:59 +00002761/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00002762///
2763/// \param TemplateArgLoc If this source location is valid, then we
2764/// are actually checking the template parameter list of a template
2765/// argument (New) against the template parameter list of its
2766/// corresponding template template parameter (Old). We produce
2767/// slightly different diagnostics in this scenario.
2768///
Douglas Gregorddc29e12009-02-06 22:42:48 +00002769/// \returns True if the template parameter lists are equal, false
2770/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002771bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00002772Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2773 TemplateParameterList *Old,
2774 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00002775 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002776 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002777 if (Old->size() != New->size()) {
2778 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002779 unsigned NextDiag = diag::err_template_param_list_different_arity;
2780 if (TemplateArgLoc.isValid()) {
2781 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2782 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00002783 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002784 Diag(New->getTemplateLoc(), NextDiag)
2785 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00002786 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002787 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00002788 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002789 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002790 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2791 }
2792
2793 return false;
2794 }
2795
2796 for (TemplateParameterList::iterator OldParm = Old->begin(),
2797 OldParmEnd = Old->end(), NewParm = New->begin();
2798 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2799 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002800 if (Complain) {
2801 unsigned NextDiag = diag::err_template_param_different_kind;
2802 if (TemplateArgLoc.isValid()) {
2803 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2804 NextDiag = diag::note_template_param_different_kind;
2805 }
2806 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002807 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002808 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002809 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00002810 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00002811 return false;
2812 }
2813
2814 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2815 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00002816 // know we're at the same index).
Mike Stump1eb44332009-09-09 15:08:12 +00002817 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002818 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2819 // The types of non-type template parameters must agree.
2820 NonTypeTemplateParmDecl *NewNTTP
2821 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00002822
2823 // If we are matching a template template argument to a template
2824 // template parameter and one of the non-type template parameter types
2825 // is dependent, then we must wait until template instantiation time
2826 // to actually compare the arguments.
2827 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2828 (OldNTTP->getType()->isDependentType() ||
2829 NewNTTP->getType()->isDependentType()))
2830 continue;
2831
Douglas Gregorddc29e12009-02-06 22:42:48 +00002832 if (Context.getCanonicalType(OldNTTP->getType()) !=
2833 Context.getCanonicalType(NewNTTP->getType())) {
2834 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002835 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2836 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002837 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002838 diag::err_template_arg_template_params_mismatch);
2839 NextDiag = diag::note_template_nontype_parm_different_type;
2840 }
2841 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002842 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00002843 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00002844 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00002845 diag::note_template_nontype_parm_prev_declaration)
2846 << OldNTTP->getType();
2847 }
2848 return false;
2849 }
2850 } else {
2851 // The template parameter lists of template template
2852 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00002853 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00002854 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00002855 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002856 = cast<TemplateTemplateParmDecl>(*OldParm);
2857 TemplateTemplateParmDecl *NewTTP
2858 = cast<TemplateTemplateParmDecl>(*NewParm);
2859 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2860 OldTTP->getTemplateParameters(),
2861 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00002862 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00002863 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002864 return false;
2865 }
2866 }
2867
2868 return true;
2869}
2870
2871/// \brief Check whether a template can be declared within this scope.
2872///
2873/// If the template declaration is valid in this scope, returns
2874/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00002875bool
Douglas Gregor05396e22009-08-25 17:23:04 +00002876Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002877 // Find the nearest enclosing declaration scope.
2878 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2879 (S->getFlags() & Scope::TemplateParamScope) != 0)
2880 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002881
Douglas Gregorddc29e12009-02-06 22:42:48 +00002882 // C++ [temp]p2:
2883 // A template-declaration can appear only as a namespace scope or
2884 // class scope declaration.
2885 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00002886 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2887 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00002888 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00002889 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002890
Eli Friedman1503f772009-07-31 01:43:05 +00002891 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002892 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002893
2894 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2895 return false;
2896
Mike Stump1eb44332009-09-09 15:08:12 +00002897 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002898 diag::err_template_outside_namespace_or_class_scope)
2899 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002900}
Douglas Gregorcc636682009-02-17 23:15:12 +00002901
Douglas Gregord5cb8762009-10-07 00:13:32 +00002902/// \brief Determine what kind of template specialization the given declaration
2903/// is.
2904static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2905 if (!D)
2906 return TSK_Undeclared;
2907
Douglas Gregorf6b11852009-10-08 15:14:33 +00002908 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2909 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00002910 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2911 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002912 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2913 return Var->getTemplateSpecializationKind();
2914
Douglas Gregord5cb8762009-10-07 00:13:32 +00002915 return TSK_Undeclared;
2916}
2917
Douglas Gregor9302da62009-10-14 23:50:59 +00002918/// \brief Check whether a specialization is well-formed in the current
2919/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00002920///
Douglas Gregor9302da62009-10-14 23:50:59 +00002921/// This routine determines whether a template specialization can be declared
2922/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00002923///
2924/// \param S the semantic analysis object for which this check is being
2925/// performed.
2926///
2927/// \param Specialized the entity being specialized or instantiated, which
2928/// may be a kind of template (class template, function template, etc.) or
2929/// a member of a class template (member function, static data member,
2930/// member class).
2931///
2932/// \param PrevDecl the previous declaration of this entity, if any.
2933///
2934/// \param Loc the location of the explicit specialization or instantiation of
2935/// this entity.
2936///
2937/// \param IsPartialSpecialization whether this is a partial specialization of
2938/// a class template.
2939///
Douglas Gregord5cb8762009-10-07 00:13:32 +00002940/// \returns true if there was an error that we cannot recover from, false
2941/// otherwise.
2942static bool CheckTemplateSpecializationScope(Sema &S,
2943 NamedDecl *Specialized,
2944 NamedDecl *PrevDecl,
2945 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00002946 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002947 // Keep these "kind" numbers in sync with the %select statements in the
2948 // various diagnostics emitted by this routine.
2949 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002950 bool isTemplateSpecialization = false;
2951 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002952 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002953 isTemplateSpecialization = true;
2954 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002955 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002956 isTemplateSpecialization = true;
2957 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00002958 EntityKind = 3;
2959 else if (isa<VarDecl>(Specialized))
2960 EntityKind = 4;
2961 else if (isa<RecordDecl>(Specialized))
2962 EntityKind = 5;
2963 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00002964 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2965 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00002966 return true;
2967 }
2968
Douglas Gregor88b70942009-02-25 22:02:03 +00002969 // C++ [temp.expl.spec]p2:
2970 // An explicit specialization shall be declared in the namespace
2971 // of which the template is a member, or, for member templates, in
2972 // the namespace of which the enclosing class or enclosing class
2973 // template is a member. An explicit specialization of a member
2974 // function, member class or static data member of a class
2975 // template shall be declared in the namespace of which the class
2976 // template is a member. Such a declaration may also be a
2977 // definition. If the declaration is not a definition, the
2978 // specialization may be defined later in the name- space in which
2979 // the explicit specialization was declared, or in a namespace
2980 // that encloses the one in which the explicit specialization was
2981 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00002982 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2983 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00002984 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00002985 return true;
2986 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002987
Douglas Gregor0a407472009-10-07 17:30:37 +00002988 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2989 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00002990 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00002991 return true;
2992 }
2993
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002994 // C++ [temp.class.spec]p6:
2995 // A class template partial specialization may be declared or redeclared
2996 // in any namespace scope in which its definition may be defined (14.5.1
2997 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00002998 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002999 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003000 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003001 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003002 if ((!PrevDecl ||
3003 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3004 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3005 // There is no prior declaration of this entity, so this
3006 // specialization must be in the same context as the template
3007 // itself.
3008 if (!DC->Equals(SpecializedContext)) {
3009 if (isa<TranslationUnitDecl>(SpecializedContext))
3010 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3011 << EntityKind << Specialized;
3012 else if (isa<NamespaceDecl>(SpecializedContext))
3013 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3014 << EntityKind << Specialized
3015 << cast<NamedDecl>(SpecializedContext);
3016
3017 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3018 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003019 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003020 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003021
3022 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003023 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003024 // Note that HandleDeclarator() performs this check for explicit
3025 // specializations of function templates, static data members, and member
3026 // functions, so we skip the check here for those kinds of entities.
3027 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003028 // Should we refactor that check, so that it occurs later?
3029 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003030 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3031 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003032 if (isa<TranslationUnitDecl>(SpecializedContext))
3033 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3034 << EntityKind << Specialized;
3035 else if (isa<NamespaceDecl>(SpecializedContext))
3036 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3037 << EntityKind << Specialized
3038 << cast<NamedDecl>(SpecializedContext);
3039
Douglas Gregor9302da62009-10-14 23:50:59 +00003040 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003041 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003042
3043 // FIXME: check for specialization-after-instantiation errors and such.
3044
Douglas Gregor88b70942009-02-25 22:02:03 +00003045 return false;
3046}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003047
Douglas Gregore94866f2009-06-12 21:21:02 +00003048/// \brief Check the non-type template arguments of a class template
3049/// partial specialization according to C++ [temp.class.spec]p9.
3050///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003051/// \param TemplateParams the template parameters of the primary class
3052/// template.
3053///
3054/// \param TemplateArg the template arguments of the class template
3055/// partial specialization.
3056///
3057/// \param MirrorsPrimaryTemplate will be set true if the class
3058/// template partial specialization arguments are identical to the
3059/// implicit template arguments of the primary template. This is not
3060/// necessarily an error (C++0x), and it is left to the caller to diagnose
3061/// this condition when it is an error.
3062///
Douglas Gregore94866f2009-06-12 21:21:02 +00003063/// \returns true if there was an error, false otherwise.
3064bool Sema::CheckClassTemplatePartialSpecializationArgs(
3065 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00003066 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003067 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003068 // FIXME: the interface to this function will have to change to
3069 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003070 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003071
Anders Carlssonfb250522009-06-23 01:26:57 +00003072 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00003073
Douglas Gregore94866f2009-06-12 21:21:02 +00003074 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003075 // Determine whether the template argument list of the partial
3076 // specialization is identical to the implicit argument list of
3077 // the primary template. The caller may need to diagnostic this as
3078 // an error per C++ [temp.class.spec]p9b3.
3079 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003080 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003081 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3082 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003083 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003084 MirrorsPrimaryTemplate = false;
3085 } else if (TemplateTemplateParmDecl *TTP
3086 = dyn_cast<TemplateTemplateParmDecl>(
3087 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003088 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003089 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003090 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003091 if (!ArgDecl ||
3092 ArgDecl->getIndex() != TTP->getIndex() ||
3093 ArgDecl->getDepth() != TTP->getDepth())
3094 MirrorsPrimaryTemplate = false;
3095 }
3096 }
3097
Mike Stump1eb44332009-09-09 15:08:12 +00003098 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003099 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003100 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003101 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003102 }
3103
Anders Carlsson6360be72009-06-13 18:20:51 +00003104 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003105 if (!ArgExpr) {
3106 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003107 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003108 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003109
3110 // C++ [temp.class.spec]p8:
3111 // A non-type argument is non-specialized if it is the name of a
3112 // non-type parameter. All other non-type arguments are
3113 // specialized.
3114 //
3115 // Below, we check the two conditions that only apply to
3116 // specialized non-type arguments, so skip any non-specialized
3117 // arguments.
3118 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003119 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003120 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003121 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003122 (Param->getIndex() != NTTP->getIndex() ||
3123 Param->getDepth() != NTTP->getDepth()))
3124 MirrorsPrimaryTemplate = false;
3125
Douglas Gregore94866f2009-06-12 21:21:02 +00003126 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003127 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003128
3129 // C++ [temp.class.spec]p9:
3130 // Within the argument list of a class template partial
3131 // specialization, the following restrictions apply:
3132 // -- A partially specialized non-type argument expression
3133 // shall not involve a template parameter of the partial
3134 // specialization except when the argument expression is a
3135 // simple identifier.
3136 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003137 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003138 diag::err_dependent_non_type_arg_in_partial_spec)
3139 << ArgExpr->getSourceRange();
3140 return true;
3141 }
3142
3143 // -- The type of a template parameter corresponding to a
3144 // specialized non-type argument shall not be dependent on a
3145 // parameter of the specialization.
3146 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003147 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003148 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3149 << Param->getType()
3150 << ArgExpr->getSourceRange();
3151 Diag(Param->getLocation(), diag::note_template_param_here);
3152 return true;
3153 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003154
3155 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003156 }
3157
3158 return false;
3159}
3160
Douglas Gregor212e81c2009-03-25 00:13:59 +00003161Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003162Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3163 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00003164 SourceLocation KWLoc,
Douglas Gregorcc636682009-02-17 23:15:12 +00003165 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003166 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00003167 SourceLocation TemplateNameLoc,
3168 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00003169 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00003170 SourceLocation RAngleLoc,
3171 AttributeList *Attr,
3172 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003173 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00003174
Douglas Gregorcc636682009-02-17 23:15:12 +00003175 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00003176 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003177 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00003178 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3179
3180 if (!ClassTemplate) {
3181 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3182 << (Name.getAsTemplateDecl() &&
3183 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3184 return true;
3185 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003186
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003187 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003188 bool isPartialSpecialization = false;
3189
Douglas Gregor88b70942009-02-25 22:02:03 +00003190 // Check the validity of the template headers that introduce this
3191 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003192 // FIXME: We probably shouldn't complain about these headers for
3193 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00003194 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00003195 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3196 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003197 TemplateParameterLists.size(),
3198 isExplicitSpecialization);
Douglas Gregor05396e22009-08-25 17:23:04 +00003199 if (TemplateParams && TemplateParams->size() > 0) {
3200 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003201
Douglas Gregor05396e22009-08-25 17:23:04 +00003202 // C++ [temp.class.spec]p10:
3203 // The template parameter list of a specialization shall not
3204 // contain default template argument values.
3205 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3206 Decl *Param = TemplateParams->getParam(I);
3207 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3208 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003209 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003210 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00003211 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003212 }
3213 } else if (NonTypeTemplateParmDecl *NTTP
3214 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3215 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003216 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003217 diag::err_default_arg_in_partial_spec)
3218 << DefArg->getSourceRange();
3219 NTTP->setDefaultArgument(0);
3220 DefArg->Destroy(Context);
3221 }
3222 } else {
3223 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003224 if (TTP->hasDefaultArgument()) {
3225 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003226 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003227 << TTP->getDefaultArgument().getSourceRange();
3228 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003229 }
3230 }
3231 }
Douglas Gregora735b202009-10-13 14:39:41 +00003232 } else if (TemplateParams) {
3233 if (TUK == TUK_Friend)
3234 Diag(KWLoc, diag::err_template_spec_friend)
3235 << CodeModificationHint::CreateRemoval(
3236 SourceRange(TemplateParams->getTemplateLoc(),
3237 TemplateParams->getRAngleLoc()))
3238 << SourceRange(LAngleLoc, RAngleLoc);
3239 else
3240 isExplicitSpecialization = true;
3241 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003242 Diag(KWLoc, diag::err_template_spec_needs_header)
3243 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003244 isExplicitSpecialization = true;
3245 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003246
Douglas Gregorcc636682009-02-17 23:15:12 +00003247 // Check that the specialization uses the same tag kind as the
3248 // original template.
3249 TagDecl::TagKind Kind;
3250 switch (TagSpec) {
3251 default: assert(0 && "Unknown tag type!");
3252 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3253 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3254 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3255 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003256 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003257 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003258 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003259 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003260 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00003261 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003262 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003263 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003264 diag::note_previous_use);
3265 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3266 }
3267
Douglas Gregor40808ce2009-03-09 23:48:35 +00003268 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00003269 TemplateArgumentListInfo TemplateArgs;
3270 TemplateArgs.setLAngleLoc(LAngleLoc);
3271 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00003272 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003273
Douglas Gregorcc636682009-02-17 23:15:12 +00003274 // Check that the template argument list is well-formed for this
3275 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003276 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3277 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00003278 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3279 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003280 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003281
Mike Stump1eb44332009-09-09 15:08:12 +00003282 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003283 ClassTemplate->getTemplateParameters()->size()) &&
3284 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003285
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003286 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003287 // corresponds to these arguments.
3288 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003289 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003290 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003291 if (CheckClassTemplatePartialSpecializationArgs(
3292 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003293 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003294 return true;
3295
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003296 if (MirrorsPrimaryTemplate) {
3297 // C++ [temp.class.spec]p9b3:
3298 //
Mike Stump1eb44332009-09-09 15:08:12 +00003299 // -- The argument list of the specialization shall not be identical
3300 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003301 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003302 << (TUK == TUK_Definition)
Mike Stump1eb44332009-09-09 15:08:12 +00003303 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003304 RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003305 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003306 ClassTemplate->getIdentifier(),
3307 TemplateNameLoc,
3308 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003309 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003310 AS_none);
3311 }
3312
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003313 // FIXME: Diagnose friend partial specializations
3314
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003315 // FIXME: Template parameter list matters, too
Mike Stump1eb44332009-09-09 15:08:12 +00003316 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003317 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003318 Converted.flatSize(),
3319 Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003320 } else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00003321 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003322 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003323 Converted.flatSize(),
3324 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00003325 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003326 ClassTemplateSpecializationDecl *PrevDecl = 0;
3327
3328 if (isPartialSpecialization)
3329 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00003330 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003331 InsertPos);
3332 else
3333 PrevDecl
3334 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003335
3336 ClassTemplateSpecializationDecl *Specialization = 0;
3337
Douglas Gregor88b70942009-02-25 22:02:03 +00003338 // Check whether we can declare a class template specialization in
3339 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003340 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003341 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003342 TemplateNameLoc,
3343 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003344 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003345
Douglas Gregorb88e8882009-07-30 17:40:51 +00003346 // The canonical type
3347 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003348 if (PrevDecl &&
3349 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3350 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003351 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003352 // arguments was referenced but not declared, or we're only
3353 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003354 // declaration node as our own, updating its source location to
3355 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003356 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003357 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003358 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003359 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003360 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003361 // Build the canonical type that describes the converted template
3362 // arguments of the class template partial specialization.
3363 CanonType = Context.getTemplateSpecializationType(
3364 TemplateName(ClassTemplate),
3365 Converted.getFlatArguments(),
3366 Converted.flatSize());
3367
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003368 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003369 ClassTemplatePartialSpecializationDecl *PrevPartial
3370 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00003371 ClassTemplatePartialSpecializationDecl *Partial
3372 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003373 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003374 TemplateNameLoc,
3375 TemplateParams,
3376 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003377 Converted,
John McCalld5532b62009-11-23 01:53:49 +00003378 TemplateArgs,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003379 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003380
3381 if (PrevPartial) {
3382 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3383 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3384 } else {
3385 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3386 }
3387 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003388
Douglas Gregored9c0f92009-10-29 00:04:11 +00003389 // If we are providing an explicit specialization of a member class
3390 // template specialization, make a note of that.
3391 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3392 PrevPartial->setMemberSpecialization();
3393
Douglas Gregor031a5882009-06-13 00:26:55 +00003394 // Check that all of the template parameters of the class template
3395 // partial specialization are deducible from the template
3396 // arguments. If not, this class template partial specialization
3397 // will never be used.
3398 llvm::SmallVector<bool, 8> DeducibleParams;
3399 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003400 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003401 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003402 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003403 unsigned NumNonDeducible = 0;
3404 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3405 if (!DeducibleParams[I])
3406 ++NumNonDeducible;
3407
3408 if (NumNonDeducible) {
3409 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3410 << (NumNonDeducible > 1)
3411 << SourceRange(TemplateNameLoc, RAngleLoc);
3412 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3413 if (!DeducibleParams[I]) {
3414 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3415 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003416 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003417 diag::note_partial_spec_unused_parameter)
3418 << Param->getDeclName();
3419 else
Mike Stump1eb44332009-09-09 15:08:12 +00003420 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003421 diag::note_partial_spec_unused_parameter)
3422 << std::string("<anonymous>");
3423 }
3424 }
3425 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003426 } else {
3427 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003428 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003429 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00003430 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorcc636682009-02-17 23:15:12 +00003431 ClassTemplate->getDeclContext(),
3432 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003433 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003434 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003435 PrevDecl);
3436
3437 if (PrevDecl) {
3438 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3439 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3440 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003441 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00003442 InsertPos);
3443 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00003444
3445 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003446 }
3447
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003448 // C++ [temp.expl.spec]p6:
3449 // If a template, a member template or the member of a class template is
3450 // explicitly specialized then that specialization shall be declared
3451 // before the first use of that specialization that would cause an implicit
3452 // instantiation to take place, in every translation unit in which such a
3453 // use occurs; no diagnostic is required.
3454 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3455 SourceRange Range(TemplateNameLoc, RAngleLoc);
3456 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3457 << Context.getTypeDeclType(Specialization) << Range;
3458
3459 Diag(PrevDecl->getPointOfInstantiation(),
3460 diag::note_instantiation_required_here)
3461 << (PrevDecl->getTemplateSpecializationKind()
3462 != TSK_ImplicitInstantiation);
3463 return true;
3464 }
3465
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003466 // If this is not a friend, note that this is an explicit specialization.
3467 if (TUK != TUK_Friend)
3468 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003469
3470 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003471 if (TUK == TUK_Definition) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003472 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003473 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003474 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003475 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003476 Diag(Def->getLocation(), diag::note_previous_definition);
3477 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003478 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003479 }
3480 }
3481
Douglas Gregorfc705b82009-02-26 22:19:44 +00003482 // Build the fully-sugared type for this class template
3483 // specialization as the user wrote in the specialization
3484 // itself. This means that we'll pretty-print the type retrieved
3485 // from the specialization's declaration the way that the user
3486 // actually wrote the specialization, rather than formatting the
3487 // name based on the "canonical" representation used to store the
3488 // template arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003489 QualType WrittenTy
John McCalld5532b62009-11-23 01:53:49 +00003490 = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003491 if (TUK != TUK_Friend)
3492 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003493 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00003494
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003495 // C++ [temp.expl.spec]p9:
3496 // A template explicit specialization is in the scope of the
3497 // namespace in which the template was defined.
3498 //
3499 // We actually implement this paragraph where we set the semantic
3500 // context (in the creation of the ClassTemplateSpecializationDecl),
3501 // but we also maintain the lexical context where the actual
3502 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00003503 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003504
Douglas Gregorcc636682009-02-17 23:15:12 +00003505 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003506 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00003507 Specialization->startDefinition();
3508
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003509 if (TUK == TUK_Friend) {
3510 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3511 TemplateNameLoc,
3512 WrittenTy.getTypePtr(),
3513 /*FIXME:*/KWLoc);
3514 Friend->setAccess(AS_public);
3515 CurContext->addDecl(Friend);
3516 } else {
3517 // Add the specialization into its lexical context, so that it can
3518 // be seen when iterating through the list of declarations in that
3519 // context. However, specializations are not found by name lookup.
3520 CurContext->addDecl(Specialization);
3521 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003522 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003523}
Douglas Gregord57959a2009-03-27 23:10:48 +00003524
Mike Stump1eb44332009-09-09 15:08:12 +00003525Sema::DeclPtrTy
3526Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00003527 MultiTemplateParamsArg TemplateParameterLists,
3528 Declarator &D) {
3529 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3530}
3531
Mike Stump1eb44332009-09-09 15:08:12 +00003532Sema::DeclPtrTy
3533Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003534 MultiTemplateParamsArg TemplateParameterLists,
3535 Declarator &D) {
3536 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3537 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3538 "Not a function declarator!");
3539 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00003540
Douglas Gregor52591bf2009-06-24 00:54:41 +00003541 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00003542 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00003543 }
Mike Stump1eb44332009-09-09 15:08:12 +00003544
Douglas Gregor52591bf2009-06-24 00:54:41 +00003545 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003546
3547 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003548 move(TemplateParameterLists),
3549 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003550 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003551 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00003552 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00003553 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003554 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3555 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00003556 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00003557}
3558
Douglas Gregor454885e2009-10-15 15:54:05 +00003559/// \brief Diagnose cases where we have an explicit template specialization
3560/// before/after an explicit template instantiation, producing diagnostics
3561/// for those cases where they are required and determining whether the
3562/// new specialization/instantiation will have any effect.
3563///
Douglas Gregor454885e2009-10-15 15:54:05 +00003564/// \param NewLoc the location of the new explicit specialization or
3565/// instantiation.
3566///
3567/// \param NewTSK the kind of the new explicit specialization or instantiation.
3568///
3569/// \param PrevDecl the previous declaration of the entity.
3570///
3571/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3572///
3573/// \param PrevPointOfInstantiation if valid, indicates where the previus
3574/// declaration was instantiated (either implicitly or explicitly).
3575///
3576/// \param SuppressNew will be set to true to indicate that the new
3577/// specialization or instantiation has no effect and should be ignored.
3578///
3579/// \returns true if there was an error that should prevent the introduction of
3580/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00003581bool
3582Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3583 TemplateSpecializationKind NewTSK,
3584 NamedDecl *PrevDecl,
3585 TemplateSpecializationKind PrevTSK,
3586 SourceLocation PrevPointOfInstantiation,
3587 bool &SuppressNew) {
Douglas Gregor454885e2009-10-15 15:54:05 +00003588 SuppressNew = false;
3589
3590 switch (NewTSK) {
3591 case TSK_Undeclared:
3592 case TSK_ImplicitInstantiation:
3593 assert(false && "Don't check implicit instantiations here");
3594 return false;
3595
3596 case TSK_ExplicitSpecialization:
3597 switch (PrevTSK) {
3598 case TSK_Undeclared:
3599 case TSK_ExplicitSpecialization:
3600 // Okay, we're just specializing something that is either already
3601 // explicitly specialized or has merely been mentioned without any
3602 // instantiation.
3603 return false;
3604
3605 case TSK_ImplicitInstantiation:
3606 if (PrevPointOfInstantiation.isInvalid()) {
3607 // The declaration itself has not actually been instantiated, so it is
3608 // still okay to specialize it.
3609 return false;
3610 }
3611 // Fall through
3612
3613 case TSK_ExplicitInstantiationDeclaration:
3614 case TSK_ExplicitInstantiationDefinition:
3615 assert((PrevTSK == TSK_ImplicitInstantiation ||
3616 PrevPointOfInstantiation.isValid()) &&
3617 "Explicit instantiation without point of instantiation?");
3618
3619 // C++ [temp.expl.spec]p6:
3620 // If a template, a member template or the member of a class template
3621 // is explicitly specialized then that specialization shall be declared
3622 // before the first use of that specialization that would cause an
3623 // implicit instantiation to take place, in every translation unit in
3624 // which such a use occurs; no diagnostic is required.
Douglas Gregor0d035142009-10-27 18:42:08 +00003625 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00003626 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003627 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00003628 << (PrevTSK != TSK_ImplicitInstantiation);
3629
3630 return true;
3631 }
3632 break;
3633
3634 case TSK_ExplicitInstantiationDeclaration:
3635 switch (PrevTSK) {
3636 case TSK_ExplicitInstantiationDeclaration:
3637 // This explicit instantiation declaration is redundant (that's okay).
3638 SuppressNew = true;
3639 return false;
3640
3641 case TSK_Undeclared:
3642 case TSK_ImplicitInstantiation:
3643 // We're explicitly instantiating something that may have already been
3644 // implicitly instantiated; that's fine.
3645 return false;
3646
3647 case TSK_ExplicitSpecialization:
3648 // C++0x [temp.explicit]p4:
3649 // For a given set of template parameters, if an explicit instantiation
3650 // of a template appears after a declaration of an explicit
3651 // specialization for that template, the explicit instantiation has no
3652 // effect.
3653 return false;
3654
3655 case TSK_ExplicitInstantiationDefinition:
3656 // C++0x [temp.explicit]p10:
3657 // If an entity is the subject of both an explicit instantiation
3658 // declaration and an explicit instantiation definition in the same
3659 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00003660 Diag(NewLoc,
3661 diag::err_explicit_instantiation_declaration_after_definition);
3662 Diag(PrevPointOfInstantiation,
3663 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00003664 assert(PrevPointOfInstantiation.isValid() &&
3665 "Explicit instantiation without point of instantiation?");
3666 SuppressNew = true;
3667 return false;
3668 }
3669 break;
3670
3671 case TSK_ExplicitInstantiationDefinition:
3672 switch (PrevTSK) {
3673 case TSK_Undeclared:
3674 case TSK_ImplicitInstantiation:
3675 // We're explicitly instantiating something that may have already been
3676 // implicitly instantiated; that's fine.
3677 return false;
3678
3679 case TSK_ExplicitSpecialization:
3680 // C++ DR 259, C++0x [temp.explicit]p4:
3681 // For a given set of template parameters, if an explicit
3682 // instantiation of a template appears after a declaration of
3683 // an explicit specialization for that template, the explicit
3684 // instantiation has no effect.
3685 //
3686 // In C++98/03 mode, we only give an extension warning here, because it
3687 // is not not harmful to try to explicitly instantiate something that
3688 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00003689 if (!getLangOptions().CPlusPlus0x) {
3690 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00003691 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003692 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00003693 diag::note_previous_template_specialization);
3694 }
3695 SuppressNew = true;
3696 return false;
3697
3698 case TSK_ExplicitInstantiationDeclaration:
3699 // We're explicity instantiating a definition for something for which we
3700 // were previously asked to suppress instantiations. That's fine.
3701 return false;
3702
3703 case TSK_ExplicitInstantiationDefinition:
3704 // C++0x [temp.spec]p5:
3705 // For a given template and a given set of template-arguments,
3706 // - an explicit instantiation definition shall appear at most once
3707 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00003708 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00003709 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003710 Diag(PrevPointOfInstantiation,
3711 diag::note_previous_explicit_instantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00003712 SuppressNew = true;
3713 return false;
3714 }
3715 break;
3716 }
3717
3718 assert(false && "Missing specialization/instantiation case?");
3719
3720 return false;
3721}
3722
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003723/// \brief Perform semantic analysis for the given function template
3724/// specialization.
3725///
3726/// This routine performs all of the semantic analysis required for an
3727/// explicit function template specialization. On successful completion,
3728/// the function declaration \p FD will become a function template
3729/// specialization.
3730///
3731/// \param FD the function declaration, which will be updated to become a
3732/// function template specialization.
3733///
3734/// \param HasExplicitTemplateArgs whether any template arguments were
3735/// explicitly provided.
3736///
3737/// \param LAngleLoc the location of the left angle bracket ('<'), if
3738/// template arguments were explicitly provided.
3739///
3740/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3741/// if any.
3742///
3743/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3744/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3745/// true as in, e.g., \c void sort<>(char*, char*);
3746///
3747/// \param RAngleLoc the location of the right angle bracket ('>'), if
3748/// template arguments were explicitly provided.
3749///
3750/// \param PrevDecl the set of declarations that
3751bool
3752Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00003753 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00003754 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003755 // The set of function template specializations that could match this
3756 // explicit function template specialization.
3757 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3758 CandidateSet Candidates;
3759
3760 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall68263142009-11-18 22:49:29 +00003761 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3762 I != E; ++I) {
3763 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3764 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003765 // Only consider templates found within the same semantic lookup scope as
3766 // FD.
3767 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3768 continue;
3769
3770 // C++ [temp.expl.spec]p11:
3771 // A trailing template-argument can be left unspecified in the
3772 // template-id naming an explicit function template specialization
3773 // provided it can be deduced from the function argument type.
3774 // Perform template argument deduction to determine whether we may be
3775 // specializing this template.
3776 // FIXME: It is somewhat wasteful to build
3777 TemplateDeductionInfo Info(Context);
3778 FunctionDecl *Specialization = 0;
3779 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00003780 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003781 FD->getType(),
3782 Specialization,
3783 Info)) {
3784 // FIXME: Template argument deduction failed; record why it failed, so
3785 // that we can provide nifty diagnostics.
3786 (void)TDK;
3787 continue;
3788 }
3789
3790 // Record this candidate.
3791 Candidates.push_back(Specialization);
3792 }
3793 }
3794
Douglas Gregorc5df30f2009-09-26 03:41:46 +00003795 // Find the most specialized function template.
3796 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3797 Candidates.size(),
3798 TPOC_Other,
3799 FD->getLocation(),
3800 PartialDiagnostic(diag::err_function_template_spec_no_match)
3801 << FD->getDeclName(),
3802 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00003803 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorc5df30f2009-09-26 03:41:46 +00003804 PartialDiagnostic(diag::note_function_template_spec_matched));
3805 if (!Specialization)
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003806 return true;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003807
3808 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003809 // If so, we have run afoul of .
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003810
Douglas Gregord5cb8762009-10-07 00:13:32 +00003811 // Check the scope of this explicit specialization.
3812 if (CheckTemplateSpecializationScope(*this,
3813 Specialization->getPrimaryTemplate(),
3814 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003815 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003816 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003817
3818 // C++ [temp.expl.spec]p6:
3819 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00003820 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003821 // before the first use of that specialization that would cause an implicit
3822 // instantiation to take place, in every translation unit in which such a
3823 // use occurs; no diagnostic is required.
3824 FunctionTemplateSpecializationInfo *SpecInfo
3825 = Specialization->getTemplateSpecializationInfo();
3826 assert(SpecInfo && "Function template specialization info missing?");
3827 if (SpecInfo->getPointOfInstantiation().isValid()) {
3828 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3829 << FD;
3830 Diag(SpecInfo->getPointOfInstantiation(),
3831 diag::note_instantiation_required_here)
3832 << (Specialization->getTemplateSpecializationKind()
3833 != TSK_ImplicitInstantiation);
3834 return true;
3835 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003836
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003837 // Mark the prior declaration as an explicit specialization, so that later
3838 // clients know that this is an explicit specialization.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003839 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003840
3841 // Turn the given function declaration into a function template
3842 // specialization, with the template arguments from the previous
3843 // specialization.
3844 FD->setFunctionTemplateSpecialization(Context,
3845 Specialization->getPrimaryTemplate(),
3846 new (Context) TemplateArgumentList(
3847 *Specialization->getTemplateSpecializationArgs()),
3848 /*InsertPos=*/0,
3849 TSK_ExplicitSpecialization);
3850
3851 // The "previous declaration" for this function template specialization is
3852 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00003853 Previous.clear();
3854 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003855 return false;
3856}
3857
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003858/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003859/// specialization.
3860///
3861/// This routine performs all of the semantic analysis required for an
3862/// explicit member function specialization. On successful completion,
3863/// the function declaration \p FD will become a member function
3864/// specialization.
3865///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003866/// \param Member the member declaration, which will be updated to become a
3867/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003868///
John McCall68263142009-11-18 22:49:29 +00003869/// \param Previous the set of declarations, one of which may be specialized
3870/// by this function specialization; the set will be modified to contain the
3871/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003872bool
John McCall68263142009-11-18 22:49:29 +00003873Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003874 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3875
3876 // Try to find the member we are instantiating.
3877 NamedDecl *Instantiation = 0;
3878 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003879 MemberSpecializationInfo *MSInfo = 0;
3880
John McCall68263142009-11-18 22:49:29 +00003881 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003882 // Nowhere to look anyway.
3883 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00003884 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3885 I != E; ++I) {
3886 NamedDecl *D = (*I)->getUnderlyingDecl();
3887 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003888 if (Context.hasSameType(Function->getType(), Method->getType())) {
3889 Instantiation = Method;
3890 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003891 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003892 break;
3893 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003894 }
3895 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003896 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00003897 VarDecl *PrevVar;
3898 if (Previous.isSingleResult() &&
3899 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003900 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00003901 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003902 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003903 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003904 }
3905 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00003906 CXXRecordDecl *PrevRecord;
3907 if (Previous.isSingleResult() &&
3908 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
3909 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003910 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003911 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003912 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003913 }
3914
3915 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003916 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003917 // specializations are always out-of-line, the caller will complain about
3918 // this mismatch later.
3919 return false;
3920 }
3921
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003922 // Make sure that this is a specialization of a member.
3923 if (!InstantiatedFrom) {
3924 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3925 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003926 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3927 return true;
3928 }
3929
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003930 // C++ [temp.expl.spec]p6:
3931 // If a template, a member template or the member of a class template is
3932 // explicitly specialized then that spe- cialization shall be declared
3933 // before the first use of that specialization that would cause an implicit
3934 // instantiation to take place, in every translation unit in which such a
3935 // use occurs; no diagnostic is required.
3936 assert(MSInfo && "Member specialization info missing?");
3937 if (MSInfo->getPointOfInstantiation().isValid()) {
3938 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3939 << Member;
3940 Diag(MSInfo->getPointOfInstantiation(),
3941 diag::note_instantiation_required_here)
3942 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3943 return true;
3944 }
3945
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003946 // Check the scope of this explicit specialization.
3947 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003948 InstantiatedFrom,
3949 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003950 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003951 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00003952
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003953 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00003954 // the original declaration to note that it is an explicit specialization
3955 // (if it was previously an implicit instantiation). This latter step
3956 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003957 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00003958 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3959 if (InstantiationFunction->getTemplateSpecializationKind() ==
3960 TSK_ImplicitInstantiation) {
3961 InstantiationFunction->setTemplateSpecializationKind(
3962 TSK_ExplicitSpecialization);
3963 InstantiationFunction->setLocation(Member->getLocation());
3964 }
3965
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003966 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3967 cast<CXXMethodDecl>(InstantiatedFrom),
3968 TSK_ExplicitSpecialization);
3969 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00003970 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3971 if (InstantiationVar->getTemplateSpecializationKind() ==
3972 TSK_ImplicitInstantiation) {
3973 InstantiationVar->setTemplateSpecializationKind(
3974 TSK_ExplicitSpecialization);
3975 InstantiationVar->setLocation(Member->getLocation());
3976 }
3977
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003978 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3979 cast<VarDecl>(InstantiatedFrom),
3980 TSK_ExplicitSpecialization);
3981 } else {
3982 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00003983 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3984 if (InstantiationClass->getTemplateSpecializationKind() ==
3985 TSK_ImplicitInstantiation) {
3986 InstantiationClass->setTemplateSpecializationKind(
3987 TSK_ExplicitSpecialization);
3988 InstantiationClass->setLocation(Member->getLocation());
3989 }
3990
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003991 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00003992 cast<CXXRecordDecl>(InstantiatedFrom),
3993 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003994 }
3995
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003996 // Save the caller the trouble of having to figure out which declaration
3997 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00003998 Previous.clear();
3999 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004000 return false;
4001}
4002
Douglas Gregor558c0322009-10-14 23:41:34 +00004003/// \brief Check the scope of an explicit instantiation.
4004static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4005 SourceLocation InstLoc,
4006 bool WasQualifiedName) {
4007 DeclContext *ExpectedContext
4008 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4009 DeclContext *CurContext = S.CurContext->getLookupContext();
4010
4011 // C++0x [temp.explicit]p2:
4012 // An explicit instantiation shall appear in an enclosing namespace of its
4013 // template.
4014 //
4015 // This is DR275, which we do not retroactively apply to C++98/03.
4016 if (S.getLangOptions().CPlusPlus0x &&
4017 !CurContext->Encloses(ExpectedContext)) {
4018 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4019 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4020 << D << NS;
4021 else
4022 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4023 << D;
4024 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4025 return;
4026 }
4027
4028 // C++0x [temp.explicit]p2:
4029 // If the name declared in the explicit instantiation is an unqualified
4030 // name, the explicit instantiation shall appear in the namespace where
4031 // its template is declared or, if that namespace is inline (7.3.1), any
4032 // namespace from its enclosing namespace set.
4033 if (WasQualifiedName)
4034 return;
4035
4036 if (CurContext->Equals(ExpectedContext))
4037 return;
4038
4039 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4040 << D << ExpectedContext;
4041 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4042}
4043
4044/// \brief Determine whether the given scope specifier has a template-id in it.
4045static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4046 if (!SS.isSet())
4047 return false;
4048
4049 // C++0x [temp.explicit]p2:
4050 // If the explicit instantiation is for a member function, a member class
4051 // or a static data member of a class template specialization, the name of
4052 // the class template specialization in the qualified-id for the member
4053 // name shall be a simple-template-id.
4054 //
4055 // C++98 has the same restriction, just worded differently.
4056 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4057 NNS; NNS = NNS->getPrefix())
4058 if (Type *T = NNS->getAsType())
4059 if (isa<TemplateSpecializationType>(T))
4060 return true;
4061
4062 return false;
4063}
4064
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004065// Explicit instantiation of a class template specialization
Douglas Gregor45f96552009-09-04 06:33:52 +00004066// FIXME: Implement extern template semantics
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004067Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004068Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004069 SourceLocation ExternLoc,
4070 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004071 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004072 SourceLocation KWLoc,
4073 const CXXScopeSpec &SS,
4074 TemplateTy TemplateD,
4075 SourceLocation TemplateNameLoc,
4076 SourceLocation LAngleLoc,
4077 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004078 SourceLocation RAngleLoc,
4079 AttributeList *Attr) {
4080 // Find the class template we're specializing
4081 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004082 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004083 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4084
4085 // Check that the specialization uses the same tag kind as the
4086 // original template.
4087 TagDecl::TagKind Kind;
4088 switch (TagSpec) {
4089 default: assert(0 && "Unknown tag type!");
4090 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4091 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4092 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4093 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004094 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004095 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004096 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004097 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004098 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00004099 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004100 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004101 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004102 diag::note_previous_use);
4103 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4104 }
4105
Douglas Gregor558c0322009-10-14 23:41:34 +00004106 // C++0x [temp.explicit]p2:
4107 // There are two forms of explicit instantiation: an explicit instantiation
4108 // definition and an explicit instantiation declaration. An explicit
4109 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00004110 TemplateSpecializationKind TSK
4111 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4112 : TSK_ExplicitInstantiationDeclaration;
4113
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004114 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004115 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004116 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004117
4118 // Check that the template argument list is well-formed for this
4119 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00004120 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4121 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00004122 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4123 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004124 return true;
4125
Mike Stump1eb44332009-09-09 15:08:12 +00004126 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004127 ClassTemplate->getTemplateParameters()->size()) &&
4128 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004129
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004130 // Find the class template specialization declaration that
4131 // corresponds to these arguments.
4132 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00004133 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00004134 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00004135 Converted.flatSize(),
4136 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004137 void *InsertPos = 0;
4138 ClassTemplateSpecializationDecl *PrevDecl
4139 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4140
Douglas Gregord5cb8762009-10-07 00:13:32 +00004141 // C++0x [temp.explicit]p2:
4142 // [...] An explicit instantiation shall appear in an enclosing
4143 // namespace of its template. [...]
4144 //
4145 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004146 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4147 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00004148
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004149 ClassTemplateSpecializationDecl *Specialization = 0;
4150
Douglas Gregord78f5982009-11-25 06:01:46 +00004151 bool ReusedDecl = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004152 if (PrevDecl) {
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004153 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004154 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004155 PrevDecl,
4156 PrevDecl->getSpecializationKind(),
4157 PrevDecl->getPointOfInstantiation(),
4158 SuppressNew))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004159 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004160
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004161 if (SuppressNew)
Douglas Gregor52604ab2009-09-11 21:19:12 +00004162 return DeclPtrTy::make(PrevDecl);
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004163
Douglas Gregor52604ab2009-09-11 21:19:12 +00004164 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4165 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4166 // Since the only prior class template specialization with these
4167 // arguments was referenced but not declared, reuse that
4168 // declaration node as our own, updating its source location to
4169 // reflect our new declaration.
4170 Specialization = PrevDecl;
4171 Specialization->setLocation(TemplateNameLoc);
4172 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00004173 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00004174 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004175 }
Douglas Gregor52604ab2009-09-11 21:19:12 +00004176
4177 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004178 // Create a new class template specialization declaration node for
4179 // this explicit specialization.
4180 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00004181 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004182 ClassTemplate->getDeclContext(),
4183 TemplateNameLoc,
4184 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00004185 Converted, PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004186
Douglas Gregor52604ab2009-09-11 21:19:12 +00004187 if (PrevDecl) {
4188 // Remove the previous declaration from the folding set, since we want
4189 // to introduce a new declaration.
4190 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4191 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4192 }
4193
4194 // Insert the new specialization.
4195 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004196 }
4197
4198 // Build the fully-sugared type for this explicit instantiation as
4199 // the user wrote in the explicit instantiation itself. This means
4200 // that we'll pretty-print the type retrieved from the
4201 // specialization's declaration the way that the user actually wrote
4202 // the explicit instantiation, rather than formatting the name based
4203 // on the "canonical" representation used to store the template
4204 // arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004205 QualType WrittenTy
John McCalld5532b62009-11-23 01:53:49 +00004206 = Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004207 Context.getTypeDeclType(Specialization));
4208 Specialization->setTypeAsWritten(WrittenTy);
4209 TemplateArgsIn.release();
4210
Douglas Gregord78f5982009-11-25 06:01:46 +00004211 if (!ReusedDecl) {
4212 // Add the explicit instantiation into its lexical context. However,
4213 // since explicit instantiations are never found by name lookup, we
4214 // just put it into the declaration context directly.
4215 Specialization->setLexicalDeclContext(CurContext);
4216 CurContext->addDecl(Specialization);
4217 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004218
4219 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004220 // A definition of a class template or class member template
4221 // shall be in scope at the point of the explicit instantiation of
4222 // the class template or class member template.
4223 //
4224 // This check comes when we actually try to perform the
4225 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004226 ClassTemplateSpecializationDecl *Def
4227 = cast_or_null<ClassTemplateSpecializationDecl>(
4228 Specialization->getDefinition(Context));
4229 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004230 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor0d035142009-10-27 18:42:08 +00004231
4232 // Instantiate the members of this class template specialization.
4233 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4234 Specialization->getDefinition(Context));
4235 if (Def)
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004236 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004237
4238 return DeclPtrTy::make(Specialization);
4239}
4240
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004241// Explicit instantiation of a member class of a class template.
4242Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004243Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004244 SourceLocation ExternLoc,
4245 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004246 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004247 SourceLocation KWLoc,
4248 const CXXScopeSpec &SS,
4249 IdentifierInfo *Name,
4250 SourceLocation NameLoc,
4251 AttributeList *Attr) {
4252
Douglas Gregor402abb52009-05-28 23:31:59 +00004253 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004254 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00004255 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004256 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00004257 MultiTemplateParamsArg(*this, 0, 0),
4258 Owned, IsDependent);
4259 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4260
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004261 if (!TagD)
4262 return true;
4263
4264 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4265 if (Tag->isEnum()) {
4266 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4267 << Context.getTypeDeclType(Tag);
4268 return true;
4269 }
4270
Douglas Gregord0c87372009-05-27 17:30:49 +00004271 if (Tag->isInvalidDecl())
4272 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004273
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004274 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4275 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4276 if (!Pattern) {
4277 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4278 << Context.getTypeDeclType(Record);
4279 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4280 return true;
4281 }
4282
Douglas Gregor558c0322009-10-14 23:41:34 +00004283 // C++0x [temp.explicit]p2:
4284 // If the explicit instantiation is for a class or member class, the
4285 // elaborated-type-specifier in the declaration shall include a
4286 // simple-template-id.
4287 //
4288 // C++98 has the same restriction, just worded differently.
4289 if (!ScopeSpecifierHasTemplateId(SS))
4290 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4291 << Record << SS.getRange();
4292
4293 // C++0x [temp.explicit]p2:
4294 // There are two forms of explicit instantiation: an explicit instantiation
4295 // definition and an explicit instantiation declaration. An explicit
4296 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004297 TemplateSpecializationKind TSK
4298 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4299 : TSK_ExplicitInstantiationDeclaration;
4300
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004301 // C++0x [temp.explicit]p2:
4302 // [...] An explicit instantiation shall appear in an enclosing
4303 // namespace of its template. [...]
4304 //
4305 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004306 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004307
4308 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004309 CXXRecordDecl *PrevDecl
4310 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4311 if (!PrevDecl && Record->getDefinition(Context))
4312 PrevDecl = Record;
4313 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004314 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4315 bool SuppressNew = false;
4316 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004317 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004318 PrevDecl,
4319 MSInfo->getTemplateSpecializationKind(),
4320 MSInfo->getPointOfInstantiation(),
4321 SuppressNew))
4322 return true;
4323 if (SuppressNew)
4324 return TagD;
4325 }
4326
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004327 CXXRecordDecl *RecordDef
4328 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4329 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004330 // C++ [temp.explicit]p3:
4331 // A definition of a member class of a class template shall be in scope
4332 // at the point of an explicit instantiation of the member class.
4333 CXXRecordDecl *Def
4334 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4335 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004336 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4337 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004338 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4339 << Pattern;
4340 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004341 } else {
4342 if (InstantiateClass(NameLoc, Record, Def,
4343 getTemplateInstantiationArgs(Record),
4344 TSK))
4345 return true;
4346
4347 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4348 if (!RecordDef)
4349 return true;
4350 }
4351 }
4352
4353 // Instantiate all of the members of the class.
4354 InstantiateClassMembers(NameLoc, RecordDef,
4355 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004356
Mike Stump390b4cc2009-05-16 07:39:55 +00004357 // FIXME: We don't have any representation for explicit instantiations of
4358 // member classes. Such a representation is not needed for compilation, but it
4359 // should be available for clients that want to see all of the declarations in
4360 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004361 return TagD;
4362}
4363
Douglas Gregord5a423b2009-09-25 18:43:00 +00004364Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4365 SourceLocation ExternLoc,
4366 SourceLocation TemplateLoc,
4367 Declarator &D) {
4368 // Explicit instantiations always require a name.
4369 DeclarationName Name = GetNameForDeclarator(D);
4370 if (!Name) {
4371 if (!D.isInvalidType())
4372 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4373 diag::err_explicit_instantiation_requires_name)
4374 << D.getDeclSpec().getSourceRange()
4375 << D.getSourceRange();
4376
4377 return true;
4378 }
4379
4380 // The scope passed in may not be a decl scope. Zip up the scope tree until
4381 // we find one that is.
4382 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4383 (S->getFlags() & Scope::TemplateParamScope) != 0)
4384 S = S->getParent();
4385
4386 // Determine the type of the declaration.
4387 QualType R = GetTypeForDeclarator(D, S, 0);
4388 if (R.isNull())
4389 return true;
4390
4391 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4392 // Cannot explicitly instantiate a typedef.
4393 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4394 << Name;
4395 return true;
4396 }
4397
Douglas Gregor663b5a02009-10-14 20:14:33 +00004398 // C++0x [temp.explicit]p1:
4399 // [...] An explicit instantiation of a function template shall not use the
4400 // inline or constexpr specifiers.
4401 // Presumably, this also applies to member functions of class templates as
4402 // well.
4403 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4404 Diag(D.getDeclSpec().getInlineSpecLoc(),
4405 diag::err_explicit_instantiation_inline)
Chris Lattner29d9c1a2009-12-06 17:36:05 +00004406 <<CodeModificationHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00004407
4408 // FIXME: check for constexpr specifier.
4409
Douglas Gregor558c0322009-10-14 23:41:34 +00004410 // C++0x [temp.explicit]p2:
4411 // There are two forms of explicit instantiation: an explicit instantiation
4412 // definition and an explicit instantiation declaration. An explicit
4413 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00004414 TemplateSpecializationKind TSK
4415 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4416 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00004417
John McCalla24dc2e2009-11-17 02:14:36 +00004418 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4419 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004420
4421 if (!R->isFunctionType()) {
4422 // C++ [temp.explicit]p1:
4423 // A [...] static data member of a class template can be explicitly
4424 // instantiated from the member definition associated with its class
4425 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00004426 if (Previous.isAmbiguous())
4427 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004428
John McCall1bcee0a2009-12-02 08:25:40 +00004429 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004430 if (!Prev || !Prev->isStaticDataMember()) {
4431 // We expect to see a data data member here.
4432 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4433 << Name;
4434 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4435 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00004436 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004437 return true;
4438 }
4439
4440 if (!Prev->getInstantiatedFromStaticDataMember()) {
4441 // FIXME: Check for explicit specialization?
4442 Diag(D.getIdentifierLoc(),
4443 diag::err_explicit_instantiation_data_member_not_instantiated)
4444 << Prev;
4445 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4446 // FIXME: Can we provide a note showing where this was declared?
4447 return true;
4448 }
4449
Douglas Gregor558c0322009-10-14 23:41:34 +00004450 // C++0x [temp.explicit]p2:
4451 // If the explicit instantiation is for a member function, a member class
4452 // or a static data member of a class template specialization, the name of
4453 // the class template specialization in the qualified-id for the member
4454 // name shall be a simple-template-id.
4455 //
4456 // C++98 has the same restriction, just worded differently.
4457 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4458 Diag(D.getIdentifierLoc(),
4459 diag::err_explicit_instantiation_without_qualified_id)
4460 << Prev << D.getCXXScopeSpec().getRange();
4461
4462 // Check the scope of this explicit instantiation.
4463 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4464
Douglas Gregor454885e2009-10-15 15:54:05 +00004465 // Verify that it is okay to explicitly instantiate here.
4466 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4467 assert(MSInfo && "Missing static data member specialization info?");
4468 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004469 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00004470 MSInfo->getTemplateSpecializationKind(),
4471 MSInfo->getPointOfInstantiation(),
4472 SuppressNew))
4473 return true;
4474 if (SuppressNew)
4475 return DeclPtrTy();
4476
Douglas Gregord5a423b2009-09-25 18:43:00 +00004477 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004478 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004479 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004480 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4481 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004482
4483 // FIXME: Create an ExplicitInstantiation node?
4484 return DeclPtrTy();
4485 }
4486
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004487 // If the declarator is a template-id, translate the parser's template
4488 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00004489 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00004490 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004491 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4492 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00004493 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4494 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00004495 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4496 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00004497 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00004498 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00004499 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00004500 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00004501 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004502
Douglas Gregord5a423b2009-09-25 18:43:00 +00004503 // C++ [temp.explicit]p1:
4504 // A [...] function [...] can be explicitly instantiated from its template.
4505 // A member function [...] of a class template can be explicitly
4506 // instantiated from the member definition associated with its class
4507 // template.
Douglas Gregord5a423b2009-09-25 18:43:00 +00004508 llvm::SmallVector<FunctionDecl *, 8> Matches;
4509 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4510 P != PEnd; ++P) {
4511 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00004512 if (!HasExplicitTemplateArgs) {
4513 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4514 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4515 Matches.clear();
4516 Matches.push_back(Method);
4517 break;
4518 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00004519 }
4520 }
4521
4522 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4523 if (!FunTmpl)
4524 continue;
4525
4526 TemplateDeductionInfo Info(Context);
4527 FunctionDecl *Specialization = 0;
4528 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004529 = DeduceTemplateArguments(FunTmpl,
4530 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00004531 R, Specialization, Info)) {
4532 // FIXME: Keep track of almost-matches?
4533 (void)TDK;
4534 continue;
4535 }
4536
4537 Matches.push_back(Specialization);
4538 }
4539
4540 // Find the most specialized function template specialization.
4541 FunctionDecl *Specialization
4542 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4543 D.getIdentifierLoc(),
4544 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4545 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4546 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4547
4548 if (!Specialization)
4549 return true;
4550
Douglas Gregor0a897e32009-10-15 17:21:20 +00004551 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00004552 Diag(D.getIdentifierLoc(),
4553 diag::err_explicit_instantiation_member_function_not_instantiated)
4554 << Specialization
4555 << (Specialization->getTemplateSpecializationKind() ==
4556 TSK_ExplicitSpecialization);
4557 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4558 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00004559 }
Douglas Gregor558c0322009-10-14 23:41:34 +00004560
Douglas Gregor0a897e32009-10-15 17:21:20 +00004561 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00004562 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4563 PrevDecl = Specialization;
4564
Douglas Gregor0a897e32009-10-15 17:21:20 +00004565 if (PrevDecl) {
4566 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004567 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00004568 PrevDecl,
4569 PrevDecl->getTemplateSpecializationKind(),
4570 PrevDecl->getPointOfInstantiation(),
4571 SuppressNew))
4572 return true;
4573
4574 // FIXME: We may still want to build some representation of this
4575 // explicit specialization.
4576 if (SuppressNew)
4577 return DeclPtrTy();
4578 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00004579
4580 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00004581
4582 if (TSK == TSK_ExplicitInstantiationDefinition)
4583 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4584 false, /*DefinitionRequired=*/true);
Douglas Gregor0a897e32009-10-15 17:21:20 +00004585
Douglas Gregor558c0322009-10-14 23:41:34 +00004586 // C++0x [temp.explicit]p2:
4587 // If the explicit instantiation is for a member function, a member class
4588 // or a static data member of a class template specialization, the name of
4589 // the class template specialization in the qualified-id for the member
4590 // name shall be a simple-template-id.
4591 //
4592 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004593 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004594 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00004595 D.getCXXScopeSpec().isSet() &&
4596 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4597 Diag(D.getIdentifierLoc(),
4598 diag::err_explicit_instantiation_without_qualified_id)
4599 << Specialization << D.getCXXScopeSpec().getRange();
4600
4601 CheckExplicitInstantiationScope(*this,
4602 FunTmpl? (NamedDecl *)FunTmpl
4603 : Specialization->getInstantiatedFromMemberFunction(),
4604 D.getIdentifierLoc(),
4605 D.getCXXScopeSpec().isSet());
4606
Douglas Gregord5a423b2009-09-25 18:43:00 +00004607 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4608 return DeclPtrTy();
4609}
4610
Douglas Gregord57959a2009-03-27 23:10:48 +00004611Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00004612Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4613 const CXXScopeSpec &SS, IdentifierInfo *Name,
4614 SourceLocation TagLoc, SourceLocation NameLoc) {
4615 // This has to hold, because SS is expected to be defined.
4616 assert(Name && "Expected a name in a dependent tag");
4617
4618 NestedNameSpecifier *NNS
4619 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4620 if (!NNS)
4621 return true;
4622
4623 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4624 if (T.isNull())
4625 return true;
4626
4627 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4628 QualType ElabType = Context.getElaboratedType(T, TagKind);
4629
4630 return ElabType.getAsOpaquePtr();
4631}
4632
4633Sema::TypeResult
Douglas Gregord57959a2009-03-27 23:10:48 +00004634Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4635 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00004636 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00004637 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4638 if (!NNS)
4639 return true;
4640
4641 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00004642 if (T.isNull())
4643 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00004644 return T.getAsOpaquePtr();
4645}
4646
Douglas Gregor17343172009-04-01 00:28:59 +00004647Sema::TypeResult
4648Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4649 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00004650 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004651 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00004652 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +00004653 const TemplateSpecializationType *TemplateId
John McCall183700f2009-09-21 23:43:11 +00004654 = T->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00004655 assert(TemplateId && "Expected a template specialization type");
4656
Douglas Gregor6946baf2009-09-02 13:05:45 +00004657 if (computeDeclContext(SS, false)) {
4658 // If we can compute a declaration context, then the "typename"
4659 // keyword was superfluous. Just build a QualifiedNameType to keep
4660 // track of the nested-name-specifier.
Mike Stump1eb44332009-09-09 15:08:12 +00004661
Douglas Gregor6946baf2009-09-02 13:05:45 +00004662 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4663 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4664 }
Mike Stump1eb44332009-09-09 15:08:12 +00004665
Douglas Gregor6946baf2009-09-02 13:05:45 +00004666 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00004667}
4668
Douglas Gregord57959a2009-03-27 23:10:48 +00004669/// \brief Build the type that describes a C++ typename specifier,
4670/// e.g., "typename T::type".
4671QualType
4672Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4673 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00004674 CXXRecordDecl *CurrentInstantiation = 0;
4675 if (NNS->isDependent()) {
4676 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00004677
Douglas Gregor42af25f2009-05-11 19:58:34 +00004678 // If the nested-name-specifier does not refer to the current
4679 // instantiation, then build a typename type.
4680 if (!CurrentInstantiation)
4681 return Context.getTypenameType(NNS, &II);
Mike Stump1eb44332009-09-09 15:08:12 +00004682
Douglas Gregorde18d122009-09-02 13:12:51 +00004683 // The nested-name-specifier refers to the current instantiation, so the
4684 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump1eb44332009-09-09 15:08:12 +00004685 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorde18d122009-09-02 13:12:51 +00004686 // extraneous "typename" keywords, and we retroactively apply this DR to
4687 // C++03 code.
Douglas Gregor42af25f2009-05-11 19:58:34 +00004688 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004689
Douglas Gregor42af25f2009-05-11 19:58:34 +00004690 DeclContext *Ctx = 0;
4691
4692 if (CurrentInstantiation)
4693 Ctx = CurrentInstantiation;
4694 else {
4695 CXXScopeSpec SS;
4696 SS.setScopeRep(NNS);
4697 SS.setRange(Range);
4698 if (RequireCompleteDeclContext(SS))
4699 return QualType();
4700
4701 Ctx = computeDeclContext(SS);
4702 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004703 assert(Ctx && "No declaration context?");
4704
4705 DeclarationName Name(&II);
John McCalla24dc2e2009-11-17 02:14:36 +00004706 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4707 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00004708 unsigned DiagID = 0;
4709 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00004710 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00004711 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00004712 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00004713 break;
4714
4715 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +00004716 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregord57959a2009-03-27 23:10:48 +00004717 // We found a type. Build a QualifiedNameType, since the
4718 // typename-specifier was just sugar. FIXME: Tell
4719 // QualifiedNameType that it has a "typename" prefix.
4720 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4721 }
4722
4723 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00004724 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00004725 break;
4726
John McCall7ba107a2009-11-18 02:36:19 +00004727 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004728 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00004729 return QualType();
4730
Douglas Gregord57959a2009-03-27 23:10:48 +00004731 case LookupResult::FoundOverloaded:
4732 DiagID = diag::err_typename_nested_not_type;
4733 Referenced = *Result.begin();
4734 break;
4735
John McCall6e247262009-10-10 05:48:19 +00004736 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00004737 return QualType();
4738 }
4739
4740 // If we get here, it's because name lookup did not find a
4741 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor3f093272009-10-13 21:16:44 +00004742 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00004743 if (Referenced)
4744 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4745 << Name;
4746 return QualType();
4747}
Douglas Gregor4a959d82009-08-06 16:20:37 +00004748
4749namespace {
4750 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00004751 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00004752 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00004753 SourceLocation Loc;
4754 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00004755
Douglas Gregor4a959d82009-08-06 16:20:37 +00004756 public:
Mike Stump1eb44332009-09-09 15:08:12 +00004757 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00004758 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00004759 DeclarationName Entity)
4760 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00004761 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00004762
4763 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00004764 /// transformed.
4765 ///
4766 /// For the purposes of type reconstruction, a type has already been
4767 /// transformed if it is NULL or if it is not dependent.
4768 bool AlreadyTransformed(QualType T) {
4769 return T.isNull() || !T->isDependentType();
4770 }
Mike Stump1eb44332009-09-09 15:08:12 +00004771
4772 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00004773 /// rebuilt.
4774 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00004775
Douglas Gregor4a959d82009-08-06 16:20:37 +00004776 /// \brief Returns the name of the entity whose type is being rebuilt.
4777 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00004778
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004779 /// \brief Sets the "base" location and entity when that
4780 /// information is known based on another transformation.
4781 void setBase(SourceLocation Loc, DeclarationName Entity) {
4782 this->Loc = Loc;
4783 this->Entity = Entity;
4784 }
4785
Douglas Gregor4a959d82009-08-06 16:20:37 +00004786 /// \brief Transforms an expression by returning the expression itself
4787 /// (an identity function).
4788 ///
4789 /// FIXME: This is completely unsafe; we will need to actually clone the
4790 /// expressions.
4791 Sema::OwningExprResult TransformExpr(Expr *E) {
4792 return getSema().Owned(E);
4793 }
Mike Stump1eb44332009-09-09 15:08:12 +00004794
Douglas Gregor4a959d82009-08-06 16:20:37 +00004795 /// \brief Transforms a typename type by determining whether the type now
4796 /// refers to a member of the current instantiation, and then
4797 /// type-checking and building a QualifiedNameType (when possible).
John McCalla2becad2009-10-21 00:40:46 +00004798 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor4a959d82009-08-06 16:20:37 +00004799 };
4800}
4801
Mike Stump1eb44332009-09-09 15:08:12 +00004802QualType
John McCalla2becad2009-10-21 00:40:46 +00004803CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4804 TypenameTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00004805 TypenameType *T = TL.getTypePtr();
John McCalla2becad2009-10-21 00:40:46 +00004806
Douglas Gregor4a959d82009-08-06 16:20:37 +00004807 NestedNameSpecifier *NNS
4808 = TransformNestedNameSpecifier(T->getQualifier(),
4809 /*FIXME:*/SourceRange(getBaseLocation()));
4810 if (!NNS)
4811 return QualType();
4812
4813 // If the nested-name-specifier did not change, and we cannot compute the
4814 // context corresponding to the nested-name-specifier, then this
4815 // typename type will not change; exit early.
4816 CXXScopeSpec SS;
4817 SS.setRange(SourceRange(getBaseLocation()));
4818 SS.setScopeRep(NNS);
John McCall833ca992009-10-29 08:12:44 +00004819
4820 QualType Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004821 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall833ca992009-10-29 08:12:44 +00004822 Result = QualType(T, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004823
4824 // Rebuild the typename type, which will probably turn into a
Douglas Gregor4a959d82009-08-06 16:20:37 +00004825 // QualifiedNameType.
John McCall833ca992009-10-29 08:12:44 +00004826 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004827 QualType NewTemplateId
Douglas Gregor4a959d82009-08-06 16:20:37 +00004828 = TransformType(QualType(TemplateId, 0));
4829 if (NewTemplateId.isNull())
4830 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004831
Douglas Gregor4a959d82009-08-06 16:20:37 +00004832 if (NNS == T->getQualifier() &&
4833 NewTemplateId == QualType(TemplateId, 0))
John McCall833ca992009-10-29 08:12:44 +00004834 Result = QualType(T, 0);
4835 else
4836 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4837 } else
4838 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4839 SourceRange(TL.getNameLoc()));
Mike Stump1eb44332009-09-09 15:08:12 +00004840
John McCall833ca992009-10-29 08:12:44 +00004841 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4842 NewTL.setNameLoc(TL.getNameLoc());
4843 return Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004844}
4845
4846/// \brief Rebuilds a type within the context of the current instantiation.
4847///
Mike Stump1eb44332009-09-09 15:08:12 +00004848/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00004849/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00004850/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00004851/// partial specialization thereof). This routine will rebuild that type now
4852/// that we have entered the declarator's scope, which may produce different
4853/// canonical types, e.g.,
4854///
4855/// \code
4856/// template<typename T>
4857/// struct X {
4858/// typedef T* pointer;
4859/// pointer data();
4860/// };
4861///
4862/// template<typename T>
4863/// typename X<T>::pointer X<T>::data() { ... }
4864/// \endcode
4865///
4866/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4867/// since we do not know that we can look into X<T> when we parsed the type.
4868/// This function will rebuild the type, performing the lookup of "pointer"
4869/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4870/// as the canonical type of T*, allowing the return types of the out-of-line
4871/// definition and the declaration to match.
4872QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4873 DeclarationName Name) {
4874 if (T.isNull() || !T->isDependentType())
4875 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00004876
Douglas Gregor4a959d82009-08-06 16:20:37 +00004877 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4878 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00004879}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004880
4881/// \brief Produces a formatted string that describes the binding of
4882/// template parameters to template arguments.
4883std::string
4884Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4885 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004886 // FIXME: For variadic templates, we'll need to get the structured list.
4887 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4888 Args.flat_size());
4889}
4890
4891std::string
4892Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4893 const TemplateArgument *Args,
4894 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004895 std::string Result;
4896
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004897 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004898 return Result;
4899
4900 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004901 if (I >= NumArgs)
4902 break;
4903
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004904 if (I == 0)
4905 Result += "[with ";
4906 else
4907 Result += ", ";
4908
4909 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4910 Result += Id->getName();
4911 } else {
4912 Result += '$';
4913 Result += llvm::utostr(I);
4914 }
4915
4916 Result += " = ";
4917
4918 switch (Args[I].getKind()) {
4919 case TemplateArgument::Null:
4920 Result += "<no value>";
4921 break;
4922
4923 case TemplateArgument::Type: {
4924 std::string TypeStr;
4925 Args[I].getAsType().getAsStringInternal(TypeStr,
4926 Context.PrintingPolicy);
4927 Result += TypeStr;
4928 break;
4929 }
4930
4931 case TemplateArgument::Declaration: {
4932 bool Unnamed = true;
4933 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4934 if (ND->getDeclName()) {
4935 Unnamed = false;
4936 Result += ND->getNameAsString();
4937 }
4938 }
4939
4940 if (Unnamed) {
4941 Result += "<anonymous>";
4942 }
4943 break;
4944 }
4945
Douglas Gregor788cd062009-11-11 01:00:40 +00004946 case TemplateArgument::Template: {
4947 std::string Str;
4948 llvm::raw_string_ostream OS(Str);
4949 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
4950 Result += OS.str();
4951 break;
4952 }
4953
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004954 case TemplateArgument::Integral: {
4955 Result += Args[I].getAsIntegral()->toString(10);
4956 break;
4957 }
4958
4959 case TemplateArgument::Expression: {
4960 assert(false && "No expressions in deduced template arguments!");
4961 Result += "<expression>";
4962 break;
4963 }
4964
4965 case TemplateArgument::Pack:
4966 // FIXME: Format template argument packs
4967 Result += "<template argument pack>";
4968 break;
4969 }
4970 }
4971
4972 Result += ']';
4973 return Result;
4974}