blob: 8cd1703436122f22bcc1e7a638faa3e04dc856de [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: {
333 DeclaratorInfo *DI;
334 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
335 if (!DI)
336 DI = SemaRef.Context.getTrivialDeclaratorInfo(T, Arg.getLocation());
337 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
354 llvm::llvm_unreachable("Unhandled parsed template argument");
355 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
422 DeclaratorInfo *DefaultDInfo;
423 GetTypeFromParser(DefaultT, &DefaultDInfo);
424
425 assert(DefaultDInfo && "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 McCall833ca992009-10-29 08:12:44 +0000440 if (CheckTemplateArgument(Parm, DefaultDInfo)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000441 Parm->setInvalidDecl();
442 return;
443 }
444
John McCall833ca992009-10-29 08:12:44 +0000445 Parm->setDefaultArgument(DefaultDInfo, 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) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000499 DeclaratorInfo *DInfo = 0;
500 QualType T = GetTypeForDeclarator(D, S, &DInfo);
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(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000522 Depth, Position, ParamName, T, DInfo);
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 Gregor6102d982009-09-26 07:05:09 +0000694 if (PrevDecl && TUK == TUK_Friend) {
695 // C++ [namespace.memdef]p3:
696 // [...] When looking for a prior declaration of a class or a function
697 // declared as a friend, and when the name of the friend class or
698 // function is neither a qualified name nor a template-id, scopes outside
699 // the innermost enclosing namespace scope are not considered.
700 DeclContext *OutermostContext = CurContext;
701 while (!OutermostContext->isFileContext())
702 OutermostContext = OutermostContext->getLookupParent();
703
704 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
705 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
706 SemanticContext = PrevDecl->getDeclContext();
707 } else {
708 // Declarations in outer scopes don't matter. However, the outermost
Douglas Gregor259571e2009-10-30 22:42:42 +0000709 // context we computed is the semantic context for our new
Douglas Gregor6102d982009-09-26 07:05:09 +0000710 // declaration.
711 PrevDecl = 0;
712 SemanticContext = OutermostContext;
713 }
Douglas Gregor259571e2009-10-30 22:42:42 +0000714
715 if (CurContext->isDependentContext()) {
716 // If this is a dependent context, we don't want to link the friend
717 // class template to the template in scope, because that would perform
718 // checking of the template parameter lists that can't be performed
719 // until the outer context is instantiated.
720 PrevDecl = 0;
721 }
Douglas Gregor6102d982009-09-26 07:05:09 +0000722 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000723 PrevDecl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000724
Douglas Gregorddc29e12009-02-06 22:42:48 +0000725 // If there is a previous declaration with the same name, check
726 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000727 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000728 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000729
730 // We may have found the injected-class-name of a class template,
731 // class template partial specialization, or class template specialization.
732 // In these cases, grab the template that is being defined or specialized.
733 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
734 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
735 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
736 PrevClassTemplate
737 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
738 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
739 PrevClassTemplate
740 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
741 ->getSpecializedTemplate();
742 }
743 }
744
Douglas Gregorddc29e12009-02-06 22:42:48 +0000745 if (PrevClassTemplate) {
746 // Ensure that the template parameter lists are compatible.
747 if (!TemplateParameterListsAreEqual(TemplateParams,
748 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000749 /*Complain=*/true,
750 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000751 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000752
753 // C++ [temp.class]p4:
754 // In a redeclaration, partial specialization, explicit
755 // specialization or explicit instantiation of a class template,
756 // the class-key shall agree in kind with the original class
757 // template declaration (7.1.5.3).
758 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000759 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000760 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000761 << Name
Mike Stump1eb44332009-09-09 15:08:12 +0000762 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +0000763 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000764 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000765 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000766 }
767
Douglas Gregorddc29e12009-02-06 22:42:48 +0000768 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000769 if (TUK == TUK_Definition) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000770 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
771 Diag(NameLoc, diag::err_redefinition) << Name;
772 Diag(Def->getLocation(), diag::note_previous_definition);
773 // FIXME: Would it make sense to try to "forget" the previous
774 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000775 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000776 }
777 }
778 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
779 // Maybe we will complain about the shadowed template parameter.
780 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
781 // Just pretend that we didn't see the previous declaration.
782 PrevDecl = 0;
783 } else if (PrevDecl) {
784 // C++ [temp]p5:
785 // A class template shall not have the same name as any other
786 // template, class, function, object, enumeration, enumerator,
787 // namespace, or type in the same scope (3.3), except as specified
788 // in (14.5.4).
789 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
790 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000791 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000792 }
793
Douglas Gregord684b002009-02-10 19:49:53 +0000794 // Check the template parameter list of this declaration, possibly
795 // merging in the template parameter list from the previous class
796 // template declaration.
797 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000798 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
799 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000800 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000801
Douglas Gregor7da97d02009-05-10 22:57:19 +0000802 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000803 // declaration!
804
Mike Stump1eb44332009-09-09 15:08:12 +0000805 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000806 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000807 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000808 PrevClassTemplate->getTemplatedDecl() : 0,
809 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000810
811 ClassTemplateDecl *NewTemplate
812 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
813 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000814 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000815 NewClass->setDescribedClassTemplate(NewTemplate);
816
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000817 // Build the type for the class template declaration now.
Mike Stump1eb44332009-09-09 15:08:12 +0000818 QualType T =
819 Context.getTypeDeclType(NewClass,
820 PrevClassTemplate?
821 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000822 assert(T->isDependentType() && "Class template type is not dependent?");
823 (void)T;
824
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000825 // If we are providing an explicit specialization of a member that is a
826 // class template, make a note of that.
827 if (PrevClassTemplate &&
828 PrevClassTemplate->getInstantiatedFromMemberTemplate())
829 PrevClassTemplate->setMemberSpecialization();
830
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000831 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000832 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000833 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000834
Douglas Gregorddc29e12009-02-06 22:42:48 +0000835 // Set the lexical context of these templates
836 NewClass->setLexicalDeclContext(CurContext);
837 NewTemplate->setLexicalDeclContext(CurContext);
838
John McCall0f434ec2009-07-31 02:45:11 +0000839 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000840 NewClass->startDefinition();
841
842 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000843 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000844
John McCall05b23ea2009-09-14 21:59:20 +0000845 if (TUK != TUK_Friend)
846 PushOnScopeChains(NewTemplate, S);
847 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000848 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000849 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000850 NewClass->setAccess(PrevClassTemplate->getAccess());
851 }
John McCall05b23ea2009-09-14 21:59:20 +0000852
Douglas Gregord85bea22009-09-26 06:47:28 +0000853 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
854 PrevClassTemplate != NULL);
855
John McCall05b23ea2009-09-14 21:59:20 +0000856 // Friend templates are visible in fairly strange ways.
857 if (!CurContext->isDependentContext()) {
858 DeclContext *DC = SemanticContext->getLookupContext();
859 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
860 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
861 PushOnScopeChains(NewTemplate, EnclosingScope,
862 /* AddToContext = */ false);
863 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000864
865 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
866 NewClass->getLocation(),
867 NewTemplate,
868 /*FIXME:*/NewClass->getLocation());
869 Friend->setAccess(AS_public);
870 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000871 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000872
Douglas Gregord684b002009-02-10 19:49:53 +0000873 if (Invalid) {
874 NewTemplate->setInvalidDecl();
875 NewClass->setInvalidDecl();
876 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000877 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000878}
879
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000880/// \brief Diagnose the presence of a default template argument on a
881/// template parameter, which is ill-formed in certain contexts.
882///
883/// \returns true if the default template argument should be dropped.
884static bool DiagnoseDefaultTemplateArgument(Sema &S,
885 Sema::TemplateParamListContext TPC,
886 SourceLocation ParamLoc,
887 SourceRange DefArgRange) {
888 switch (TPC) {
889 case Sema::TPC_ClassTemplate:
890 return false;
891
892 case Sema::TPC_FunctionTemplate:
893 // C++ [temp.param]p9:
894 // A default template-argument shall not be specified in a
895 // function template declaration or a function template
896 // definition [...]
897 // (This sentence is not in C++0x, per DR226).
898 if (!S.getLangOptions().CPlusPlus0x)
899 S.Diag(ParamLoc,
900 diag::err_template_parameter_default_in_function_template)
901 << DefArgRange;
902 return false;
903
904 case Sema::TPC_ClassTemplateMember:
905 // C++0x [temp.param]p9:
906 // A default template-argument shall not be specified in the
907 // template-parameter-lists of the definition of a member of a
908 // class template that appears outside of the member's class.
909 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
910 << DefArgRange;
911 return true;
912
913 case Sema::TPC_FriendFunctionTemplate:
914 // C++ [temp.param]p9:
915 // A default template-argument shall not be specified in a
916 // friend template declaration.
917 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
918 << DefArgRange;
919 return true;
920
921 // FIXME: C++0x [temp.param]p9 allows default template-arguments
922 // for friend function templates if there is only a single
923 // declaration (and it is a definition). Strange!
924 }
925
926 return false;
927}
928
Douglas Gregord684b002009-02-10 19:49:53 +0000929/// \brief Checks the validity of a template parameter list, possibly
930/// considering the template parameter list from a previous
931/// declaration.
932///
933/// If an "old" template parameter list is provided, it must be
934/// equivalent (per TemplateParameterListsAreEqual) to the "new"
935/// template parameter list.
936///
937/// \param NewParams Template parameter list for a new template
938/// declaration. This template parameter list will be updated with any
939/// default arguments that are carried through from the previous
940/// template parameter list.
941///
942/// \param OldParams If provided, template parameter list from a
943/// previous declaration of the same template. Default template
944/// arguments will be merged from the old template parameter list to
945/// the new template parameter list.
946///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000947/// \param TPC Describes the context in which we are checking the given
948/// template parameter list.
949///
Douglas Gregord684b002009-02-10 19:49:53 +0000950/// \returns true if an error occurred, false otherwise.
951bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000952 TemplateParameterList *OldParams,
953 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +0000954 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Douglas Gregord684b002009-02-10 19:49:53 +0000956 // C++ [temp.param]p10:
957 // The set of default template-arguments available for use with a
958 // template declaration or definition is obtained by merging the
959 // default arguments from the definition (if in scope) and all
960 // declarations in scope in the same way default function
961 // arguments are (8.3.6).
962 bool SawDefaultArgument = false;
963 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000964
Anders Carlsson49d25572009-06-12 23:20:15 +0000965 bool SawParameterPack = false;
966 SourceLocation ParameterPackLoc;
967
Mike Stump1a35fde2009-02-11 23:03:27 +0000968 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000969 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000970 if (OldParams)
971 OldParam = OldParams->begin();
972
973 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
974 NewParamEnd = NewParams->end();
975 NewParam != NewParamEnd; ++NewParam) {
976 // Variables used to diagnose redundant default arguments
977 bool RedundantDefaultArg = false;
978 SourceLocation OldDefaultLoc;
979 SourceLocation NewDefaultLoc;
980
981 // Variables used to diagnose missing default arguments
982 bool MissingDefaultArg = false;
983
Anders Carlsson49d25572009-06-12 23:20:15 +0000984 // C++0x [temp.param]p11:
985 // If a template parameter of a class template is a template parameter pack,
986 // it must be the last template parameter.
987 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +0000988 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +0000989 diag::err_template_param_pack_must_be_last_template_parameter);
990 Invalid = true;
991 }
992
Douglas Gregord684b002009-02-10 19:49:53 +0000993 if (TemplateTypeParmDecl *NewTypeParm
994 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000995 // Check the presence of a default argument here.
996 if (NewTypeParm->hasDefaultArgument() &&
997 DiagnoseDefaultTemplateArgument(*this, TPC,
998 NewTypeParm->getLocation(),
999 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1000 .getFullSourceRange()))
1001 NewTypeParm->removeDefaultArgument();
1002
1003 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001004 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001005 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Anders Carlsson49d25572009-06-12 23:20:15 +00001007 if (NewTypeParm->isParameterPack()) {
1008 assert(!NewTypeParm->hasDefaultArgument() &&
1009 "Parameter packs can't have a default argument!");
1010 SawParameterPack = true;
1011 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001012 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001013 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001014 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1015 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1016 SawDefaultArgument = true;
1017 RedundantDefaultArg = true;
1018 PreviousDefaultArgLoc = NewDefaultLoc;
1019 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1020 // Merge the default argument from the old declaration to the
1021 // new declaration.
1022 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001023 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001024 true);
1025 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1026 } else if (NewTypeParm->hasDefaultArgument()) {
1027 SawDefaultArgument = true;
1028 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1029 } else if (SawDefaultArgument)
1030 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001031 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001032 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001033 // Check the presence of a default argument here.
1034 if (NewNonTypeParm->hasDefaultArgument() &&
1035 DiagnoseDefaultTemplateArgument(*this, TPC,
1036 NewNonTypeParm->getLocation(),
1037 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1038 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1039 NewNonTypeParm->setDefaultArgument(0);
1040 }
1041
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001042 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001043 NonTypeTemplateParmDecl *OldNonTypeParm
1044 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001045 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001046 NewNonTypeParm->hasDefaultArgument()) {
1047 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1048 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1049 SawDefaultArgument = true;
1050 RedundantDefaultArg = true;
1051 PreviousDefaultArgLoc = NewDefaultLoc;
1052 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1053 // Merge the default argument from the old declaration to the
1054 // new declaration.
1055 SawDefaultArgument = true;
1056 // FIXME: We need to create a new kind of "default argument"
1057 // expression that points to a previous template template
1058 // parameter.
1059 NewNonTypeParm->setDefaultArgument(
1060 OldNonTypeParm->getDefaultArgument());
1061 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1062 } else if (NewNonTypeParm->hasDefaultArgument()) {
1063 SawDefaultArgument = true;
1064 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1065 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001066 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001067 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001068 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001069 TemplateTemplateParmDecl *NewTemplateParm
1070 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001071 if (NewTemplateParm->hasDefaultArgument() &&
1072 DiagnoseDefaultTemplateArgument(*this, TPC,
1073 NewTemplateParm->getLocation(),
1074 NewTemplateParm->getDefaultArgument().getSourceRange()))
1075 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1076
1077 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001078 TemplateTemplateParmDecl *OldTemplateParm
1079 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001080 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001081 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001082 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1083 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001084 SawDefaultArgument = true;
1085 RedundantDefaultArg = true;
1086 PreviousDefaultArgLoc = NewDefaultLoc;
1087 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1088 // Merge the default argument from the old declaration to the
1089 // new declaration.
1090 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001091 // FIXME: We need to create a new kind of "default argument" expression
1092 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001093 NewTemplateParm->setDefaultArgument(
1094 OldTemplateParm->getDefaultArgument());
Douglas Gregor788cd062009-11-11 01:00:40 +00001095 PreviousDefaultArgLoc
1096 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001097 } else if (NewTemplateParm->hasDefaultArgument()) {
1098 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001099 PreviousDefaultArgLoc
1100 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001101 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001102 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001103 }
1104
1105 if (RedundantDefaultArg) {
1106 // C++ [temp.param]p12:
1107 // A template-parameter shall not be given default arguments
1108 // by two different declarations in the same scope.
1109 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1110 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1111 Invalid = true;
1112 } else if (MissingDefaultArg) {
1113 // C++ [temp.param]p11:
1114 // If a template-parameter has a default template-argument,
1115 // all subsequent template-parameters shall have a default
1116 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001117 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001118 diag::err_template_param_default_arg_missing);
1119 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1120 Invalid = true;
1121 }
1122
1123 // If we have an old template parameter list that we're merging
1124 // in, move on to the next parameter.
1125 if (OldParams)
1126 ++OldParam;
1127 }
1128
1129 return Invalid;
1130}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001131
Mike Stump1eb44332009-09-09 15:08:12 +00001132/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001133/// specifier, returning the template parameter list that applies to the
1134/// name.
1135///
1136/// \param DeclStartLoc the start of the declaration that has a scope
1137/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001138///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001139/// \param SS the scope specifier that will be matched to the given template
1140/// parameter lists. This scope specifier precedes a qualified name that is
1141/// being declared.
1142///
1143/// \param ParamLists the template parameter lists, from the outermost to the
1144/// innermost template parameter lists.
1145///
1146/// \param NumParamLists the number of template parameter lists in ParamLists.
1147///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001148/// \param IsExplicitSpecialization will be set true if the entity being
1149/// declared is an explicit specialization, false otherwise.
1150///
Mike Stump1eb44332009-09-09 15:08:12 +00001151/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001152/// name that is preceded by the scope specifier @p SS. This template
1153/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001154/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001155/// template specialization), or may be NULL (if we were's declaring isn't
1156/// itself a template).
1157TemplateParameterList *
1158Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1159 const CXXScopeSpec &SS,
1160 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001161 unsigned NumParamLists,
1162 bool &IsExplicitSpecialization) {
1163 IsExplicitSpecialization = false;
1164
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001165 // Find the template-ids that occur within the nested-name-specifier. These
1166 // template-ids will match up with the template parameter lists.
1167 llvm::SmallVector<const TemplateSpecializationType *, 4>
1168 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001169 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1170 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001171 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1172 NNS; NNS = NNS->getPrefix()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001173 if (const TemplateSpecializationType *SpecType
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001174 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
1175 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1176 if (!Template)
1177 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Ted Kremenek6217b802009-07-29 21:53:49 +00001179 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001180 ClassTemplateSpecializationDecl *SpecDecl
1181 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1182 // If the nested name specifier refers to an explicit specialization,
1183 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001184 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1185 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001186 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001187 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001188 }
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001190 TemplateIdsInSpecifier.push_back(SpecType);
1191 }
1192 }
Mike Stump1eb44332009-09-09 15:08:12 +00001193
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001194 // Reverse the list of template-ids in the scope specifier, so that we can
1195 // more easily match up the template-ids and the template parameter lists.
1196 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001198 SourceLocation FirstTemplateLoc = DeclStartLoc;
1199 if (NumParamLists)
1200 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001202 // Match the template-ids found in the specifier to the template parameter
1203 // lists.
1204 unsigned Idx = 0;
1205 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1206 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001207 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1208 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001209 if (Idx >= NumParamLists) {
1210 // We have a template-id without a corresponding template parameter
1211 // list.
1212 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001213 // FIXME: the location information here isn't great.
1214 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001215 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001216 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001217 << SS.getRange();
1218 } else {
1219 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1220 << SS.getRange()
1221 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1222 "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001223 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001224 }
1225 return 0;
1226 }
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001228 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001229 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001230 TemplateDecl *Template
Douglas Gregorb88e8882009-07-30 17:40:51 +00001231 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1232
Mike Stump1eb44332009-09-09 15:08:12 +00001233 if (ClassTemplateDecl *ClassTemplate
Douglas Gregorb88e8882009-07-30 17:40:51 +00001234 = dyn_cast<ClassTemplateDecl>(Template)) {
1235 TemplateParameterList *ExpectedTemplateParams = 0;
1236 // Is this template-id naming the primary template?
1237 if (Context.hasSameType(TemplateId,
1238 ClassTemplate->getInjectedClassNameType(Context)))
1239 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1240 // ... or a partial specialization?
1241 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1242 = ClassTemplate->findPartialSpecialization(TemplateId))
1243 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1244
1245 if (ExpectedTemplateParams)
Mike Stump1eb44332009-09-09 15:08:12 +00001246 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregorb88e8882009-07-30 17:40:51 +00001247 ExpectedTemplateParams,
Douglas Gregorfb898e12009-11-12 16:20:59 +00001248 true, TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00001249 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001250
1251 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregorb88e8882009-07-30 17:40:51 +00001252 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001253 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001254 diag::err_template_param_list_matches_nontemplate)
1255 << TemplateId
1256 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001257 else
1258 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001259 }
Mike Stump1eb44332009-09-09 15:08:12 +00001260
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001261 // If there were at least as many template-ids as there were template
1262 // parameter lists, then there are no template parameter lists remaining for
1263 // the declaration itself.
1264 if (Idx >= NumParamLists)
1265 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001267 // If there were too many template parameter lists, complain about that now.
1268 if (Idx != NumParamLists - 1) {
1269 while (Idx < NumParamLists - 1) {
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001270 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001271 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001272 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1273 : diag::err_template_spec_extra_headers)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001274 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1275 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001276
1277 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1278 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1279 diag::note_explicit_template_spec_does_not_need_header)
1280 << ExplicitSpecializationsInSpecifier.back();
1281 ExplicitSpecializationsInSpecifier.pop_back();
1282 }
1283
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001284 ++Idx;
1285 }
1286 }
Mike Stump1eb44332009-09-09 15:08:12 +00001287
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001288 // Return the last template parameter list, which corresponds to the
1289 // entity being declared.
1290 return ParamLists[NumParamLists - 1];
1291}
1292
Douglas Gregor7532dc62009-03-30 22:58:21 +00001293QualType Sema::CheckTemplateIdType(TemplateName Name,
1294 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001295 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001296 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001297 if (!Template) {
1298 // The template name does not resolve to a template, so we just
1299 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001300 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001301 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001302
Douglas Gregor40808ce2009-03-09 23:48:35 +00001303 // Check that the template argument list is well-formed for this
1304 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001305 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCalld5532b62009-11-23 01:53:49 +00001306 TemplateArgs.size());
1307 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001308 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001309 return QualType();
1310
Mike Stump1eb44332009-09-09 15:08:12 +00001311 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001312 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001313 "Converted template argument list is too short!");
1314
1315 QualType CanonType;
1316
Douglas Gregorcaddba02009-11-12 18:38:13 +00001317 if (Name.isDependent() ||
1318 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001319 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001320 // This class template specialization is a dependent
1321 // type. Therefore, its canonical type is another class template
1322 // specialization type that contains all of the converted
1323 // arguments in canonical form. This ensures that, e.g., A<T> and
1324 // A<T, T> have identical types when A is declared as:
1325 //
1326 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001327 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001328 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001329 Converted.getFlatArguments(),
1330 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001331
Douglas Gregor1275ae02009-07-28 23:00:59 +00001332 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001333 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001334 // In the future, we need to teach getTemplateSpecializationType to only
1335 // build the canonical type and return that to us.
1336 CanonType = Context.getCanonicalType(CanonType);
Mike Stump1eb44332009-09-09 15:08:12 +00001337 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001338 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001339 // Find the class template specialization declaration that
1340 // corresponds to these arguments.
1341 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001342 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001343 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001344 Converted.flatSize(),
1345 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001346 void *InsertPos = 0;
1347 ClassTemplateSpecializationDecl *Decl
1348 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1349 if (!Decl) {
1350 // This is the first time we have referenced this class template
1351 // specialization. Create the canonical declaration and add it to
1352 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001353 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001354 ClassTemplate->getDeclContext(),
John McCall9cc78072009-09-11 07:25:08 +00001355 ClassTemplate->getLocation(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001356 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00001357 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001358 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1359 Decl->setLexicalDeclContext(CurContext);
1360 }
1361
1362 CanonType = Context.getTypeDeclType(Decl);
1363 }
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Douglas Gregor40808ce2009-03-09 23:48:35 +00001365 // Build the fully-sugared type for this class template
1366 // specialization, which refers back to the class template
1367 // specialization we created or found.
John McCalld5532b62009-11-23 01:53:49 +00001368 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001369}
1370
Douglas Gregorcc636682009-02-17 23:15:12 +00001371Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001372Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001373 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001374 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001375 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001376 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001377
Douglas Gregor40808ce2009-03-09 23:48:35 +00001378 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001379 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001380 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001381
John McCalld5532b62009-11-23 01:53:49 +00001382 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001383 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001384
1385 if (Result.isNull())
1386 return true;
1387
John McCall833ca992009-10-29 08:12:44 +00001388 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result);
1389 TemplateSpecializationTypeLoc TL
1390 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1391 TL.setTemplateNameLoc(TemplateLoc);
1392 TL.setLAngleLoc(LAngleLoc);
1393 TL.setRAngleLoc(RAngleLoc);
1394 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1395 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1396
1397 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCall6b2becf2009-09-08 17:47:29 +00001398}
John McCallf1bbbb42009-09-04 01:14:41 +00001399
John McCall6b2becf2009-09-08 17:47:29 +00001400Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1401 TagUseKind TUK,
1402 DeclSpec::TST TagSpec,
1403 SourceLocation TagLoc) {
1404 if (TypeResult.isInvalid())
1405 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001406
John McCall833ca992009-10-29 08:12:44 +00001407 // FIXME: preserve source info, ideally without copying the DI.
1408 DeclaratorInfo *DI;
1409 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001410
John McCall6b2becf2009-09-08 17:47:29 +00001411 // Verify the tag specifier.
1412 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001413
John McCall6b2becf2009-09-08 17:47:29 +00001414 if (const RecordType *RT = Type->getAs<RecordType>()) {
1415 RecordDecl *D = RT->getDecl();
1416
1417 IdentifierInfo *Id = D->getIdentifier();
1418 assert(Id && "templated class must have an identifier");
1419
1420 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1421 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001422 << Type
John McCall6b2becf2009-09-08 17:47:29 +00001423 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1424 D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001425 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001426 }
1427 }
1428
John McCall6b2becf2009-09-08 17:47:29 +00001429 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1430
1431 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001432}
1433
John McCallf7a1a742009-11-24 19:00:30 +00001434Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1435 LookupResult &R,
1436 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001437 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001438 // FIXME: Can we do any checking at this point? I guess we could check the
1439 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001440 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001441 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001442
1443 // These should be filtered out by our callers.
1444 assert(!R.empty() && "empty lookup results when building templateid");
1445 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1446
1447 NestedNameSpecifier *Qualifier = 0;
1448 SourceRange QualifierRange;
1449 if (SS.isSet()) {
1450 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1451 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001452 }
1453
John McCallf7a1a742009-11-24 19:00:30 +00001454 bool Dependent
1455 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1456 &TemplateArgs);
1457 UnresolvedLookupExpr *ULE
1458 = UnresolvedLookupExpr::Create(Context, Dependent,
1459 Qualifier, QualifierRange,
1460 R.getLookupName(), R.getNameLoc(),
1461 RequiresADL, TemplateArgs);
1462 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1463 ULE->addDecl(*I);
1464
1465 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001466}
1467
John McCallf7a1a742009-11-24 19:00:30 +00001468// We actually only call this from template instantiation.
1469Sema::OwningExprResult
1470Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1471 DeclarationName Name,
1472 SourceLocation NameLoc,
1473 const TemplateArgumentListInfo &TemplateArgs) {
1474 DeclContext *DC;
1475 if (!(DC = computeDeclContext(SS, false)) ||
1476 DC->isDependentContext() ||
1477 RequireCompleteDeclContext(SS))
1478 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001479
John McCallf7a1a742009-11-24 19:00:30 +00001480 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1481 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00001482
John McCallf7a1a742009-11-24 19:00:30 +00001483 if (R.isAmbiguous())
1484 return ExprError();
1485
1486 if (R.empty()) {
1487 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1488 << Name << SS.getRange();
1489 return ExprError();
1490 }
1491
1492 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1493 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1494 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1495 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1496 return ExprError();
1497 }
1498
1499 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001500}
1501
Douglas Gregorc45c2322009-03-31 00:43:58 +00001502/// \brief Form a dependent template name.
1503///
1504/// This action forms a dependent template name given the template
1505/// name and its (presumably dependent) scope specifier. For
1506/// example, given "MetaFun::template apply", the scope specifier \p
1507/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1508/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump1eb44332009-09-09 15:08:12 +00001509Sema::TemplateTy
Douglas Gregorc45c2322009-03-31 00:43:58 +00001510Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001511 const CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +00001512 UnqualifiedId &Name,
Douglas Gregora481edb2009-11-20 23:39:24 +00001513 TypeTy *ObjectType,
1514 bool EnteringContext) {
Mike Stump1eb44332009-09-09 15:08:12 +00001515 if ((ObjectType &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001516 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
Douglas Gregora481edb2009-11-20 23:39:24 +00001517 (SS.isSet() && computeDeclContext(SS, EnteringContext))) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001518 // C++0x [temp.names]p5:
1519 // If a name prefixed by the keyword template is not the name of
1520 // a template, the program is ill-formed. [Note: the keyword
1521 // template may not be applied to non-template members of class
1522 // templates. -end note ] [ Note: as is the case with the
1523 // typename prefix, the template prefix is allowed in cases
1524 // where it is not strictly necessary; i.e., when the
1525 // nested-name-specifier or the expression on the left of the ->
1526 // or . is not dependent on a template-parameter, or the use
1527 // does not appear in the scope of a template. -end note]
1528 //
1529 // Note: C++03 was more strict here, because it banned the use of
1530 // the "template" keyword prior to a template-name that was not a
1531 // dependent name. C++ DR468 relaxed this requirement (the
1532 // "template" keyword is now permitted). We follow the C++0x
1533 // rules, even in C++03 mode, retroactively applying the DR.
1534 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001535 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregora481edb2009-11-20 23:39:24 +00001536 EnteringContext, Template);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001537 if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001538 Diag(Name.getSourceRange().getBegin(),
1539 diag::err_template_kw_refers_to_non_template)
1540 << GetNameFromUnqualifiedId(Name)
1541 << Name.getSourceRange();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001542 return TemplateTy();
1543 }
1544
1545 return Template;
1546 }
1547
Mike Stump1eb44332009-09-09 15:08:12 +00001548 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001549 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001550
1551 switch (Name.getKind()) {
1552 case UnqualifiedId::IK_Identifier:
1553 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1554 Name.Identifier));
1555
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001556 case UnqualifiedId::IK_OperatorFunctionId:
1557 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1558 Name.OperatorFunctionId.Operator));
Sean Hunte6252d12009-11-28 08:58:14 +00001559
1560 case UnqualifiedId::IK_LiteralOperatorId:
1561 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1562
Douglas Gregor014e88d2009-11-03 23:16:33 +00001563 default:
1564 break;
1565 }
1566
1567 Diag(Name.getSourceRange().getBegin(),
1568 diag::err_template_kw_refers_to_non_template)
1569 << GetNameFromUnqualifiedId(Name)
1570 << Name.getSourceRange();
1571 return TemplateTy();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001572}
1573
Mike Stump1eb44332009-09-09 15:08:12 +00001574bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001575 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001576 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001577 const TemplateArgument &Arg = AL.getArgument();
1578
Anders Carlsson436b1562009-06-13 00:33:33 +00001579 // Check template type parameter.
1580 if (Arg.getKind() != TemplateArgument::Type) {
1581 // C++ [temp.arg.type]p1:
1582 // A template-argument for a template-parameter which is a
1583 // type shall be a type-id.
1584
1585 // We have a template type parameter but the template argument
1586 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001587 SourceRange SR = AL.getSourceRange();
1588 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001589 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001590
Anders Carlsson436b1562009-06-13 00:33:33 +00001591 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001592 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001593
John McCall833ca992009-10-29 08:12:44 +00001594 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001595 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Anders Carlsson436b1562009-06-13 00:33:33 +00001597 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001598 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001599 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001600 return false;
1601}
1602
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001603/// \brief Substitute template arguments into the default template argument for
1604/// the given template type parameter.
1605///
1606/// \param SemaRef the semantic analysis object for which we are performing
1607/// the substitution.
1608///
1609/// \param Template the template that we are synthesizing template arguments
1610/// for.
1611///
1612/// \param TemplateLoc the location of the template name that started the
1613/// template-id we are checking.
1614///
1615/// \param RAngleLoc the location of the right angle bracket ('>') that
1616/// terminates the template-id.
1617///
1618/// \param Param the template template parameter whose default we are
1619/// substituting into.
1620///
1621/// \param Converted the list of template arguments provided for template
1622/// parameters that precede \p Param in the template parameter list.
1623///
1624/// \returns the substituted template argument, or NULL if an error occurred.
1625static DeclaratorInfo *
1626SubstDefaultTemplateArgument(Sema &SemaRef,
1627 TemplateDecl *Template,
1628 SourceLocation TemplateLoc,
1629 SourceLocation RAngleLoc,
1630 TemplateTypeParmDecl *Param,
1631 TemplateArgumentListBuilder &Converted) {
1632 DeclaratorInfo *ArgType = Param->getDefaultArgumentInfo();
1633
1634 // If the argument type is dependent, instantiate it now based
1635 // on the previously-computed template arguments.
1636 if (ArgType->getType()->isDependentType()) {
1637 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1638 /*TakeArgs=*/false);
1639
1640 MultiLevelTemplateArgumentList AllTemplateArgs
1641 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1642
1643 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1644 Template, Converted.getFlatArguments(),
1645 Converted.flatSize(),
1646 SourceRange(TemplateLoc, RAngleLoc));
1647
1648 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1649 Param->getDefaultArgumentLoc(),
1650 Param->getDeclName());
1651 }
1652
1653 return ArgType;
1654}
1655
1656/// \brief Substitute template arguments into the default template argument for
1657/// the given non-type template parameter.
1658///
1659/// \param SemaRef the semantic analysis object for which we are performing
1660/// the substitution.
1661///
1662/// \param Template the template that we are synthesizing template arguments
1663/// for.
1664///
1665/// \param TemplateLoc the location of the template name that started the
1666/// template-id we are checking.
1667///
1668/// \param RAngleLoc the location of the right angle bracket ('>') that
1669/// terminates the template-id.
1670///
Douglas Gregor788cd062009-11-11 01:00:40 +00001671/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001672/// substituting into.
1673///
1674/// \param Converted the list of template arguments provided for template
1675/// parameters that precede \p Param in the template parameter list.
1676///
1677/// \returns the substituted template argument, or NULL if an error occurred.
1678static Sema::OwningExprResult
1679SubstDefaultTemplateArgument(Sema &SemaRef,
1680 TemplateDecl *Template,
1681 SourceLocation TemplateLoc,
1682 SourceLocation RAngleLoc,
1683 NonTypeTemplateParmDecl *Param,
1684 TemplateArgumentListBuilder &Converted) {
1685 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1686 /*TakeArgs=*/false);
1687
1688 MultiLevelTemplateArgumentList AllTemplateArgs
1689 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1690
1691 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1692 Template, Converted.getFlatArguments(),
1693 Converted.flatSize(),
1694 SourceRange(TemplateLoc, RAngleLoc));
1695
1696 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1697}
1698
Douglas Gregor788cd062009-11-11 01:00:40 +00001699/// \brief Substitute template arguments into the default template argument for
1700/// the given template template parameter.
1701///
1702/// \param SemaRef the semantic analysis object for which we are performing
1703/// the substitution.
1704///
1705/// \param Template the template that we are synthesizing template arguments
1706/// for.
1707///
1708/// \param TemplateLoc the location of the template name that started the
1709/// template-id we are checking.
1710///
1711/// \param RAngleLoc the location of the right angle bracket ('>') that
1712/// terminates the template-id.
1713///
1714/// \param Param the template template parameter whose default we are
1715/// substituting into.
1716///
1717/// \param Converted the list of template arguments provided for template
1718/// parameters that precede \p Param in the template parameter list.
1719///
1720/// \returns the substituted template argument, or NULL if an error occurred.
1721static TemplateName
1722SubstDefaultTemplateArgument(Sema &SemaRef,
1723 TemplateDecl *Template,
1724 SourceLocation TemplateLoc,
1725 SourceLocation RAngleLoc,
1726 TemplateTemplateParmDecl *Param,
1727 TemplateArgumentListBuilder &Converted) {
1728 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1729 /*TakeArgs=*/false);
1730
1731 MultiLevelTemplateArgumentList AllTemplateArgs
1732 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1733
1734 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1735 Template, Converted.getFlatArguments(),
1736 Converted.flatSize(),
1737 SourceRange(TemplateLoc, RAngleLoc));
1738
1739 return SemaRef.SubstTemplateName(
1740 Param->getDefaultArgument().getArgument().getAsTemplate(),
1741 Param->getDefaultArgument().getTemplateNameLoc(),
1742 AllTemplateArgs);
1743}
1744
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001745/// \brief If the given template parameter has a default template
1746/// argument, substitute into that default template argument and
1747/// return the corresponding template argument.
1748TemplateArgumentLoc
1749Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1750 SourceLocation TemplateLoc,
1751 SourceLocation RAngleLoc,
1752 Decl *Param,
1753 TemplateArgumentListBuilder &Converted) {
1754 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1755 if (!TypeParm->hasDefaultArgument())
1756 return TemplateArgumentLoc();
1757
1758 DeclaratorInfo *DI = SubstDefaultTemplateArgument(*this, Template,
1759 TemplateLoc,
1760 RAngleLoc,
1761 TypeParm,
1762 Converted);
1763 if (DI)
1764 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1765
1766 return TemplateArgumentLoc();
1767 }
1768
1769 if (NonTypeTemplateParmDecl *NonTypeParm
1770 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1771 if (!NonTypeParm->hasDefaultArgument())
1772 return TemplateArgumentLoc();
1773
1774 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1775 TemplateLoc,
1776 RAngleLoc,
1777 NonTypeParm,
1778 Converted);
1779 if (Arg.isInvalid())
1780 return TemplateArgumentLoc();
1781
1782 Expr *ArgE = Arg.takeAs<Expr>();
1783 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1784 }
1785
1786 TemplateTemplateParmDecl *TempTempParm
1787 = cast<TemplateTemplateParmDecl>(Param);
1788 if (!TempTempParm->hasDefaultArgument())
1789 return TemplateArgumentLoc();
1790
1791 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1792 TemplateLoc,
1793 RAngleLoc,
1794 TempTempParm,
1795 Converted);
1796 if (TName.isNull())
1797 return TemplateArgumentLoc();
1798
1799 return TemplateArgumentLoc(TemplateArgument(TName),
1800 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1801 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1802}
1803
Douglas Gregore7526412009-11-11 19:31:23 +00001804/// \brief Check that the given template argument corresponds to the given
1805/// template parameter.
1806bool Sema::CheckTemplateArgument(NamedDecl *Param,
1807 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00001808 TemplateDecl *Template,
1809 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00001810 SourceLocation RAngleLoc,
1811 TemplateArgumentListBuilder &Converted) {
Douglas Gregord9e15302009-11-11 19:41:09 +00001812 // Check template type parameters.
1813 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00001814 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00001815
Douglas Gregord9e15302009-11-11 19:41:09 +00001816 // Check non-type template parameters.
1817 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00001818 // Do substitution on the type of the non-type template parameter
1819 // with the template arguments we've seen thus far.
1820 QualType NTTPType = NTTP->getType();
1821 if (NTTPType->isDependentType()) {
1822 // Do substitution on the type of the non-type template parameter.
1823 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1824 NTTP, Converted.getFlatArguments(),
1825 Converted.flatSize(),
1826 SourceRange(TemplateLoc, RAngleLoc));
1827
1828 TemplateArgumentList TemplateArgs(Context, Converted,
1829 /*TakeArgs=*/false);
1830 NTTPType = SubstType(NTTPType,
1831 MultiLevelTemplateArgumentList(TemplateArgs),
1832 NTTP->getLocation(),
1833 NTTP->getDeclName());
1834 // If that worked, check the non-type template parameter type
1835 // for validity.
1836 if (!NTTPType.isNull())
1837 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1838 NTTP->getLocation());
1839 if (NTTPType.isNull())
1840 return true;
1841 }
1842
1843 switch (Arg.getArgument().getKind()) {
1844 case TemplateArgument::Null:
1845 assert(false && "Should never see a NULL template argument here");
1846 return true;
1847
1848 case TemplateArgument::Expression: {
1849 Expr *E = Arg.getArgument().getAsExpr();
1850 TemplateArgument Result;
1851 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1852 return true;
1853
1854 Converted.Append(Result);
1855 break;
1856 }
1857
1858 case TemplateArgument::Declaration:
1859 case TemplateArgument::Integral:
1860 // We've already checked this template argument, so just copy
1861 // it to the list of converted arguments.
1862 Converted.Append(Arg.getArgument());
1863 break;
1864
1865 case TemplateArgument::Template:
1866 // We were given a template template argument. It may not be ill-formed;
1867 // see below.
1868 if (DependentTemplateName *DTN
1869 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1870 // We have a template argument such as \c T::template X, which we
1871 // parsed as a template template argument. However, since we now
1872 // know that we need a non-type template argument, convert this
1873 // template name into an expression.
John McCallf7a1a742009-11-24 19:00:30 +00001874 Expr *E = DependentScopeDeclRefExpr::Create(Context,
1875 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00001876 Arg.getTemplateQualifierRange(),
John McCallf7a1a742009-11-24 19:00:30 +00001877 DTN->getIdentifier(),
1878 Arg.getTemplateNameLoc());
Douglas Gregore7526412009-11-11 19:31:23 +00001879
1880 TemplateArgument Result;
1881 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1882 return true;
1883
1884 Converted.Append(Result);
1885 break;
1886 }
1887
1888 // We have a template argument that actually does refer to a class
1889 // template, template alias, or template template parameter, and
1890 // therefore cannot be a non-type template argument.
1891 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1892 << Arg.getSourceRange();
1893
1894 Diag(Param->getLocation(), diag::note_template_param_here);
1895 return true;
1896
1897 case TemplateArgument::Type: {
1898 // We have a non-type template parameter but the template
1899 // argument is a type.
1900
1901 // C++ [temp.arg]p2:
1902 // In a template-argument, an ambiguity between a type-id and
1903 // an expression is resolved to a type-id, regardless of the
1904 // form of the corresponding template-parameter.
1905 //
1906 // We warn specifically about this case, since it can be rather
1907 // confusing for users.
1908 QualType T = Arg.getArgument().getAsType();
1909 SourceRange SR = Arg.getSourceRange();
1910 if (T->isFunctionType())
1911 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1912 else
1913 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1914 Diag(Param->getLocation(), diag::note_template_param_here);
1915 return true;
1916 }
1917
1918 case TemplateArgument::Pack:
Douglas Gregord9e15302009-11-11 19:41:09 +00001919 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00001920 break;
1921 }
1922
1923 return false;
1924 }
1925
1926
1927 // Check template template parameters.
1928 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
1929
1930 // Substitute into the template parameter list of the template
1931 // template parameter, since previously-supplied template arguments
1932 // may appear within the template template parameter.
1933 {
1934 // Set up a template instantiation context.
1935 LocalInstantiationScope Scope(*this);
1936 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1937 TempParm, Converted.getFlatArguments(),
1938 Converted.flatSize(),
1939 SourceRange(TemplateLoc, RAngleLoc));
1940
1941 TemplateArgumentList TemplateArgs(Context, Converted,
1942 /*TakeArgs=*/false);
1943 TempParm = cast_or_null<TemplateTemplateParmDecl>(
1944 SubstDecl(TempParm, CurContext,
1945 MultiLevelTemplateArgumentList(TemplateArgs)));
1946 if (!TempParm)
1947 return true;
1948
1949 // FIXME: TempParam is leaked.
1950 }
1951
1952 switch (Arg.getArgument().getKind()) {
1953 case TemplateArgument::Null:
1954 assert(false && "Should never see a NULL template argument here");
1955 return true;
1956
1957 case TemplateArgument::Template:
1958 if (CheckTemplateArgument(TempParm, Arg))
1959 return true;
1960
1961 Converted.Append(Arg.getArgument());
1962 break;
1963
1964 case TemplateArgument::Expression:
1965 case TemplateArgument::Type:
1966 // We have a template template parameter but the template
1967 // argument does not refer to a template.
1968 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1969 return true;
1970
1971 case TemplateArgument::Declaration:
1972 llvm::llvm_unreachable(
1973 "Declaration argument with template template parameter");
1974 break;
1975 case TemplateArgument::Integral:
1976 llvm::llvm_unreachable(
1977 "Integral argument with template template parameter");
1978 break;
1979
1980 case TemplateArgument::Pack:
Douglas Gregord9e15302009-11-11 19:41:09 +00001981 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00001982 break;
1983 }
1984
1985 return false;
1986}
1987
Douglas Gregorc15cb382009-02-09 23:23:08 +00001988/// \brief Check that the given template argument list is well-formed
1989/// for specializing the given template.
1990bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1991 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001992 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001993 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001994 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001995 TemplateParameterList *Params = Template->getTemplateParameters();
1996 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00001997 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001998 bool Invalid = false;
1999
John McCalld5532b62009-11-23 01:53:49 +00002000 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2001
Mike Stump1eb44332009-09-09 15:08:12 +00002002 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002003 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002005 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002006 (NumArgs < Params->getMinRequiredArguments() &&
2007 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002008 // FIXME: point at either the first arg beyond what we can handle,
2009 // or the '>', depending on whether we have too many or too few
2010 // arguments.
2011 SourceRange Range;
2012 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002013 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002014 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2015 << (NumArgs > NumParams)
2016 << (isa<ClassTemplateDecl>(Template)? 0 :
2017 isa<FunctionTemplateDecl>(Template)? 1 :
2018 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2019 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002020 Diag(Template->getLocation(), diag::note_template_decl_here)
2021 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002022 Invalid = true;
2023 }
Mike Stump1eb44332009-09-09 15:08:12 +00002024
2025 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002026 // [...] The type and form of each template-argument specified in
2027 // a template-id shall match the type and form specified for the
2028 // corresponding parameter declared by the template in its
2029 // template-parameter-list.
2030 unsigned ArgIdx = 0;
2031 for (TemplateParameterList::iterator Param = Params->begin(),
2032 ParamEnd = Params->end();
2033 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002034 if (ArgIdx > NumArgs && PartialTemplateArgs)
2035 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002036
Douglas Gregord9e15302009-11-11 19:41:09 +00002037 // If we have a template parameter pack, check every remaining template
2038 // argument against that template parameter pack.
2039 if ((*Param)->isTemplateParameterPack()) {
2040 Converted.BeginPack();
2041 for (; ArgIdx < NumArgs; ++ArgIdx) {
2042 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2043 TemplateLoc, RAngleLoc, Converted)) {
2044 Invalid = true;
2045 break;
2046 }
2047 }
2048 Converted.EndPack();
2049 continue;
2050 }
2051
Douglas Gregorf35f8282009-11-11 21:54:23 +00002052 if (ArgIdx < NumArgs) {
2053 // Check the template argument we were given.
2054 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2055 TemplateLoc, RAngleLoc, Converted))
2056 return true;
2057
2058 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002059 }
Douglas Gregore7526412009-11-11 19:31:23 +00002060
Douglas Gregorf35f8282009-11-11 21:54:23 +00002061 // We have a default template argument that we will use.
2062 TemplateArgumentLoc Arg;
2063
2064 // Retrieve the default template argument from the template
2065 // parameter. For each kind of template parameter, we substitute the
2066 // template arguments provided thus far and any "outer" template arguments
2067 // (when the template parameter was part of a nested template) into
2068 // the default argument.
2069 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2070 if (!TTP->hasDefaultArgument()) {
2071 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2072 break;
2073 }
2074
2075 DeclaratorInfo *ArgType = SubstDefaultTemplateArgument(*this,
2076 Template,
2077 TemplateLoc,
2078 RAngleLoc,
2079 TTP,
2080 Converted);
2081 if (!ArgType)
2082 return true;
2083
2084 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2085 ArgType);
2086 } else if (NonTypeTemplateParmDecl *NTTP
2087 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2088 if (!NTTP->hasDefaultArgument()) {
2089 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2090 break;
2091 }
2092
2093 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2094 TemplateLoc,
2095 RAngleLoc,
2096 NTTP,
2097 Converted);
2098 if (E.isInvalid())
2099 return true;
2100
2101 Expr *Ex = E.takeAs<Expr>();
2102 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2103 } else {
2104 TemplateTemplateParmDecl *TempParm
2105 = cast<TemplateTemplateParmDecl>(*Param);
2106
2107 if (!TempParm->hasDefaultArgument()) {
2108 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2109 break;
2110 }
2111
2112 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2113 TemplateLoc,
2114 RAngleLoc,
2115 TempParm,
2116 Converted);
2117 if (Name.isNull())
2118 return true;
2119
2120 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2121 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2122 TempParm->getDefaultArgument().getTemplateNameLoc());
2123 }
2124
2125 // Introduce an instantiation record that describes where we are using
2126 // the default template argument.
2127 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2128 Converted.getFlatArguments(),
2129 Converted.flatSize(),
2130 SourceRange(TemplateLoc, RAngleLoc));
2131
2132 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002133 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002134 RAngleLoc, Converted))
2135 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002136 }
2137
2138 return Invalid;
2139}
2140
2141/// \brief Check a template argument against its corresponding
2142/// template type parameter.
2143///
2144/// This routine implements the semantics of C++ [temp.arg.type]. It
2145/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002146bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00002147 DeclaratorInfo *ArgInfo) {
2148 assert(ArgInfo && "invalid DeclaratorInfo");
2149 QualType Arg = ArgInfo->getType();
2150
Douglas Gregorc15cb382009-02-09 23:23:08 +00002151 // C++ [temp.arg.type]p2:
2152 // A local type, a type with no linkage, an unnamed type or a type
2153 // compounded from any of these types shall not be used as a
2154 // template-argument for a template type-parameter.
2155 //
2156 // FIXME: Perform the recursive and no-linkage type checks.
2157 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00002158 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002159 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00002160 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002161 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00002162 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2163 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2164 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2165 << QualType(Tag, 0) << SR;
2166 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00002167 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall833ca992009-10-29 08:12:44 +00002168 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2169 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002170 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2171 return true;
2172 }
2173
2174 return false;
2175}
2176
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002177/// \brief Checks whether the given template argument is the address
2178/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002179bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2180 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002181 bool Invalid = false;
2182
2183 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002184 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002185 Arg = Cast->getSubExpr();
2186
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002187 // C++0x allows nullptr, and there's no further checking to be done for that.
2188 if (Arg->getType()->isNullPtrType())
2189 return false;
2190
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002191 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002192 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002193 // A template-argument for a non-type, non-template
2194 // template-parameter shall be one of: [...]
2195 //
2196 // -- the address of an object or function with external
2197 // linkage, including function templates and function
2198 // template-ids but excluding non-static class members,
2199 // expressed as & id-expression where the & is optional if
2200 // the name refers to a function or array, or if the
2201 // corresponding template-parameter is a reference; or
2202 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002203
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002204 // Ignore (and complain about) any excess parentheses.
2205 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2206 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002207 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002208 diag::err_template_arg_extra_parens)
2209 << Arg->getSourceRange();
2210 Invalid = true;
2211 }
2212
2213 Arg = Parens->getSubExpr();
2214 }
2215
2216 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2217 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2218 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2219 } else
2220 DRE = dyn_cast<DeclRefExpr>(Arg);
2221
2222 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00002223 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002224 diag::err_template_arg_not_object_or_func_form)
2225 << Arg->getSourceRange();
2226
2227 // Cannot refer to non-static data members
2228 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2229 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2230 << Field << Arg->getSourceRange();
2231
2232 // Cannot refer to non-static member functions
2233 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2234 if (!Method->isStatic())
Mike Stump1eb44332009-09-09 15:08:12 +00002235 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002236 diag::err_template_arg_method)
2237 << Method << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002238
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002239 // Functions must have external linkage.
2240 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregord85b5b92009-11-25 22:24:25 +00002241 if (Func->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump1eb44332009-09-09 15:08:12 +00002242 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002243 diag::err_template_arg_function_not_extern)
2244 << Func << Arg->getSourceRange();
2245 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2246 << true;
2247 return true;
2248 }
2249
2250 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002251 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002252 return Invalid;
2253 }
2254
2255 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregord85b5b92009-11-25 22:24:25 +00002256 if (Var->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump1eb44332009-09-09 15:08:12 +00002257 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002258 diag::err_template_arg_object_not_extern)
2259 << Var << Arg->getSourceRange();
2260 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2261 << true;
2262 return true;
2263 }
2264
2265 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002266 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002267 return Invalid;
2268 }
Mike Stump1eb44332009-09-09 15:08:12 +00002269
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002270 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002271 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002272 diag::err_template_arg_not_object_or_func)
2273 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002274 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002275 diag::note_template_arg_refers_here);
2276 return true;
2277}
2278
2279/// \brief Checks whether the given template argument is a pointer to
2280/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002281bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2282 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002283 bool Invalid = false;
2284
2285 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002286 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002287 Arg = Cast->getSubExpr();
2288
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002289 // C++0x allows nullptr, and there's no further checking to be done for that.
2290 if (Arg->getType()->isNullPtrType())
2291 return false;
2292
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002293 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002294 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002295 // A template-argument for a non-type, non-template
2296 // template-parameter shall be one of: [...]
2297 //
2298 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002299 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002300
2301 // Ignore (and complain about) any excess parentheses.
2302 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2303 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002304 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002305 diag::err_template_arg_extra_parens)
2306 << Arg->getSourceRange();
2307 Invalid = true;
2308 }
2309
2310 Arg = Parens->getSubExpr();
2311 }
2312
Douglas Gregorcaddba02009-11-12 18:38:13 +00002313 // A pointer-to-member constant written &Class::member.
2314 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002315 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2316 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2317 if (DRE && !DRE->getQualifier())
2318 DRE = 0;
2319 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002320 }
2321 // A constant of pointer-to-member type.
2322 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2323 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2324 if (VD->getType()->isMemberPointerType()) {
2325 if (isa<NonTypeTemplateParmDecl>(VD) ||
2326 (isa<VarDecl>(VD) &&
2327 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2328 if (Arg->isTypeDependent() || Arg->isValueDependent())
2329 Converted = TemplateArgument(Arg->Retain());
2330 else
2331 Converted = TemplateArgument(VD->getCanonicalDecl());
2332 return Invalid;
2333 }
2334 }
2335 }
2336
2337 DRE = 0;
2338 }
2339
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002340 if (!DRE)
2341 return Diag(Arg->getSourceRange().getBegin(),
2342 diag::err_template_arg_not_pointer_to_member_form)
2343 << Arg->getSourceRange();
2344
2345 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2346 assert((isa<FieldDecl>(DRE->getDecl()) ||
2347 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2348 "Only non-static member pointers can make it here");
2349
2350 // Okay: this is the address of a non-static member, and therefore
2351 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002352 if (Arg->isTypeDependent() || Arg->isValueDependent())
2353 Converted = TemplateArgument(Arg->Retain());
2354 else
2355 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002356 return Invalid;
2357 }
2358
2359 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002360 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002361 diag::err_template_arg_not_pointer_to_member_form)
2362 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002363 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002364 diag::note_template_arg_refers_here);
2365 return true;
2366}
2367
Douglas Gregorc15cb382009-02-09 23:23:08 +00002368/// \brief Check a template argument against its corresponding
2369/// non-type template parameter.
2370///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002371/// This routine implements the semantics of C++ [temp.arg.nontype].
2372/// It returns true if an error occurred, and false otherwise. \p
2373/// InstantiatedParamType is the type of the non-type template
2374/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002375///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002376/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002377bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002378 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002379 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002380 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2381
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002382 // If either the parameter has a dependent type or the argument is
2383 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002384 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00002385 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2386 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002387 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002388 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002389 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002390
2391 // C++ [temp.arg.nontype]p5:
2392 // The following conversions are performed on each expression used
2393 // as a non-type template-argument. If a non-type
2394 // template-argument cannot be converted to the type of the
2395 // corresponding template-parameter then the program is
2396 // ill-formed.
2397 //
2398 // -- for a non-type template-parameter of integral or
2399 // enumeration type, integral promotions (4.5) and integral
2400 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002401 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002402 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002403 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002404 // C++ [temp.arg.nontype]p1:
2405 // A template-argument for a non-type, non-template
2406 // template-parameter shall be one of:
2407 //
2408 // -- an integral constant-expression of integral or enumeration
2409 // type; or
2410 // -- the name of a non-type template-parameter; or
2411 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002412 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002413 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002414 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002415 diag::err_template_arg_not_integral_or_enumeral)
2416 << ArgType << Arg->getSourceRange();
2417 Diag(Param->getLocation(), diag::note_template_param_here);
2418 return true;
2419 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002420 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002421 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2422 << ArgType << Arg->getSourceRange();
2423 return true;
2424 }
2425
2426 // FIXME: We need some way to more easily get the unqualified form
2427 // of the types without going all the way to the
2428 // canonical type.
2429 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2430 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2431 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2432 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2433
2434 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002435 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002436 // Okay: no conversion necessary
2437 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2438 !ParamType->isEnumeralType()) {
2439 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002440 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002441 } else {
2442 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002443 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002444 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002445 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002446 Diag(Param->getLocation(), diag::note_template_param_here);
2447 return true;
2448 }
2449
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002450 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002451 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002452 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002453
2454 if (!Arg->isValueDependent()) {
2455 // Check that an unsigned parameter does not receive a negative
2456 // value.
2457 if (IntegerType->isUnsignedIntegerType()
2458 && (Value.isSigned() && Value.isNegative())) {
2459 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2460 << Value.toString(10) << Param->getType()
2461 << Arg->getSourceRange();
2462 Diag(Param->getLocation(), diag::note_template_param_here);
2463 return true;
2464 }
2465
2466 // Check that we don't overflow the template parameter type.
2467 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2468 if (Value.getActiveBits() > AllowedBits) {
Mike Stump1eb44332009-09-09 15:08:12 +00002469 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002470 diag::err_template_arg_too_large)
2471 << Value.toString(10) << Param->getType()
2472 << Arg->getSourceRange();
2473 Diag(Param->getLocation(), diag::note_template_param_here);
2474 return true;
2475 }
2476
2477 if (Value.getBitWidth() != AllowedBits)
2478 Value.extOrTrunc(AllowedBits);
2479 Value.setIsSigned(IntegerType->isSignedIntegerType());
2480 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002481
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002482 // Add the value of this argument to the list of converted
2483 // arguments. We use the bitwidth and signedness of the template
2484 // parameter.
2485 if (Arg->isValueDependent()) {
2486 // The argument is value-dependent. Create a new
2487 // TemplateArgument with the converted expression.
2488 Converted = TemplateArgument(Arg);
2489 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002490 }
2491
John McCall833ca992009-10-29 08:12:44 +00002492 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002493 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002494 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002495 return false;
2496 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002497
Douglas Gregorb86b0572009-02-11 01:18:59 +00002498 // Handle pointer-to-function, reference-to-function, and
2499 // pointer-to-member-function all in (roughly) the same way.
2500 if (// -- For a non-type template-parameter of type pointer to
2501 // function, only the function-to-pointer conversion (4.3) is
2502 // applied. If the template-argument represents a set of
2503 // overloaded functions (or a pointer to such), the matching
2504 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002505 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002506 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002507 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002508 // -- For a non-type template-parameter of type reference to
2509 // function, no conversions apply. If the template-argument
2510 // represents a set of overloaded functions, the matching
2511 // function is selected from the set (13.4).
2512 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002513 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002514 // -- For a non-type template-parameter of type pointer to
2515 // member function, no conversions apply. If the
2516 // template-argument represents a set of overloaded member
2517 // functions, the matching member function is selected from
2518 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002519 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002520 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002521 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002522 ->isFunctionType())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002523 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002524 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002525 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002526 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2527 ParamType->isMemberPointerType())) {
2528 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002529 if (ParamType->isMemberPointerType())
2530 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2531 else
2532 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002533 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002534 ArgType = Context.getPointerType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002535 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump1eb44332009-09-09 15:08:12 +00002536 } else if (FunctionDecl *Fn
Douglas Gregora35284b2009-02-11 00:19:33 +00002537 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002538 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2539 return true;
2540
Anders Carlsson96ad5332009-10-21 17:16:23 +00002541 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00002542 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002543 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002544 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman73c39ab2009-10-20 08:27:19 +00002545 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregora35284b2009-02-11 00:19:33 +00002546 }
2547 }
2548
Mike Stump1eb44332009-09-09 15:08:12 +00002549 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002550 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002551 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002552 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002553 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002554 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002555 Diag(Param->getLocation(), diag::note_template_param_here);
2556 return true;
2557 }
Mike Stump1eb44332009-09-09 15:08:12 +00002558
Douglas Gregorcaddba02009-11-12 18:38:13 +00002559 if (ParamType->isMemberPointerType())
2560 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump1eb44332009-09-09 15:08:12 +00002561
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002562 NamedDecl *Entity = 0;
2563 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2564 return true;
2565
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002566 if (Entity)
2567 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002568 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002569 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00002570 }
2571
Chris Lattnerfe90de72009-02-20 21:37:53 +00002572 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002573 // -- for a non-type template-parameter of type pointer to
2574 // object, qualification conversions (4.4) and the
2575 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002576 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002577 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002578 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002579
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002580 if (ArgType->isNullPtrType()) {
2581 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002582 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002583 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002584 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002585 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002586 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002587
Douglas Gregorb86b0572009-02-11 01:18:59 +00002588 if (IsQualificationConversion(ArgType, ParamType)) {
2589 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002590 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002591 }
Mike Stump1eb44332009-09-09 15:08:12 +00002592
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002593 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002594 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002595 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002596 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002597 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002598 Diag(Param->getLocation(), diag::note_template_param_here);
2599 return true;
2600 }
Mike Stump1eb44332009-09-09 15:08:12 +00002601
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002602 NamedDecl *Entity = 0;
2603 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2604 return true;
2605
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002606 if (Entity)
2607 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002608 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002609 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002610 }
Mike Stump1eb44332009-09-09 15:08:12 +00002611
Ted Kremenek6217b802009-07-29 21:53:49 +00002612 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002613 // -- For a non-type template-parameter of type reference to
2614 // object, no conversions apply. The type referred to by the
2615 // reference may be more cv-qualified than the (otherwise
2616 // identical) type of the template-argument. The
2617 // template-parameter is bound directly to the
2618 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002619 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002620 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002621
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002622 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002623 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002624 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002625 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002626 << Arg->getSourceRange();
2627 Diag(Param->getLocation(), diag::note_template_param_here);
2628 return true;
2629 }
2630
Mike Stump1eb44332009-09-09 15:08:12 +00002631 unsigned ParamQuals
Douglas Gregorb86b0572009-02-11 01:18:59 +00002632 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2633 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00002634
Douglas Gregorb86b0572009-02-11 01:18:59 +00002635 if ((ParamQuals | ArgQuals) != ParamQuals) {
2636 Diag(Arg->getSourceRange().getBegin(),
2637 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002638 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002639 << Arg->getSourceRange();
2640 Diag(Param->getLocation(), diag::note_template_param_here);
2641 return true;
2642 }
Mike Stump1eb44332009-09-09 15:08:12 +00002643
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002644 NamedDecl *Entity = 0;
2645 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2646 return true;
2647
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002648 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002649 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002650 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002651 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002652
2653 // -- For a non-type template-parameter of type pointer to data
2654 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002655 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00002656 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2657
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002658 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002659 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002660 } else if (ArgType->isNullPtrType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002661 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002662 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002663 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002664 } else {
2665 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002666 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00002667 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002668 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00002669 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002670 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00002671 }
2672
Douglas Gregorcaddba02009-11-12 18:38:13 +00002673 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002674}
2675
2676/// \brief Check a template argument against its corresponding
2677/// template template parameter.
2678///
2679/// This routine implements the semantics of C++ [temp.arg.template].
2680/// It returns true if an error occurred, and false otherwise.
2681bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00002682 const TemplateArgumentLoc &Arg) {
2683 TemplateName Name = Arg.getArgument().getAsTemplate();
2684 TemplateDecl *Template = Name.getAsTemplateDecl();
2685 if (!Template) {
2686 // Any dependent template name is fine.
2687 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2688 return false;
2689 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002690
2691 // C++ [temp.arg.template]p1:
2692 // A template-argument for a template template-parameter shall be
2693 // the name of a class template, expressed as id-expression. Only
2694 // primary class templates are considered when matching the
2695 // template template argument with the corresponding parameter;
2696 // partial specializations are not considered even if their
2697 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002698 //
2699 // Note that we also allow template template parameters here, which
2700 // will happen when we are dealing with, e.g., class template
2701 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00002702 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002703 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002704 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00002705 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00002706 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00002707 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002708 << Template;
2709 }
2710
2711 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2712 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00002713 true,
2714 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00002715 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00002716}
2717
Douglas Gregorddc29e12009-02-06 22:42:48 +00002718/// \brief Determine whether the given template parameter lists are
2719/// equivalent.
2720///
Mike Stump1eb44332009-09-09 15:08:12 +00002721/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00002722/// source code as part of a new template declaration.
2723///
2724/// \param Old The old template parameter list, typically found via
2725/// name lookup of the template declared with this template parameter
2726/// list.
2727///
2728/// \param Complain If true, this routine will produce a diagnostic if
2729/// the template parameter lists are not equivalent.
2730///
Douglas Gregorfb898e12009-11-12 16:20:59 +00002731/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00002732///
2733/// \param TemplateArgLoc If this source location is valid, then we
2734/// are actually checking the template parameter list of a template
2735/// argument (New) against the template parameter list of its
2736/// corresponding template template parameter (Old). We produce
2737/// slightly different diagnostics in this scenario.
2738///
Douglas Gregorddc29e12009-02-06 22:42:48 +00002739/// \returns True if the template parameter lists are equal, false
2740/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002741bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00002742Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2743 TemplateParameterList *Old,
2744 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00002745 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002746 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002747 if (Old->size() != New->size()) {
2748 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002749 unsigned NextDiag = diag::err_template_param_list_different_arity;
2750 if (TemplateArgLoc.isValid()) {
2751 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2752 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00002753 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002754 Diag(New->getTemplateLoc(), NextDiag)
2755 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00002756 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002757 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00002758 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002759 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002760 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2761 }
2762
2763 return false;
2764 }
2765
2766 for (TemplateParameterList::iterator OldParm = Old->begin(),
2767 OldParmEnd = Old->end(), NewParm = New->begin();
2768 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2769 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002770 if (Complain) {
2771 unsigned NextDiag = diag::err_template_param_different_kind;
2772 if (TemplateArgLoc.isValid()) {
2773 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2774 NextDiag = diag::note_template_param_different_kind;
2775 }
2776 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002777 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002778 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002779 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00002780 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00002781 return false;
2782 }
2783
2784 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2785 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00002786 // know we're at the same index).
Mike Stump1eb44332009-09-09 15:08:12 +00002787 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002788 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2789 // The types of non-type template parameters must agree.
2790 NonTypeTemplateParmDecl *NewNTTP
2791 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00002792
2793 // If we are matching a template template argument to a template
2794 // template parameter and one of the non-type template parameter types
2795 // is dependent, then we must wait until template instantiation time
2796 // to actually compare the arguments.
2797 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2798 (OldNTTP->getType()->isDependentType() ||
2799 NewNTTP->getType()->isDependentType()))
2800 continue;
2801
Douglas Gregorddc29e12009-02-06 22:42:48 +00002802 if (Context.getCanonicalType(OldNTTP->getType()) !=
2803 Context.getCanonicalType(NewNTTP->getType())) {
2804 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002805 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2806 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002807 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002808 diag::err_template_arg_template_params_mismatch);
2809 NextDiag = diag::note_template_nontype_parm_different_type;
2810 }
2811 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002812 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00002813 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00002814 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00002815 diag::note_template_nontype_parm_prev_declaration)
2816 << OldNTTP->getType();
2817 }
2818 return false;
2819 }
2820 } else {
2821 // The template parameter lists of template template
2822 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00002823 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00002824 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00002825 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002826 = cast<TemplateTemplateParmDecl>(*OldParm);
2827 TemplateTemplateParmDecl *NewTTP
2828 = cast<TemplateTemplateParmDecl>(*NewParm);
2829 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2830 OldTTP->getTemplateParameters(),
2831 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00002832 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00002833 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002834 return false;
2835 }
2836 }
2837
2838 return true;
2839}
2840
2841/// \brief Check whether a template can be declared within this scope.
2842///
2843/// If the template declaration is valid in this scope, returns
2844/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00002845bool
Douglas Gregor05396e22009-08-25 17:23:04 +00002846Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002847 // Find the nearest enclosing declaration scope.
2848 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2849 (S->getFlags() & Scope::TemplateParamScope) != 0)
2850 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002851
Douglas Gregorddc29e12009-02-06 22:42:48 +00002852 // C++ [temp]p2:
2853 // A template-declaration can appear only as a namespace scope or
2854 // class scope declaration.
2855 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00002856 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2857 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00002858 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00002859 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002860
Eli Friedman1503f772009-07-31 01:43:05 +00002861 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002862 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002863
2864 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2865 return false;
2866
Mike Stump1eb44332009-09-09 15:08:12 +00002867 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002868 diag::err_template_outside_namespace_or_class_scope)
2869 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002870}
Douglas Gregorcc636682009-02-17 23:15:12 +00002871
Douglas Gregord5cb8762009-10-07 00:13:32 +00002872/// \brief Determine what kind of template specialization the given declaration
2873/// is.
2874static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2875 if (!D)
2876 return TSK_Undeclared;
2877
Douglas Gregorf6b11852009-10-08 15:14:33 +00002878 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2879 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00002880 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2881 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002882 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2883 return Var->getTemplateSpecializationKind();
2884
Douglas Gregord5cb8762009-10-07 00:13:32 +00002885 return TSK_Undeclared;
2886}
2887
Douglas Gregor9302da62009-10-14 23:50:59 +00002888/// \brief Check whether a specialization is well-formed in the current
2889/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00002890///
Douglas Gregor9302da62009-10-14 23:50:59 +00002891/// This routine determines whether a template specialization can be declared
2892/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00002893///
2894/// \param S the semantic analysis object for which this check is being
2895/// performed.
2896///
2897/// \param Specialized the entity being specialized or instantiated, which
2898/// may be a kind of template (class template, function template, etc.) or
2899/// a member of a class template (member function, static data member,
2900/// member class).
2901///
2902/// \param PrevDecl the previous declaration of this entity, if any.
2903///
2904/// \param Loc the location of the explicit specialization or instantiation of
2905/// this entity.
2906///
2907/// \param IsPartialSpecialization whether this is a partial specialization of
2908/// a class template.
2909///
Douglas Gregord5cb8762009-10-07 00:13:32 +00002910/// \returns true if there was an error that we cannot recover from, false
2911/// otherwise.
2912static bool CheckTemplateSpecializationScope(Sema &S,
2913 NamedDecl *Specialized,
2914 NamedDecl *PrevDecl,
2915 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00002916 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002917 // Keep these "kind" numbers in sync with the %select statements in the
2918 // various diagnostics emitted by this routine.
2919 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002920 bool isTemplateSpecialization = false;
2921 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002922 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002923 isTemplateSpecialization = true;
2924 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002925 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002926 isTemplateSpecialization = true;
2927 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00002928 EntityKind = 3;
2929 else if (isa<VarDecl>(Specialized))
2930 EntityKind = 4;
2931 else if (isa<RecordDecl>(Specialized))
2932 EntityKind = 5;
2933 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00002934 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2935 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00002936 return true;
2937 }
2938
Douglas Gregor88b70942009-02-25 22:02:03 +00002939 // C++ [temp.expl.spec]p2:
2940 // An explicit specialization shall be declared in the namespace
2941 // of which the template is a member, or, for member templates, in
2942 // the namespace of which the enclosing class or enclosing class
2943 // template is a member. An explicit specialization of a member
2944 // function, member class or static data member of a class
2945 // template shall be declared in the namespace of which the class
2946 // template is a member. Such a declaration may also be a
2947 // definition. If the declaration is not a definition, the
2948 // specialization may be defined later in the name- space in which
2949 // the explicit specialization was declared, or in a namespace
2950 // that encloses the one in which the explicit specialization was
2951 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00002952 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2953 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00002954 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00002955 return true;
2956 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002957
Douglas Gregor0a407472009-10-07 17:30:37 +00002958 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2959 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00002960 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00002961 return true;
2962 }
2963
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002964 // C++ [temp.class.spec]p6:
2965 // A class template partial specialization may be declared or redeclared
2966 // in any namespace scope in which its definition may be defined (14.5.1
2967 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00002968 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002969 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00002970 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002971 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00002972 if ((!PrevDecl ||
2973 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2974 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2975 // There is no prior declaration of this entity, so this
2976 // specialization must be in the same context as the template
2977 // itself.
2978 if (!DC->Equals(SpecializedContext)) {
2979 if (isa<TranslationUnitDecl>(SpecializedContext))
2980 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2981 << EntityKind << Specialized;
2982 else if (isa<NamespaceDecl>(SpecializedContext))
2983 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2984 << EntityKind << Specialized
2985 << cast<NamedDecl>(SpecializedContext);
2986
2987 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2988 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002989 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002990 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00002991
2992 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00002993 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00002994 // Note that HandleDeclarator() performs this check for explicit
2995 // specializations of function templates, static data members, and member
2996 // functions, so we skip the check here for those kinds of entities.
2997 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002998 // Should we refactor that check, so that it occurs later?
2999 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003000 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3001 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003002 if (isa<TranslationUnitDecl>(SpecializedContext))
3003 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3004 << EntityKind << Specialized;
3005 else if (isa<NamespaceDecl>(SpecializedContext))
3006 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3007 << EntityKind << Specialized
3008 << cast<NamedDecl>(SpecializedContext);
3009
Douglas Gregor9302da62009-10-14 23:50:59 +00003010 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003011 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003012
3013 // FIXME: check for specialization-after-instantiation errors and such.
3014
Douglas Gregor88b70942009-02-25 22:02:03 +00003015 return false;
3016}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003017
Douglas Gregore94866f2009-06-12 21:21:02 +00003018/// \brief Check the non-type template arguments of a class template
3019/// partial specialization according to C++ [temp.class.spec]p9.
3020///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003021/// \param TemplateParams the template parameters of the primary class
3022/// template.
3023///
3024/// \param TemplateArg the template arguments of the class template
3025/// partial specialization.
3026///
3027/// \param MirrorsPrimaryTemplate will be set true if the class
3028/// template partial specialization arguments are identical to the
3029/// implicit template arguments of the primary template. This is not
3030/// necessarily an error (C++0x), and it is left to the caller to diagnose
3031/// this condition when it is an error.
3032///
Douglas Gregore94866f2009-06-12 21:21:02 +00003033/// \returns true if there was an error, false otherwise.
3034bool Sema::CheckClassTemplatePartialSpecializationArgs(
3035 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00003036 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003037 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003038 // FIXME: the interface to this function will have to change to
3039 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003040 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003041
Anders Carlssonfb250522009-06-23 01:26:57 +00003042 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00003043
Douglas Gregore94866f2009-06-12 21:21:02 +00003044 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003045 // Determine whether the template argument list of the partial
3046 // specialization is identical to the implicit argument list of
3047 // the primary template. The caller may need to diagnostic this as
3048 // an error per C++ [temp.class.spec]p9b3.
3049 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003050 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003051 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3052 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003053 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003054 MirrorsPrimaryTemplate = false;
3055 } else if (TemplateTemplateParmDecl *TTP
3056 = dyn_cast<TemplateTemplateParmDecl>(
3057 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003058 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003059 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003060 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003061 if (!ArgDecl ||
3062 ArgDecl->getIndex() != TTP->getIndex() ||
3063 ArgDecl->getDepth() != TTP->getDepth())
3064 MirrorsPrimaryTemplate = false;
3065 }
3066 }
3067
Mike Stump1eb44332009-09-09 15:08:12 +00003068 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003069 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003070 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003071 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003072 }
3073
Anders Carlsson6360be72009-06-13 18:20:51 +00003074 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003075 if (!ArgExpr) {
3076 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003077 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003078 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003079
3080 // C++ [temp.class.spec]p8:
3081 // A non-type argument is non-specialized if it is the name of a
3082 // non-type parameter. All other non-type arguments are
3083 // specialized.
3084 //
3085 // Below, we check the two conditions that only apply to
3086 // specialized non-type arguments, so skip any non-specialized
3087 // arguments.
3088 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003089 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003090 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003091 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003092 (Param->getIndex() != NTTP->getIndex() ||
3093 Param->getDepth() != NTTP->getDepth()))
3094 MirrorsPrimaryTemplate = false;
3095
Douglas Gregore94866f2009-06-12 21:21:02 +00003096 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003097 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003098
3099 // C++ [temp.class.spec]p9:
3100 // Within the argument list of a class template partial
3101 // specialization, the following restrictions apply:
3102 // -- A partially specialized non-type argument expression
3103 // shall not involve a template parameter of the partial
3104 // specialization except when the argument expression is a
3105 // simple identifier.
3106 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003107 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003108 diag::err_dependent_non_type_arg_in_partial_spec)
3109 << ArgExpr->getSourceRange();
3110 return true;
3111 }
3112
3113 // -- The type of a template parameter corresponding to a
3114 // specialized non-type argument shall not be dependent on a
3115 // parameter of the specialization.
3116 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003117 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003118 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3119 << Param->getType()
3120 << ArgExpr->getSourceRange();
3121 Diag(Param->getLocation(), diag::note_template_param_here);
3122 return true;
3123 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003124
3125 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003126 }
3127
3128 return false;
3129}
3130
Douglas Gregor212e81c2009-03-25 00:13:59 +00003131Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003132Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3133 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00003134 SourceLocation KWLoc,
Douglas Gregorcc636682009-02-17 23:15:12 +00003135 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003136 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00003137 SourceLocation TemplateNameLoc,
3138 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00003139 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00003140 SourceLocation RAngleLoc,
3141 AttributeList *Attr,
3142 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003143 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00003144
Douglas Gregorcc636682009-02-17 23:15:12 +00003145 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00003146 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003147 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00003148 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3149
3150 if (!ClassTemplate) {
3151 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3152 << (Name.getAsTemplateDecl() &&
3153 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3154 return true;
3155 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003156
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003157 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003158 bool isPartialSpecialization = false;
3159
Douglas Gregor88b70942009-02-25 22:02:03 +00003160 // Check the validity of the template headers that introduce this
3161 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003162 // FIXME: We probably shouldn't complain about these headers for
3163 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00003164 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00003165 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3166 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003167 TemplateParameterLists.size(),
3168 isExplicitSpecialization);
Douglas Gregor05396e22009-08-25 17:23:04 +00003169 if (TemplateParams && TemplateParams->size() > 0) {
3170 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003171
Douglas Gregor05396e22009-08-25 17:23:04 +00003172 // C++ [temp.class.spec]p10:
3173 // The template parameter list of a specialization shall not
3174 // contain default template argument values.
3175 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3176 Decl *Param = TemplateParams->getParam(I);
3177 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3178 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003179 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003180 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00003181 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003182 }
3183 } else if (NonTypeTemplateParmDecl *NTTP
3184 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3185 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003186 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003187 diag::err_default_arg_in_partial_spec)
3188 << DefArg->getSourceRange();
3189 NTTP->setDefaultArgument(0);
3190 DefArg->Destroy(Context);
3191 }
3192 } else {
3193 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003194 if (TTP->hasDefaultArgument()) {
3195 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003196 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003197 << TTP->getDefaultArgument().getSourceRange();
3198 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003199 }
3200 }
3201 }
Douglas Gregora735b202009-10-13 14:39:41 +00003202 } else if (TemplateParams) {
3203 if (TUK == TUK_Friend)
3204 Diag(KWLoc, diag::err_template_spec_friend)
3205 << CodeModificationHint::CreateRemoval(
3206 SourceRange(TemplateParams->getTemplateLoc(),
3207 TemplateParams->getRAngleLoc()))
3208 << SourceRange(LAngleLoc, RAngleLoc);
3209 else
3210 isExplicitSpecialization = true;
3211 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003212 Diag(KWLoc, diag::err_template_spec_needs_header)
3213 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003214 isExplicitSpecialization = true;
3215 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003216
Douglas Gregorcc636682009-02-17 23:15:12 +00003217 // Check that the specialization uses the same tag kind as the
3218 // original template.
3219 TagDecl::TagKind Kind;
3220 switch (TagSpec) {
3221 default: assert(0 && "Unknown tag type!");
3222 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3223 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3224 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3225 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003226 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003227 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003228 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003229 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003230 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00003231 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003232 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003233 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003234 diag::note_previous_use);
3235 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3236 }
3237
Douglas Gregor40808ce2009-03-09 23:48:35 +00003238 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00003239 TemplateArgumentListInfo TemplateArgs;
3240 TemplateArgs.setLAngleLoc(LAngleLoc);
3241 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00003242 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003243
Douglas Gregorcc636682009-02-17 23:15:12 +00003244 // Check that the template argument list is well-formed for this
3245 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003246 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3247 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00003248 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3249 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003250 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003251
Mike Stump1eb44332009-09-09 15:08:12 +00003252 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003253 ClassTemplate->getTemplateParameters()->size()) &&
3254 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003255
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003256 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003257 // corresponds to these arguments.
3258 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003259 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003260 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003261 if (CheckClassTemplatePartialSpecializationArgs(
3262 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003263 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003264 return true;
3265
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003266 if (MirrorsPrimaryTemplate) {
3267 // C++ [temp.class.spec]p9b3:
3268 //
Mike Stump1eb44332009-09-09 15:08:12 +00003269 // -- The argument list of the specialization shall not be identical
3270 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003271 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003272 << (TUK == TUK_Definition)
Mike Stump1eb44332009-09-09 15:08:12 +00003273 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003274 RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003275 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003276 ClassTemplate->getIdentifier(),
3277 TemplateNameLoc,
3278 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003279 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003280 AS_none);
3281 }
3282
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003283 // FIXME: Diagnose friend partial specializations
3284
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003285 // FIXME: Template parameter list matters, too
Mike Stump1eb44332009-09-09 15:08:12 +00003286 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003287 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003288 Converted.flatSize(),
3289 Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003290 } else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00003291 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003292 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003293 Converted.flatSize(),
3294 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00003295 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003296 ClassTemplateSpecializationDecl *PrevDecl = 0;
3297
3298 if (isPartialSpecialization)
3299 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00003300 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003301 InsertPos);
3302 else
3303 PrevDecl
3304 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003305
3306 ClassTemplateSpecializationDecl *Specialization = 0;
3307
Douglas Gregor88b70942009-02-25 22:02:03 +00003308 // Check whether we can declare a class template specialization in
3309 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003310 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003311 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003312 TemplateNameLoc,
3313 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003314 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003315
Douglas Gregorb88e8882009-07-30 17:40:51 +00003316 // The canonical type
3317 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003318 if (PrevDecl &&
3319 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3320 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003321 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003322 // arguments was referenced but not declared, or we're only
3323 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003324 // declaration node as our own, updating its source location to
3325 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003326 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003327 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003328 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003329 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003330 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003331 // Build the canonical type that describes the converted template
3332 // arguments of the class template partial specialization.
3333 CanonType = Context.getTemplateSpecializationType(
3334 TemplateName(ClassTemplate),
3335 Converted.getFlatArguments(),
3336 Converted.flatSize());
3337
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003338 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003339 ClassTemplatePartialSpecializationDecl *PrevPartial
3340 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00003341 ClassTemplatePartialSpecializationDecl *Partial
3342 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003343 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003344 TemplateNameLoc,
3345 TemplateParams,
3346 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003347 Converted,
John McCalld5532b62009-11-23 01:53:49 +00003348 TemplateArgs,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003349 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003350
3351 if (PrevPartial) {
3352 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3353 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3354 } else {
3355 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3356 }
3357 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003358
Douglas Gregored9c0f92009-10-29 00:04:11 +00003359 // If we are providing an explicit specialization of a member class
3360 // template specialization, make a note of that.
3361 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3362 PrevPartial->setMemberSpecialization();
3363
Douglas Gregor031a5882009-06-13 00:26:55 +00003364 // Check that all of the template parameters of the class template
3365 // partial specialization are deducible from the template
3366 // arguments. If not, this class template partial specialization
3367 // will never be used.
3368 llvm::SmallVector<bool, 8> DeducibleParams;
3369 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003370 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003371 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003372 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003373 unsigned NumNonDeducible = 0;
3374 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3375 if (!DeducibleParams[I])
3376 ++NumNonDeducible;
3377
3378 if (NumNonDeducible) {
3379 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3380 << (NumNonDeducible > 1)
3381 << SourceRange(TemplateNameLoc, RAngleLoc);
3382 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3383 if (!DeducibleParams[I]) {
3384 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3385 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003386 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003387 diag::note_partial_spec_unused_parameter)
3388 << Param->getDeclName();
3389 else
Mike Stump1eb44332009-09-09 15:08:12 +00003390 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003391 diag::note_partial_spec_unused_parameter)
3392 << std::string("<anonymous>");
3393 }
3394 }
3395 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003396 } else {
3397 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003398 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003399 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00003400 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorcc636682009-02-17 23:15:12 +00003401 ClassTemplate->getDeclContext(),
3402 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003403 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003404 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003405 PrevDecl);
3406
3407 if (PrevDecl) {
3408 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3409 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3410 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003411 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00003412 InsertPos);
3413 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00003414
3415 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003416 }
3417
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003418 // C++ [temp.expl.spec]p6:
3419 // If a template, a member template or the member of a class template is
3420 // explicitly specialized then that specialization shall be declared
3421 // before the first use of that specialization that would cause an implicit
3422 // instantiation to take place, in every translation unit in which such a
3423 // use occurs; no diagnostic is required.
3424 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3425 SourceRange Range(TemplateNameLoc, RAngleLoc);
3426 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3427 << Context.getTypeDeclType(Specialization) << Range;
3428
3429 Diag(PrevDecl->getPointOfInstantiation(),
3430 diag::note_instantiation_required_here)
3431 << (PrevDecl->getTemplateSpecializationKind()
3432 != TSK_ImplicitInstantiation);
3433 return true;
3434 }
3435
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003436 // If this is not a friend, note that this is an explicit specialization.
3437 if (TUK != TUK_Friend)
3438 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003439
3440 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003441 if (TUK == TUK_Definition) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003442 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003443 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003444 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003445 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003446 Diag(Def->getLocation(), diag::note_previous_definition);
3447 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003448 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003449 }
3450 }
3451
Douglas Gregorfc705b82009-02-26 22:19:44 +00003452 // Build the fully-sugared type for this class template
3453 // specialization as the user wrote in the specialization
3454 // itself. This means that we'll pretty-print the type retrieved
3455 // from the specialization's declaration the way that the user
3456 // actually wrote the specialization, rather than formatting the
3457 // name based on the "canonical" representation used to store the
3458 // template arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003459 QualType WrittenTy
John McCalld5532b62009-11-23 01:53:49 +00003460 = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003461 if (TUK != TUK_Friend)
3462 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003463 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00003464
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003465 // C++ [temp.expl.spec]p9:
3466 // A template explicit specialization is in the scope of the
3467 // namespace in which the template was defined.
3468 //
3469 // We actually implement this paragraph where we set the semantic
3470 // context (in the creation of the ClassTemplateSpecializationDecl),
3471 // but we also maintain the lexical context where the actual
3472 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00003473 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003474
Douglas Gregorcc636682009-02-17 23:15:12 +00003475 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003476 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00003477 Specialization->startDefinition();
3478
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003479 if (TUK == TUK_Friend) {
3480 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3481 TemplateNameLoc,
3482 WrittenTy.getTypePtr(),
3483 /*FIXME:*/KWLoc);
3484 Friend->setAccess(AS_public);
3485 CurContext->addDecl(Friend);
3486 } else {
3487 // Add the specialization into its lexical context, so that it can
3488 // be seen when iterating through the list of declarations in that
3489 // context. However, specializations are not found by name lookup.
3490 CurContext->addDecl(Specialization);
3491 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003492 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003493}
Douglas Gregord57959a2009-03-27 23:10:48 +00003494
Mike Stump1eb44332009-09-09 15:08:12 +00003495Sema::DeclPtrTy
3496Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00003497 MultiTemplateParamsArg TemplateParameterLists,
3498 Declarator &D) {
3499 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3500}
3501
Mike Stump1eb44332009-09-09 15:08:12 +00003502Sema::DeclPtrTy
3503Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003504 MultiTemplateParamsArg TemplateParameterLists,
3505 Declarator &D) {
3506 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3507 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3508 "Not a function declarator!");
3509 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00003510
Douglas Gregor52591bf2009-06-24 00:54:41 +00003511 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00003512 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00003513 }
Mike Stump1eb44332009-09-09 15:08:12 +00003514
Douglas Gregor52591bf2009-06-24 00:54:41 +00003515 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003516
3517 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003518 move(TemplateParameterLists),
3519 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003520 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003521 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00003522 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00003523 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003524 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3525 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00003526 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00003527}
3528
Douglas Gregor454885e2009-10-15 15:54:05 +00003529/// \brief Diagnose cases where we have an explicit template specialization
3530/// before/after an explicit template instantiation, producing diagnostics
3531/// for those cases where they are required and determining whether the
3532/// new specialization/instantiation will have any effect.
3533///
Douglas Gregor454885e2009-10-15 15:54:05 +00003534/// \param NewLoc the location of the new explicit specialization or
3535/// instantiation.
3536///
3537/// \param NewTSK the kind of the new explicit specialization or instantiation.
3538///
3539/// \param PrevDecl the previous declaration of the entity.
3540///
3541/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3542///
3543/// \param PrevPointOfInstantiation if valid, indicates where the previus
3544/// declaration was instantiated (either implicitly or explicitly).
3545///
3546/// \param SuppressNew will be set to true to indicate that the new
3547/// specialization or instantiation has no effect and should be ignored.
3548///
3549/// \returns true if there was an error that should prevent the introduction of
3550/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00003551bool
3552Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3553 TemplateSpecializationKind NewTSK,
3554 NamedDecl *PrevDecl,
3555 TemplateSpecializationKind PrevTSK,
3556 SourceLocation PrevPointOfInstantiation,
3557 bool &SuppressNew) {
Douglas Gregor454885e2009-10-15 15:54:05 +00003558 SuppressNew = false;
3559
3560 switch (NewTSK) {
3561 case TSK_Undeclared:
3562 case TSK_ImplicitInstantiation:
3563 assert(false && "Don't check implicit instantiations here");
3564 return false;
3565
3566 case TSK_ExplicitSpecialization:
3567 switch (PrevTSK) {
3568 case TSK_Undeclared:
3569 case TSK_ExplicitSpecialization:
3570 // Okay, we're just specializing something that is either already
3571 // explicitly specialized or has merely been mentioned without any
3572 // instantiation.
3573 return false;
3574
3575 case TSK_ImplicitInstantiation:
3576 if (PrevPointOfInstantiation.isInvalid()) {
3577 // The declaration itself has not actually been instantiated, so it is
3578 // still okay to specialize it.
3579 return false;
3580 }
3581 // Fall through
3582
3583 case TSK_ExplicitInstantiationDeclaration:
3584 case TSK_ExplicitInstantiationDefinition:
3585 assert((PrevTSK == TSK_ImplicitInstantiation ||
3586 PrevPointOfInstantiation.isValid()) &&
3587 "Explicit instantiation without point of instantiation?");
3588
3589 // C++ [temp.expl.spec]p6:
3590 // If a template, a member template or the member of a class template
3591 // is explicitly specialized then that specialization shall be declared
3592 // before the first use of that specialization that would cause an
3593 // implicit instantiation to take place, in every translation unit in
3594 // which such a use occurs; no diagnostic is required.
Douglas Gregor0d035142009-10-27 18:42:08 +00003595 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00003596 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003597 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00003598 << (PrevTSK != TSK_ImplicitInstantiation);
3599
3600 return true;
3601 }
3602 break;
3603
3604 case TSK_ExplicitInstantiationDeclaration:
3605 switch (PrevTSK) {
3606 case TSK_ExplicitInstantiationDeclaration:
3607 // This explicit instantiation declaration is redundant (that's okay).
3608 SuppressNew = true;
3609 return false;
3610
3611 case TSK_Undeclared:
3612 case TSK_ImplicitInstantiation:
3613 // We're explicitly instantiating something that may have already been
3614 // implicitly instantiated; that's fine.
3615 return false;
3616
3617 case TSK_ExplicitSpecialization:
3618 // C++0x [temp.explicit]p4:
3619 // For a given set of template parameters, if an explicit instantiation
3620 // of a template appears after a declaration of an explicit
3621 // specialization for that template, the explicit instantiation has no
3622 // effect.
3623 return false;
3624
3625 case TSK_ExplicitInstantiationDefinition:
3626 // C++0x [temp.explicit]p10:
3627 // If an entity is the subject of both an explicit instantiation
3628 // declaration and an explicit instantiation definition in the same
3629 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00003630 Diag(NewLoc,
3631 diag::err_explicit_instantiation_declaration_after_definition);
3632 Diag(PrevPointOfInstantiation,
3633 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00003634 assert(PrevPointOfInstantiation.isValid() &&
3635 "Explicit instantiation without point of instantiation?");
3636 SuppressNew = true;
3637 return false;
3638 }
3639 break;
3640
3641 case TSK_ExplicitInstantiationDefinition:
3642 switch (PrevTSK) {
3643 case TSK_Undeclared:
3644 case TSK_ImplicitInstantiation:
3645 // We're explicitly instantiating something that may have already been
3646 // implicitly instantiated; that's fine.
3647 return false;
3648
3649 case TSK_ExplicitSpecialization:
3650 // C++ DR 259, C++0x [temp.explicit]p4:
3651 // For a given set of template parameters, if an explicit
3652 // instantiation of a template appears after a declaration of
3653 // an explicit specialization for that template, the explicit
3654 // instantiation has no effect.
3655 //
3656 // In C++98/03 mode, we only give an extension warning here, because it
3657 // is not not harmful to try to explicitly instantiate something that
3658 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00003659 if (!getLangOptions().CPlusPlus0x) {
3660 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00003661 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003662 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00003663 diag::note_previous_template_specialization);
3664 }
3665 SuppressNew = true;
3666 return false;
3667
3668 case TSK_ExplicitInstantiationDeclaration:
3669 // We're explicity instantiating a definition for something for which we
3670 // were previously asked to suppress instantiations. That's fine.
3671 return false;
3672
3673 case TSK_ExplicitInstantiationDefinition:
3674 // C++0x [temp.spec]p5:
3675 // For a given template and a given set of template-arguments,
3676 // - an explicit instantiation definition shall appear at most once
3677 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00003678 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00003679 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003680 Diag(PrevPointOfInstantiation,
3681 diag::note_previous_explicit_instantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00003682 SuppressNew = true;
3683 return false;
3684 }
3685 break;
3686 }
3687
3688 assert(false && "Missing specialization/instantiation case?");
3689
3690 return false;
3691}
3692
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003693/// \brief Perform semantic analysis for the given function template
3694/// specialization.
3695///
3696/// This routine performs all of the semantic analysis required for an
3697/// explicit function template specialization. On successful completion,
3698/// the function declaration \p FD will become a function template
3699/// specialization.
3700///
3701/// \param FD the function declaration, which will be updated to become a
3702/// function template specialization.
3703///
3704/// \param HasExplicitTemplateArgs whether any template arguments were
3705/// explicitly provided.
3706///
3707/// \param LAngleLoc the location of the left angle bracket ('<'), if
3708/// template arguments were explicitly provided.
3709///
3710/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3711/// if any.
3712///
3713/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3714/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3715/// true as in, e.g., \c void sort<>(char*, char*);
3716///
3717/// \param RAngleLoc the location of the right angle bracket ('>'), if
3718/// template arguments were explicitly provided.
3719///
3720/// \param PrevDecl the set of declarations that
3721bool
3722Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00003723 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00003724 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003725 // The set of function template specializations that could match this
3726 // explicit function template specialization.
3727 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3728 CandidateSet Candidates;
3729
3730 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall68263142009-11-18 22:49:29 +00003731 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3732 I != E; ++I) {
3733 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3734 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003735 // Only consider templates found within the same semantic lookup scope as
3736 // FD.
3737 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3738 continue;
3739
3740 // C++ [temp.expl.spec]p11:
3741 // A trailing template-argument can be left unspecified in the
3742 // template-id naming an explicit function template specialization
3743 // provided it can be deduced from the function argument type.
3744 // Perform template argument deduction to determine whether we may be
3745 // specializing this template.
3746 // FIXME: It is somewhat wasteful to build
3747 TemplateDeductionInfo Info(Context);
3748 FunctionDecl *Specialization = 0;
3749 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00003750 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003751 FD->getType(),
3752 Specialization,
3753 Info)) {
3754 // FIXME: Template argument deduction failed; record why it failed, so
3755 // that we can provide nifty diagnostics.
3756 (void)TDK;
3757 continue;
3758 }
3759
3760 // Record this candidate.
3761 Candidates.push_back(Specialization);
3762 }
3763 }
3764
Douglas Gregorc5df30f2009-09-26 03:41:46 +00003765 // Find the most specialized function template.
3766 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3767 Candidates.size(),
3768 TPOC_Other,
3769 FD->getLocation(),
3770 PartialDiagnostic(diag::err_function_template_spec_no_match)
3771 << FD->getDeclName(),
3772 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00003773 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorc5df30f2009-09-26 03:41:46 +00003774 PartialDiagnostic(diag::note_function_template_spec_matched));
3775 if (!Specialization)
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003776 return true;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003777
3778 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003779 // If so, we have run afoul of .
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003780
Douglas Gregord5cb8762009-10-07 00:13:32 +00003781 // Check the scope of this explicit specialization.
3782 if (CheckTemplateSpecializationScope(*this,
3783 Specialization->getPrimaryTemplate(),
3784 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003785 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003786 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003787
3788 // C++ [temp.expl.spec]p6:
3789 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00003790 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003791 // before the first use of that specialization that would cause an implicit
3792 // instantiation to take place, in every translation unit in which such a
3793 // use occurs; no diagnostic is required.
3794 FunctionTemplateSpecializationInfo *SpecInfo
3795 = Specialization->getTemplateSpecializationInfo();
3796 assert(SpecInfo && "Function template specialization info missing?");
3797 if (SpecInfo->getPointOfInstantiation().isValid()) {
3798 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3799 << FD;
3800 Diag(SpecInfo->getPointOfInstantiation(),
3801 diag::note_instantiation_required_here)
3802 << (Specialization->getTemplateSpecializationKind()
3803 != TSK_ImplicitInstantiation);
3804 return true;
3805 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003806
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003807 // Mark the prior declaration as an explicit specialization, so that later
3808 // clients know that this is an explicit specialization.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003809 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003810
3811 // Turn the given function declaration into a function template
3812 // specialization, with the template arguments from the previous
3813 // specialization.
3814 FD->setFunctionTemplateSpecialization(Context,
3815 Specialization->getPrimaryTemplate(),
3816 new (Context) TemplateArgumentList(
3817 *Specialization->getTemplateSpecializationArgs()),
3818 /*InsertPos=*/0,
3819 TSK_ExplicitSpecialization);
3820
3821 // The "previous declaration" for this function template specialization is
3822 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00003823 Previous.clear();
3824 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003825 return false;
3826}
3827
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003828/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003829/// specialization.
3830///
3831/// This routine performs all of the semantic analysis required for an
3832/// explicit member function specialization. On successful completion,
3833/// the function declaration \p FD will become a member function
3834/// specialization.
3835///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003836/// \param Member the member declaration, which will be updated to become a
3837/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003838///
John McCall68263142009-11-18 22:49:29 +00003839/// \param Previous the set of declarations, one of which may be specialized
3840/// by this function specialization; the set will be modified to contain the
3841/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003842bool
John McCall68263142009-11-18 22:49:29 +00003843Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003844 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3845
3846 // Try to find the member we are instantiating.
3847 NamedDecl *Instantiation = 0;
3848 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003849 MemberSpecializationInfo *MSInfo = 0;
3850
John McCall68263142009-11-18 22:49:29 +00003851 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003852 // Nowhere to look anyway.
3853 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00003854 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3855 I != E; ++I) {
3856 NamedDecl *D = (*I)->getUnderlyingDecl();
3857 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003858 if (Context.hasSameType(Function->getType(), Method->getType())) {
3859 Instantiation = Method;
3860 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003861 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003862 break;
3863 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003864 }
3865 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003866 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00003867 VarDecl *PrevVar;
3868 if (Previous.isSingleResult() &&
3869 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003870 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00003871 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003872 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003873 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003874 }
3875 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00003876 CXXRecordDecl *PrevRecord;
3877 if (Previous.isSingleResult() &&
3878 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
3879 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003880 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003881 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003882 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003883 }
3884
3885 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003886 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003887 // specializations are always out-of-line, the caller will complain about
3888 // this mismatch later.
3889 return false;
3890 }
3891
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003892 // Make sure that this is a specialization of a member.
3893 if (!InstantiatedFrom) {
3894 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3895 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003896 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3897 return true;
3898 }
3899
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003900 // C++ [temp.expl.spec]p6:
3901 // If a template, a member template or the member of a class template is
3902 // explicitly specialized then that spe- cialization shall be declared
3903 // before the first use of that specialization that would cause an implicit
3904 // instantiation to take place, in every translation unit in which such a
3905 // use occurs; no diagnostic is required.
3906 assert(MSInfo && "Member specialization info missing?");
3907 if (MSInfo->getPointOfInstantiation().isValid()) {
3908 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3909 << Member;
3910 Diag(MSInfo->getPointOfInstantiation(),
3911 diag::note_instantiation_required_here)
3912 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3913 return true;
3914 }
3915
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003916 // Check the scope of this explicit specialization.
3917 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003918 InstantiatedFrom,
3919 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003920 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003921 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00003922
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003923 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00003924 // the original declaration to note that it is an explicit specialization
3925 // (if it was previously an implicit instantiation). This latter step
3926 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003927 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00003928 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3929 if (InstantiationFunction->getTemplateSpecializationKind() ==
3930 TSK_ImplicitInstantiation) {
3931 InstantiationFunction->setTemplateSpecializationKind(
3932 TSK_ExplicitSpecialization);
3933 InstantiationFunction->setLocation(Member->getLocation());
3934 }
3935
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003936 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3937 cast<CXXMethodDecl>(InstantiatedFrom),
3938 TSK_ExplicitSpecialization);
3939 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00003940 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3941 if (InstantiationVar->getTemplateSpecializationKind() ==
3942 TSK_ImplicitInstantiation) {
3943 InstantiationVar->setTemplateSpecializationKind(
3944 TSK_ExplicitSpecialization);
3945 InstantiationVar->setLocation(Member->getLocation());
3946 }
3947
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003948 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3949 cast<VarDecl>(InstantiatedFrom),
3950 TSK_ExplicitSpecialization);
3951 } else {
3952 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00003953 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3954 if (InstantiationClass->getTemplateSpecializationKind() ==
3955 TSK_ImplicitInstantiation) {
3956 InstantiationClass->setTemplateSpecializationKind(
3957 TSK_ExplicitSpecialization);
3958 InstantiationClass->setLocation(Member->getLocation());
3959 }
3960
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003961 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00003962 cast<CXXRecordDecl>(InstantiatedFrom),
3963 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003964 }
3965
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003966 // Save the caller the trouble of having to figure out which declaration
3967 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00003968 Previous.clear();
3969 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003970 return false;
3971}
3972
Douglas Gregor558c0322009-10-14 23:41:34 +00003973/// \brief Check the scope of an explicit instantiation.
3974static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
3975 SourceLocation InstLoc,
3976 bool WasQualifiedName) {
3977 DeclContext *ExpectedContext
3978 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
3979 DeclContext *CurContext = S.CurContext->getLookupContext();
3980
3981 // C++0x [temp.explicit]p2:
3982 // An explicit instantiation shall appear in an enclosing namespace of its
3983 // template.
3984 //
3985 // This is DR275, which we do not retroactively apply to C++98/03.
3986 if (S.getLangOptions().CPlusPlus0x &&
3987 !CurContext->Encloses(ExpectedContext)) {
3988 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
3989 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
3990 << D << NS;
3991 else
3992 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
3993 << D;
3994 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3995 return;
3996 }
3997
3998 // C++0x [temp.explicit]p2:
3999 // If the name declared in the explicit instantiation is an unqualified
4000 // name, the explicit instantiation shall appear in the namespace where
4001 // its template is declared or, if that namespace is inline (7.3.1), any
4002 // namespace from its enclosing namespace set.
4003 if (WasQualifiedName)
4004 return;
4005
4006 if (CurContext->Equals(ExpectedContext))
4007 return;
4008
4009 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4010 << D << ExpectedContext;
4011 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4012}
4013
4014/// \brief Determine whether the given scope specifier has a template-id in it.
4015static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4016 if (!SS.isSet())
4017 return false;
4018
4019 // C++0x [temp.explicit]p2:
4020 // If the explicit instantiation is for a member function, a member class
4021 // or a static data member of a class template specialization, the name of
4022 // the class template specialization in the qualified-id for the member
4023 // name shall be a simple-template-id.
4024 //
4025 // C++98 has the same restriction, just worded differently.
4026 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4027 NNS; NNS = NNS->getPrefix())
4028 if (Type *T = NNS->getAsType())
4029 if (isa<TemplateSpecializationType>(T))
4030 return true;
4031
4032 return false;
4033}
4034
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004035// Explicit instantiation of a class template specialization
Douglas Gregor45f96552009-09-04 06:33:52 +00004036// FIXME: Implement extern template semantics
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004037Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004038Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004039 SourceLocation ExternLoc,
4040 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004041 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004042 SourceLocation KWLoc,
4043 const CXXScopeSpec &SS,
4044 TemplateTy TemplateD,
4045 SourceLocation TemplateNameLoc,
4046 SourceLocation LAngleLoc,
4047 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004048 SourceLocation RAngleLoc,
4049 AttributeList *Attr) {
4050 // Find the class template we're specializing
4051 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004052 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004053 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4054
4055 // Check that the specialization uses the same tag kind as the
4056 // original template.
4057 TagDecl::TagKind Kind;
4058 switch (TagSpec) {
4059 default: assert(0 && "Unknown tag type!");
4060 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4061 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4062 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4063 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004064 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004065 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004066 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004067 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004068 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00004069 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004070 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004071 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004072 diag::note_previous_use);
4073 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4074 }
4075
Douglas Gregor558c0322009-10-14 23:41:34 +00004076 // C++0x [temp.explicit]p2:
4077 // There are two forms of explicit instantiation: an explicit instantiation
4078 // definition and an explicit instantiation declaration. An explicit
4079 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00004080 TemplateSpecializationKind TSK
4081 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4082 : TSK_ExplicitInstantiationDeclaration;
4083
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004084 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004085 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004086 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004087
4088 // Check that the template argument list is well-formed for this
4089 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00004090 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4091 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00004092 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4093 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004094 return true;
4095
Mike Stump1eb44332009-09-09 15:08:12 +00004096 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004097 ClassTemplate->getTemplateParameters()->size()) &&
4098 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004099
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004100 // Find the class template specialization declaration that
4101 // corresponds to these arguments.
4102 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00004103 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00004104 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00004105 Converted.flatSize(),
4106 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004107 void *InsertPos = 0;
4108 ClassTemplateSpecializationDecl *PrevDecl
4109 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4110
Douglas Gregord5cb8762009-10-07 00:13:32 +00004111 // C++0x [temp.explicit]p2:
4112 // [...] An explicit instantiation shall appear in an enclosing
4113 // namespace of its template. [...]
4114 //
4115 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004116 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4117 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00004118
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004119 ClassTemplateSpecializationDecl *Specialization = 0;
4120
Douglas Gregord78f5982009-11-25 06:01:46 +00004121 bool ReusedDecl = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004122 if (PrevDecl) {
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004123 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004124 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004125 PrevDecl,
4126 PrevDecl->getSpecializationKind(),
4127 PrevDecl->getPointOfInstantiation(),
4128 SuppressNew))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004129 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004130
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004131 if (SuppressNew)
Douglas Gregor52604ab2009-09-11 21:19:12 +00004132 return DeclPtrTy::make(PrevDecl);
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004133
Douglas Gregor52604ab2009-09-11 21:19:12 +00004134 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4135 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4136 // Since the only prior class template specialization with these
4137 // arguments was referenced but not declared, reuse that
4138 // declaration node as our own, updating its source location to
4139 // reflect our new declaration.
4140 Specialization = PrevDecl;
4141 Specialization->setLocation(TemplateNameLoc);
4142 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00004143 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00004144 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004145 }
Douglas Gregor52604ab2009-09-11 21:19:12 +00004146
4147 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004148 // Create a new class template specialization declaration node for
4149 // this explicit specialization.
4150 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00004151 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004152 ClassTemplate->getDeclContext(),
4153 TemplateNameLoc,
4154 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00004155 Converted, PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004156
Douglas Gregor52604ab2009-09-11 21:19:12 +00004157 if (PrevDecl) {
4158 // Remove the previous declaration from the folding set, since we want
4159 // to introduce a new declaration.
4160 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4161 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4162 }
4163
4164 // Insert the new specialization.
4165 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004166 }
4167
4168 // Build the fully-sugared type for this explicit instantiation as
4169 // the user wrote in the explicit instantiation itself. This means
4170 // that we'll pretty-print the type retrieved from the
4171 // specialization's declaration the way that the user actually wrote
4172 // the explicit instantiation, rather than formatting the name based
4173 // on the "canonical" representation used to store the template
4174 // arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004175 QualType WrittenTy
John McCalld5532b62009-11-23 01:53:49 +00004176 = Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004177 Context.getTypeDeclType(Specialization));
4178 Specialization->setTypeAsWritten(WrittenTy);
4179 TemplateArgsIn.release();
4180
Douglas Gregord78f5982009-11-25 06:01:46 +00004181 if (!ReusedDecl) {
4182 // Add the explicit instantiation into its lexical context. However,
4183 // since explicit instantiations are never found by name lookup, we
4184 // just put it into the declaration context directly.
4185 Specialization->setLexicalDeclContext(CurContext);
4186 CurContext->addDecl(Specialization);
4187 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004188
4189 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004190 // A definition of a class template or class member template
4191 // shall be in scope at the point of the explicit instantiation of
4192 // the class template or class member template.
4193 //
4194 // This check comes when we actually try to perform the
4195 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004196 ClassTemplateSpecializationDecl *Def
4197 = cast_or_null<ClassTemplateSpecializationDecl>(
4198 Specialization->getDefinition(Context));
4199 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004200 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor0d035142009-10-27 18:42:08 +00004201
4202 // Instantiate the members of this class template specialization.
4203 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4204 Specialization->getDefinition(Context));
4205 if (Def)
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004206 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004207
4208 return DeclPtrTy::make(Specialization);
4209}
4210
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004211// Explicit instantiation of a member class of a class template.
4212Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004213Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004214 SourceLocation ExternLoc,
4215 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004216 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004217 SourceLocation KWLoc,
4218 const CXXScopeSpec &SS,
4219 IdentifierInfo *Name,
4220 SourceLocation NameLoc,
4221 AttributeList *Attr) {
4222
Douglas Gregor402abb52009-05-28 23:31:59 +00004223 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004224 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00004225 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004226 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00004227 MultiTemplateParamsArg(*this, 0, 0),
4228 Owned, IsDependent);
4229 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4230
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004231 if (!TagD)
4232 return true;
4233
4234 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4235 if (Tag->isEnum()) {
4236 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4237 << Context.getTypeDeclType(Tag);
4238 return true;
4239 }
4240
Douglas Gregord0c87372009-05-27 17:30:49 +00004241 if (Tag->isInvalidDecl())
4242 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004243
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004244 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4245 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4246 if (!Pattern) {
4247 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4248 << Context.getTypeDeclType(Record);
4249 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4250 return true;
4251 }
4252
Douglas Gregor558c0322009-10-14 23:41:34 +00004253 // C++0x [temp.explicit]p2:
4254 // If the explicit instantiation is for a class or member class, the
4255 // elaborated-type-specifier in the declaration shall include a
4256 // simple-template-id.
4257 //
4258 // C++98 has the same restriction, just worded differently.
4259 if (!ScopeSpecifierHasTemplateId(SS))
4260 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4261 << Record << SS.getRange();
4262
4263 // C++0x [temp.explicit]p2:
4264 // There are two forms of explicit instantiation: an explicit instantiation
4265 // definition and an explicit instantiation declaration. An explicit
4266 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004267 TemplateSpecializationKind TSK
4268 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4269 : TSK_ExplicitInstantiationDeclaration;
4270
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004271 // C++0x [temp.explicit]p2:
4272 // [...] An explicit instantiation shall appear in an enclosing
4273 // namespace of its template. [...]
4274 //
4275 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004276 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004277
4278 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004279 CXXRecordDecl *PrevDecl
4280 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4281 if (!PrevDecl && Record->getDefinition(Context))
4282 PrevDecl = Record;
4283 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004284 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4285 bool SuppressNew = false;
4286 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004287 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004288 PrevDecl,
4289 MSInfo->getTemplateSpecializationKind(),
4290 MSInfo->getPointOfInstantiation(),
4291 SuppressNew))
4292 return true;
4293 if (SuppressNew)
4294 return TagD;
4295 }
4296
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004297 CXXRecordDecl *RecordDef
4298 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4299 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004300 // C++ [temp.explicit]p3:
4301 // A definition of a member class of a class template shall be in scope
4302 // at the point of an explicit instantiation of the member class.
4303 CXXRecordDecl *Def
4304 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4305 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004306 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4307 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004308 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4309 << Pattern;
4310 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004311 } else {
4312 if (InstantiateClass(NameLoc, Record, Def,
4313 getTemplateInstantiationArgs(Record),
4314 TSK))
4315 return true;
4316
4317 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4318 if (!RecordDef)
4319 return true;
4320 }
4321 }
4322
4323 // Instantiate all of the members of the class.
4324 InstantiateClassMembers(NameLoc, RecordDef,
4325 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004326
Mike Stump390b4cc2009-05-16 07:39:55 +00004327 // FIXME: We don't have any representation for explicit instantiations of
4328 // member classes. Such a representation is not needed for compilation, but it
4329 // should be available for clients that want to see all of the declarations in
4330 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004331 return TagD;
4332}
4333
Douglas Gregord5a423b2009-09-25 18:43:00 +00004334Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4335 SourceLocation ExternLoc,
4336 SourceLocation TemplateLoc,
4337 Declarator &D) {
4338 // Explicit instantiations always require a name.
4339 DeclarationName Name = GetNameForDeclarator(D);
4340 if (!Name) {
4341 if (!D.isInvalidType())
4342 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4343 diag::err_explicit_instantiation_requires_name)
4344 << D.getDeclSpec().getSourceRange()
4345 << D.getSourceRange();
4346
4347 return true;
4348 }
4349
4350 // The scope passed in may not be a decl scope. Zip up the scope tree until
4351 // we find one that is.
4352 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4353 (S->getFlags() & Scope::TemplateParamScope) != 0)
4354 S = S->getParent();
4355
4356 // Determine the type of the declaration.
4357 QualType R = GetTypeForDeclarator(D, S, 0);
4358 if (R.isNull())
4359 return true;
4360
4361 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4362 // Cannot explicitly instantiate a typedef.
4363 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4364 << Name;
4365 return true;
4366 }
4367
Douglas Gregor663b5a02009-10-14 20:14:33 +00004368 // C++0x [temp.explicit]p1:
4369 // [...] An explicit instantiation of a function template shall not use the
4370 // inline or constexpr specifiers.
4371 // Presumably, this also applies to member functions of class templates as
4372 // well.
4373 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4374 Diag(D.getDeclSpec().getInlineSpecLoc(),
4375 diag::err_explicit_instantiation_inline)
Chris Lattner29d9c1a2009-12-06 17:36:05 +00004376 <<CodeModificationHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00004377
4378 // FIXME: check for constexpr specifier.
4379
Douglas Gregor558c0322009-10-14 23:41:34 +00004380 // C++0x [temp.explicit]p2:
4381 // There are two forms of explicit instantiation: an explicit instantiation
4382 // definition and an explicit instantiation declaration. An explicit
4383 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00004384 TemplateSpecializationKind TSK
4385 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4386 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00004387
John McCalla24dc2e2009-11-17 02:14:36 +00004388 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4389 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004390
4391 if (!R->isFunctionType()) {
4392 // C++ [temp.explicit]p1:
4393 // A [...] static data member of a class template can be explicitly
4394 // instantiated from the member definition associated with its class
4395 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00004396 if (Previous.isAmbiguous())
4397 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004398
John McCall1bcee0a2009-12-02 08:25:40 +00004399 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004400 if (!Prev || !Prev->isStaticDataMember()) {
4401 // We expect to see a data data member here.
4402 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4403 << Name;
4404 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4405 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00004406 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004407 return true;
4408 }
4409
4410 if (!Prev->getInstantiatedFromStaticDataMember()) {
4411 // FIXME: Check for explicit specialization?
4412 Diag(D.getIdentifierLoc(),
4413 diag::err_explicit_instantiation_data_member_not_instantiated)
4414 << Prev;
4415 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4416 // FIXME: Can we provide a note showing where this was declared?
4417 return true;
4418 }
4419
Douglas Gregor558c0322009-10-14 23:41:34 +00004420 // C++0x [temp.explicit]p2:
4421 // If the explicit instantiation is for a member function, a member class
4422 // or a static data member of a class template specialization, the name of
4423 // the class template specialization in the qualified-id for the member
4424 // name shall be a simple-template-id.
4425 //
4426 // C++98 has the same restriction, just worded differently.
4427 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4428 Diag(D.getIdentifierLoc(),
4429 diag::err_explicit_instantiation_without_qualified_id)
4430 << Prev << D.getCXXScopeSpec().getRange();
4431
4432 // Check the scope of this explicit instantiation.
4433 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4434
Douglas Gregor454885e2009-10-15 15:54:05 +00004435 // Verify that it is okay to explicitly instantiate here.
4436 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4437 assert(MSInfo && "Missing static data member specialization info?");
4438 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004439 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00004440 MSInfo->getTemplateSpecializationKind(),
4441 MSInfo->getPointOfInstantiation(),
4442 SuppressNew))
4443 return true;
4444 if (SuppressNew)
4445 return DeclPtrTy();
4446
Douglas Gregord5a423b2009-09-25 18:43:00 +00004447 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004448 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004449 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004450 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4451 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004452
4453 // FIXME: Create an ExplicitInstantiation node?
4454 return DeclPtrTy();
4455 }
4456
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004457 // If the declarator is a template-id, translate the parser's template
4458 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00004459 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00004460 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004461 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4462 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00004463 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4464 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00004465 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4466 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00004467 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00004468 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00004469 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00004470 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00004471 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004472
Douglas Gregord5a423b2009-09-25 18:43:00 +00004473 // C++ [temp.explicit]p1:
4474 // A [...] function [...] can be explicitly instantiated from its template.
4475 // A member function [...] of a class template can be explicitly
4476 // instantiated from the member definition associated with its class
4477 // template.
Douglas Gregord5a423b2009-09-25 18:43:00 +00004478 llvm::SmallVector<FunctionDecl *, 8> Matches;
4479 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4480 P != PEnd; ++P) {
4481 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00004482 if (!HasExplicitTemplateArgs) {
4483 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4484 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4485 Matches.clear();
4486 Matches.push_back(Method);
4487 break;
4488 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00004489 }
4490 }
4491
4492 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4493 if (!FunTmpl)
4494 continue;
4495
4496 TemplateDeductionInfo Info(Context);
4497 FunctionDecl *Specialization = 0;
4498 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004499 = DeduceTemplateArguments(FunTmpl,
4500 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00004501 R, Specialization, Info)) {
4502 // FIXME: Keep track of almost-matches?
4503 (void)TDK;
4504 continue;
4505 }
4506
4507 Matches.push_back(Specialization);
4508 }
4509
4510 // Find the most specialized function template specialization.
4511 FunctionDecl *Specialization
4512 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4513 D.getIdentifierLoc(),
4514 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4515 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4516 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4517
4518 if (!Specialization)
4519 return true;
4520
Douglas Gregor0a897e32009-10-15 17:21:20 +00004521 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00004522 Diag(D.getIdentifierLoc(),
4523 diag::err_explicit_instantiation_member_function_not_instantiated)
4524 << Specialization
4525 << (Specialization->getTemplateSpecializationKind() ==
4526 TSK_ExplicitSpecialization);
4527 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4528 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00004529 }
Douglas Gregor558c0322009-10-14 23:41:34 +00004530
Douglas Gregor0a897e32009-10-15 17:21:20 +00004531 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00004532 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4533 PrevDecl = Specialization;
4534
Douglas Gregor0a897e32009-10-15 17:21:20 +00004535 if (PrevDecl) {
4536 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004537 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00004538 PrevDecl,
4539 PrevDecl->getTemplateSpecializationKind(),
4540 PrevDecl->getPointOfInstantiation(),
4541 SuppressNew))
4542 return true;
4543
4544 // FIXME: We may still want to build some representation of this
4545 // explicit specialization.
4546 if (SuppressNew)
4547 return DeclPtrTy();
4548 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00004549
4550 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00004551
4552 if (TSK == TSK_ExplicitInstantiationDefinition)
4553 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4554 false, /*DefinitionRequired=*/true);
Douglas Gregor0a897e32009-10-15 17:21:20 +00004555
Douglas Gregor558c0322009-10-14 23:41:34 +00004556 // C++0x [temp.explicit]p2:
4557 // If the explicit instantiation is for a member function, a member class
4558 // or a static data member of a class template specialization, the name of
4559 // the class template specialization in the qualified-id for the member
4560 // name shall be a simple-template-id.
4561 //
4562 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004563 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004564 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00004565 D.getCXXScopeSpec().isSet() &&
4566 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4567 Diag(D.getIdentifierLoc(),
4568 diag::err_explicit_instantiation_without_qualified_id)
4569 << Specialization << D.getCXXScopeSpec().getRange();
4570
4571 CheckExplicitInstantiationScope(*this,
4572 FunTmpl? (NamedDecl *)FunTmpl
4573 : Specialization->getInstantiatedFromMemberFunction(),
4574 D.getIdentifierLoc(),
4575 D.getCXXScopeSpec().isSet());
4576
Douglas Gregord5a423b2009-09-25 18:43:00 +00004577 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4578 return DeclPtrTy();
4579}
4580
Douglas Gregord57959a2009-03-27 23:10:48 +00004581Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00004582Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4583 const CXXScopeSpec &SS, IdentifierInfo *Name,
4584 SourceLocation TagLoc, SourceLocation NameLoc) {
4585 // This has to hold, because SS is expected to be defined.
4586 assert(Name && "Expected a name in a dependent tag");
4587
4588 NestedNameSpecifier *NNS
4589 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4590 if (!NNS)
4591 return true;
4592
4593 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4594 if (T.isNull())
4595 return true;
4596
4597 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4598 QualType ElabType = Context.getElaboratedType(T, TagKind);
4599
4600 return ElabType.getAsOpaquePtr();
4601}
4602
4603Sema::TypeResult
Douglas Gregord57959a2009-03-27 23:10:48 +00004604Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4605 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00004606 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00004607 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4608 if (!NNS)
4609 return true;
4610
4611 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00004612 if (T.isNull())
4613 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00004614 return T.getAsOpaquePtr();
4615}
4616
Douglas Gregor17343172009-04-01 00:28:59 +00004617Sema::TypeResult
4618Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4619 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00004620 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004621 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00004622 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +00004623 const TemplateSpecializationType *TemplateId
John McCall183700f2009-09-21 23:43:11 +00004624 = T->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00004625 assert(TemplateId && "Expected a template specialization type");
4626
Douglas Gregor6946baf2009-09-02 13:05:45 +00004627 if (computeDeclContext(SS, false)) {
4628 // If we can compute a declaration context, then the "typename"
4629 // keyword was superfluous. Just build a QualifiedNameType to keep
4630 // track of the nested-name-specifier.
Mike Stump1eb44332009-09-09 15:08:12 +00004631
Douglas Gregor6946baf2009-09-02 13:05:45 +00004632 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4633 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4634 }
Mike Stump1eb44332009-09-09 15:08:12 +00004635
Douglas Gregor6946baf2009-09-02 13:05:45 +00004636 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00004637}
4638
Douglas Gregord57959a2009-03-27 23:10:48 +00004639/// \brief Build the type that describes a C++ typename specifier,
4640/// e.g., "typename T::type".
4641QualType
4642Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4643 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00004644 CXXRecordDecl *CurrentInstantiation = 0;
4645 if (NNS->isDependent()) {
4646 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00004647
Douglas Gregor42af25f2009-05-11 19:58:34 +00004648 // If the nested-name-specifier does not refer to the current
4649 // instantiation, then build a typename type.
4650 if (!CurrentInstantiation)
4651 return Context.getTypenameType(NNS, &II);
Mike Stump1eb44332009-09-09 15:08:12 +00004652
Douglas Gregorde18d122009-09-02 13:12:51 +00004653 // The nested-name-specifier refers to the current instantiation, so the
4654 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump1eb44332009-09-09 15:08:12 +00004655 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorde18d122009-09-02 13:12:51 +00004656 // extraneous "typename" keywords, and we retroactively apply this DR to
4657 // C++03 code.
Douglas Gregor42af25f2009-05-11 19:58:34 +00004658 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004659
Douglas Gregor42af25f2009-05-11 19:58:34 +00004660 DeclContext *Ctx = 0;
4661
4662 if (CurrentInstantiation)
4663 Ctx = CurrentInstantiation;
4664 else {
4665 CXXScopeSpec SS;
4666 SS.setScopeRep(NNS);
4667 SS.setRange(Range);
4668 if (RequireCompleteDeclContext(SS))
4669 return QualType();
4670
4671 Ctx = computeDeclContext(SS);
4672 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004673 assert(Ctx && "No declaration context?");
4674
4675 DeclarationName Name(&II);
John McCalla24dc2e2009-11-17 02:14:36 +00004676 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4677 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00004678 unsigned DiagID = 0;
4679 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00004680 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00004681 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00004682 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00004683 break;
4684
4685 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +00004686 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregord57959a2009-03-27 23:10:48 +00004687 // We found a type. Build a QualifiedNameType, since the
4688 // typename-specifier was just sugar. FIXME: Tell
4689 // QualifiedNameType that it has a "typename" prefix.
4690 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4691 }
4692
4693 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00004694 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00004695 break;
4696
John McCall7ba107a2009-11-18 02:36:19 +00004697 case LookupResult::FoundUnresolvedValue:
4698 llvm::llvm_unreachable("unresolved using decl in non-dependent context");
4699 return QualType();
4700
Douglas Gregord57959a2009-03-27 23:10:48 +00004701 case LookupResult::FoundOverloaded:
4702 DiagID = diag::err_typename_nested_not_type;
4703 Referenced = *Result.begin();
4704 break;
4705
John McCall6e247262009-10-10 05:48:19 +00004706 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00004707 return QualType();
4708 }
4709
4710 // If we get here, it's because name lookup did not find a
4711 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor3f093272009-10-13 21:16:44 +00004712 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00004713 if (Referenced)
4714 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4715 << Name;
4716 return QualType();
4717}
Douglas Gregor4a959d82009-08-06 16:20:37 +00004718
4719namespace {
4720 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00004721 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00004722 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00004723 SourceLocation Loc;
4724 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00004725
Douglas Gregor4a959d82009-08-06 16:20:37 +00004726 public:
Mike Stump1eb44332009-09-09 15:08:12 +00004727 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00004728 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00004729 DeclarationName Entity)
4730 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00004731 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00004732
4733 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00004734 /// transformed.
4735 ///
4736 /// For the purposes of type reconstruction, a type has already been
4737 /// transformed if it is NULL or if it is not dependent.
4738 bool AlreadyTransformed(QualType T) {
4739 return T.isNull() || !T->isDependentType();
4740 }
Mike Stump1eb44332009-09-09 15:08:12 +00004741
4742 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00004743 /// rebuilt.
4744 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00004745
Douglas Gregor4a959d82009-08-06 16:20:37 +00004746 /// \brief Returns the name of the entity whose type is being rebuilt.
4747 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00004748
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004749 /// \brief Sets the "base" location and entity when that
4750 /// information is known based on another transformation.
4751 void setBase(SourceLocation Loc, DeclarationName Entity) {
4752 this->Loc = Loc;
4753 this->Entity = Entity;
4754 }
4755
Douglas Gregor4a959d82009-08-06 16:20:37 +00004756 /// \brief Transforms an expression by returning the expression itself
4757 /// (an identity function).
4758 ///
4759 /// FIXME: This is completely unsafe; we will need to actually clone the
4760 /// expressions.
4761 Sema::OwningExprResult TransformExpr(Expr *E) {
4762 return getSema().Owned(E);
4763 }
Mike Stump1eb44332009-09-09 15:08:12 +00004764
Douglas Gregor4a959d82009-08-06 16:20:37 +00004765 /// \brief Transforms a typename type by determining whether the type now
4766 /// refers to a member of the current instantiation, and then
4767 /// type-checking and building a QualifiedNameType (when possible).
John McCalla2becad2009-10-21 00:40:46 +00004768 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor4a959d82009-08-06 16:20:37 +00004769 };
4770}
4771
Mike Stump1eb44332009-09-09 15:08:12 +00004772QualType
John McCalla2becad2009-10-21 00:40:46 +00004773CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4774 TypenameTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00004775 TypenameType *T = TL.getTypePtr();
John McCalla2becad2009-10-21 00:40:46 +00004776
Douglas Gregor4a959d82009-08-06 16:20:37 +00004777 NestedNameSpecifier *NNS
4778 = TransformNestedNameSpecifier(T->getQualifier(),
4779 /*FIXME:*/SourceRange(getBaseLocation()));
4780 if (!NNS)
4781 return QualType();
4782
4783 // If the nested-name-specifier did not change, and we cannot compute the
4784 // context corresponding to the nested-name-specifier, then this
4785 // typename type will not change; exit early.
4786 CXXScopeSpec SS;
4787 SS.setRange(SourceRange(getBaseLocation()));
4788 SS.setScopeRep(NNS);
John McCall833ca992009-10-29 08:12:44 +00004789
4790 QualType Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004791 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall833ca992009-10-29 08:12:44 +00004792 Result = QualType(T, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004793
4794 // Rebuild the typename type, which will probably turn into a
Douglas Gregor4a959d82009-08-06 16:20:37 +00004795 // QualifiedNameType.
John McCall833ca992009-10-29 08:12:44 +00004796 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004797 QualType NewTemplateId
Douglas Gregor4a959d82009-08-06 16:20:37 +00004798 = TransformType(QualType(TemplateId, 0));
4799 if (NewTemplateId.isNull())
4800 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004801
Douglas Gregor4a959d82009-08-06 16:20:37 +00004802 if (NNS == T->getQualifier() &&
4803 NewTemplateId == QualType(TemplateId, 0))
John McCall833ca992009-10-29 08:12:44 +00004804 Result = QualType(T, 0);
4805 else
4806 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4807 } else
4808 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4809 SourceRange(TL.getNameLoc()));
Mike Stump1eb44332009-09-09 15:08:12 +00004810
John McCall833ca992009-10-29 08:12:44 +00004811 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4812 NewTL.setNameLoc(TL.getNameLoc());
4813 return Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004814}
4815
4816/// \brief Rebuilds a type within the context of the current instantiation.
4817///
Mike Stump1eb44332009-09-09 15:08:12 +00004818/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00004819/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00004820/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00004821/// partial specialization thereof). This routine will rebuild that type now
4822/// that we have entered the declarator's scope, which may produce different
4823/// canonical types, e.g.,
4824///
4825/// \code
4826/// template<typename T>
4827/// struct X {
4828/// typedef T* pointer;
4829/// pointer data();
4830/// };
4831///
4832/// template<typename T>
4833/// typename X<T>::pointer X<T>::data() { ... }
4834/// \endcode
4835///
4836/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4837/// since we do not know that we can look into X<T> when we parsed the type.
4838/// This function will rebuild the type, performing the lookup of "pointer"
4839/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4840/// as the canonical type of T*, allowing the return types of the out-of-line
4841/// definition and the declaration to match.
4842QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4843 DeclarationName Name) {
4844 if (T.isNull() || !T->isDependentType())
4845 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00004846
Douglas Gregor4a959d82009-08-06 16:20:37 +00004847 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4848 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00004849}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004850
4851/// \brief Produces a formatted string that describes the binding of
4852/// template parameters to template arguments.
4853std::string
4854Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4855 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004856 // FIXME: For variadic templates, we'll need to get the structured list.
4857 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4858 Args.flat_size());
4859}
4860
4861std::string
4862Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4863 const TemplateArgument *Args,
4864 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004865 std::string Result;
4866
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004867 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004868 return Result;
4869
4870 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004871 if (I >= NumArgs)
4872 break;
4873
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004874 if (I == 0)
4875 Result += "[with ";
4876 else
4877 Result += ", ";
4878
4879 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4880 Result += Id->getName();
4881 } else {
4882 Result += '$';
4883 Result += llvm::utostr(I);
4884 }
4885
4886 Result += " = ";
4887
4888 switch (Args[I].getKind()) {
4889 case TemplateArgument::Null:
4890 Result += "<no value>";
4891 break;
4892
4893 case TemplateArgument::Type: {
4894 std::string TypeStr;
4895 Args[I].getAsType().getAsStringInternal(TypeStr,
4896 Context.PrintingPolicy);
4897 Result += TypeStr;
4898 break;
4899 }
4900
4901 case TemplateArgument::Declaration: {
4902 bool Unnamed = true;
4903 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4904 if (ND->getDeclName()) {
4905 Unnamed = false;
4906 Result += ND->getNameAsString();
4907 }
4908 }
4909
4910 if (Unnamed) {
4911 Result += "<anonymous>";
4912 }
4913 break;
4914 }
4915
Douglas Gregor788cd062009-11-11 01:00:40 +00004916 case TemplateArgument::Template: {
4917 std::string Str;
4918 llvm::raw_string_ostream OS(Str);
4919 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
4920 Result += OS.str();
4921 break;
4922 }
4923
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004924 case TemplateArgument::Integral: {
4925 Result += Args[I].getAsIntegral()->toString(10);
4926 break;
4927 }
4928
4929 case TemplateArgument::Expression: {
4930 assert(false && "No expressions in deduced template arguments!");
4931 Result += "<expression>";
4932 break;
4933 }
4934
4935 case TemplateArgument::Pack:
4936 // FIXME: Format template argument packs
4937 Result += "<template argument pack>";
4938 break;
4939 }
4940 }
4941
4942 Result += ']';
4943 return Result;
4944}