blob: 4507e648684b99ed291c02bf9cb27773c493d2ce [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000011
12#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
John McCall92b7f702010-03-11 07:50:04 +000018#include "clang/AST/DeclFriend.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000020#include "clang/Parse/DeclSpec.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000021#include "clang/Parse/Template.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregor2dd078a2009-09-02 22:59:36 +000027/// \brief Determine whether the declaration found is acceptable as the name
28/// of a template and, if so, return that template declaration. Otherwise,
29/// returns NULL.
30static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
31 if (!D)
32 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +000033
Douglas Gregor2dd078a2009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
35 return D;
Mike Stump1eb44332009-09-09 15:08:12 +000036
Douglas Gregor2dd078a2009-09-02 22:59:36 +000037 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
38 // C++ [temp.local]p1:
39 // Like normal (non-template) classes, class templates have an
40 // injected-class-name (Clause 9). The injected-class-name
41 // can be used with or without a template-argument-list. When
42 // it is used without a template-argument-list, it is
43 // equivalent to the injected-class-name followed by the
44 // template-parameters of the class template enclosed in
45 // <>. When it is used with a template-argument-list, it
46 // refers to the specified class template specialization,
47 // which could be the current specialization or another
48 // specialization.
49 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000051 if (Record->getDescribedClassTemplate())
52 return Record->getDescribedClassTemplate();
53
54 if (ClassTemplateSpecializationDecl *Spec
55 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
56 return Spec->getSpecializedTemplate();
57 }
Mike Stump1eb44332009-09-09 15:08:12 +000058
Douglas Gregor2dd078a2009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump1eb44332009-09-09 15:08:12 +000061
Douglas Gregor2dd078a2009-09-02 22:59:36 +000062 return 0;
63}
64
John McCallf7a1a742009-11-24 19:00:30 +000065static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
66 LookupResult::Filter filter = R.makeFilter();
67 while (filter.hasNext()) {
68 NamedDecl *Orig = filter.next();
69 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
70 if (!Repl)
71 filter.erase();
72 else if (Repl != Orig)
73 filter.replace(Repl);
74 }
75 filter.done();
76}
77
Douglas Gregor2dd078a2009-09-02 22:59:36 +000078TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor014e88d2009-11-03 23:16:33 +000079 const CXXScopeSpec &SS,
80 UnqualifiedId &Name,
Douglas Gregor2dd078a2009-09-02 22:59:36 +000081 TypeTy *ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +000082 bool EnteringContext,
Douglas Gregor2dd078a2009-09-02 22:59:36 +000083 TemplateTy &TemplateResult) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +000084 assert(getLangOptions().CPlusPlus && "No template names in C!");
85
Douglas Gregor014e88d2009-11-03 23:16:33 +000086 DeclarationName TName;
87
88 switch (Name.getKind()) {
89 case UnqualifiedId::IK_Identifier:
90 TName = DeclarationName(Name.Identifier);
91 break;
92
93 case UnqualifiedId::IK_OperatorFunctionId:
94 TName = Context.DeclarationNames.getCXXOperatorName(
95 Name.OperatorFunctionId.Operator);
96 break;
97
Sean Hunte6252d12009-11-28 08:58:14 +000098 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +000099 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
100 break;
Sean Hunte6252d12009-11-28 08:58:14 +0000101
Douglas Gregor014e88d2009-11-03 23:16:33 +0000102 default:
103 return TNK_Non_template;
104 }
Mike Stump1eb44332009-09-09 15:08:12 +0000105
John McCallf7a1a742009-11-24 19:00:30 +0000106 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Douglas Gregorbfea2392009-12-31 08:11:17 +0000108 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
109 LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +0000110 R.suppressDiagnostics();
111 LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
112 if (R.empty())
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000113 return TNK_Non_template;
114
John McCall0bd6feb2009-12-02 08:04:21 +0000115 TemplateName Template;
116 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000117
John McCall0bd6feb2009-12-02 08:04:21 +0000118 unsigned ResultCount = R.end() - R.begin();
119 if (ResultCount > 1) {
120 // We assume that we'll preserve the qualifier from a function
121 // template name in other ways.
122 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
123 TemplateKind = TNK_Function_template;
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000124 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000125 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
126
127 if (SS.isSet() && !SS.isInvalid()) {
128 NestedNameSpecifier *Qualifier
129 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
130 Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
131 } else {
132 Template = TemplateName(TD);
133 }
134
135 if (isa<FunctionTemplateDecl>(TD))
136 TemplateKind = TNK_Function_template;
137 else {
138 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
139 TemplateKind = TNK_Type_template;
140 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000141 }
Mike Stump1eb44332009-09-09 15:08:12 +0000142
John McCall0bd6feb2009-12-02 08:04:21 +0000143 TemplateResult = TemplateTy::make(Template);
144 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000145}
146
Douglas Gregor84d0a192010-01-12 21:28:44 +0000147bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
148 SourceLocation IILoc,
149 Scope *S,
150 const CXXScopeSpec *SS,
151 TemplateTy &SuggestedTemplate,
152 TemplateNameKind &SuggestedKind) {
153 // We can't recover unless there's a dependent scope specifier preceding the
154 // template name.
155 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
156 computeDeclContext(*SS))
157 return false;
158
159 // The code is missing a 'template' keyword prior to the dependent template
160 // name.
161 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
162 Diag(IILoc, diag::err_template_kw_missing)
163 << Qualifier << II.getName()
164 << CodeModificationHint::CreateInsertion(IILoc, "template ");
165 SuggestedTemplate
166 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
167 SuggestedKind = TNK_Dependent_template_name;
168 return true;
169}
170
John McCallf7a1a742009-11-24 19:00:30 +0000171void Sema::LookupTemplateName(LookupResult &Found,
172 Scope *S, const CXXScopeSpec &SS,
173 QualType ObjectType,
174 bool EnteringContext) {
175 // Determine where to perform name lookup
176 DeclContext *LookupCtx = 0;
177 bool isDependent = false;
178 if (!ObjectType.isNull()) {
179 // This nested-name-specifier occurs in a member access expression, e.g.,
180 // x->B::f, and we are looking into the type of the object.
181 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
182 LookupCtx = computeDeclContext(ObjectType);
183 isDependent = ObjectType->isDependentType();
184 assert((isDependent || !ObjectType->isIncompleteType()) &&
185 "Caller should have completed object type");
186 } else if (SS.isSet()) {
187 // This nested-name-specifier occurs after another nested-name-specifier,
188 // so long into the context associated with the prior nested-name-specifier.
189 LookupCtx = computeDeclContext(SS, EnteringContext);
190 isDependent = isDependentScopeSpecifier(SS);
191
192 // The declaration context must be complete.
193 if (LookupCtx && RequireCompleteDeclContext(SS))
194 return;
195 }
196
197 bool ObjectTypeSearchedInScope = false;
198 if (LookupCtx) {
199 // Perform "qualified" name lookup into the declaration context we
200 // computed, which is either the type of the base of a member access
201 // expression or the declaration context associated with a prior
202 // nested-name-specifier.
203 LookupQualifiedName(Found, LookupCtx);
204
205 if (!ObjectType.isNull() && Found.empty()) {
206 // C++ [basic.lookup.classref]p1:
207 // In a class member access expression (5.2.5), if the . or -> token is
208 // immediately followed by an identifier followed by a <, the
209 // identifier must be looked up to determine whether the < is the
210 // beginning of a template argument list (14.2) or a less-than operator.
211 // The identifier is first looked up in the class of the object
212 // expression. If the identifier is not found, it is then looked up in
213 // the context of the entire postfix-expression and shall name a class
214 // or function template.
215 //
216 // FIXME: When we're instantiating a template, do we actually have to
217 // look in the scope of the template? Seems fishy...
218 if (S) LookupName(Found, S);
219 ObjectTypeSearchedInScope = true;
220 }
221 } else if (isDependent) {
Douglas Gregor2e933882010-01-12 17:06:20 +0000222 // We cannot look into a dependent object type or nested nme
223 // specifier.
John McCallf7a1a742009-11-24 19:00:30 +0000224 return;
225 } else {
226 // Perform unqualified name lookup in the current scope.
227 LookupName(Found, S);
228 }
229
230 // FIXME: Cope with ambiguous name-lookup results.
231 assert(!Found.isAmbiguous() &&
232 "Cannot handle template name-lookup ambiguities");
233
Douglas Gregor2e933882010-01-12 17:06:20 +0000234 if (Found.empty() && !isDependent) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000235 // If we did not find any names, attempt to correct any typos.
236 DeclarationName Name = Found.getLookupName();
237 if (CorrectTypo(Found, S, &SS, LookupCtx)) {
238 FilterAcceptableTemplateNames(Context, Found);
239 if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
240 if (LookupCtx)
241 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
242 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
243 << CodeModificationHint::CreateReplacement(Found.getNameLoc(),
244 Found.getLookupName().getAsString());
245 else
246 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
247 << Name << Found.getLookupName()
248 << CodeModificationHint::CreateReplacement(Found.getNameLoc(),
249 Found.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000250 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
251 Diag(Template->getLocation(), diag::note_previous_decl)
252 << Template->getDeclName();
Douglas Gregorbfea2392009-12-31 08:11:17 +0000253 } else
254 Found.clear();
255 } else {
256 Found.clear();
257 }
258 }
259
John McCallf7a1a742009-11-24 19:00:30 +0000260 FilterAcceptableTemplateNames(Context, Found);
261 if (Found.empty())
262 return;
263
264 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
265 // C++ [basic.lookup.classref]p1:
266 // [...] If the lookup in the class of the object expression finds a
267 // template, the name is also looked up in the context of the entire
268 // postfix-expression and [...]
269 //
270 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
271 LookupOrdinaryName);
272 LookupName(FoundOuter, S);
273 FilterAcceptableTemplateNames(Context, FoundOuter);
274 // FIXME: Handle ambiguities in this lookup better
275
276 if (FoundOuter.empty()) {
277 // - if the name is not found, the name found in the class of the
278 // object expression is used, otherwise
279 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
280 // - if the name is found in the context of the entire
281 // postfix-expression and does not name a class template, the name
282 // found in the class of the object expression is used, otherwise
283 } else {
284 // - if the name found is a class template, it must refer to the same
285 // entity as the one found in the class of the object expression,
286 // otherwise the program is ill-formed.
287 if (!Found.isSingleResult() ||
288 Found.getFoundDecl()->getCanonicalDecl()
289 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
290 Diag(Found.getNameLoc(),
291 diag::err_nested_name_member_ref_lookup_ambiguous)
292 << Found.getLookupName();
293 Diag(Found.getRepresentativeDecl()->getLocation(),
294 diag::note_ambig_member_ref_object_type)
295 << ObjectType;
296 Diag(FoundOuter.getFoundDecl()->getLocation(),
297 diag::note_ambig_member_ref_scope);
298
299 // Recover by taking the template that we found in the object
300 // expression's type.
301 }
302 }
303 }
304}
305
John McCall2f841ba2009-12-02 03:53:29 +0000306/// ActOnDependentIdExpression - Handle a dependent id-expression that
307/// was just parsed. This is only possible with an explicit scope
308/// specifier naming a dependent type.
John McCallf7a1a742009-11-24 19:00:30 +0000309Sema::OwningExprResult
310Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
311 DeclarationName Name,
312 SourceLocation NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +0000313 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000314 const TemplateArgumentListInfo *TemplateArgs) {
315 NestedNameSpecifier *Qualifier
316 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
317
John McCall2f841ba2009-12-02 03:53:29 +0000318 if (!isAddressOfOperand &&
319 isa<CXXMethodDecl>(CurContext) &&
320 cast<CXXMethodDecl>(CurContext)->isInstance()) {
321 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
322
John McCallf7a1a742009-11-24 19:00:30 +0000323 // Since the 'this' expression is synthesized, we don't need to
324 // perform the double-lookup check.
325 NamedDecl *FirstQualifierInScope = 0;
326
John McCallaa81e162009-12-01 22:10:20 +0000327 return Owned(CXXDependentScopeMemberExpr::Create(Context,
328 /*This*/ 0, ThisType,
329 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000330 /*Op*/ SourceLocation(),
331 Qualifier, SS.getRange(),
332 FirstQualifierInScope,
333 Name, NameLoc,
334 TemplateArgs));
335 }
336
337 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
338}
339
340Sema::OwningExprResult
341Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
342 DeclarationName Name,
343 SourceLocation NameLoc,
344 const TemplateArgumentListInfo *TemplateArgs) {
345 return Owned(DependentScopeDeclRefExpr::Create(Context,
346 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
347 SS.getRange(),
348 Name, NameLoc,
349 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000350}
351
Douglas Gregor72c3f312008-12-05 18:15:24 +0000352/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
353/// that the template parameter 'PrevDecl' is being shadowed by a new
354/// declaration at location Loc. Returns true to indicate that this is
355/// an error, and false otherwise.
356bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000357 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000358
359 // Microsoft Visual C++ permits template parameters to be shadowed.
360 if (getLangOptions().Microsoft)
361 return false;
362
363 // C++ [temp.local]p4:
364 // A template-parameter shall not be redeclared within its
365 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000366 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000367 << cast<NamedDecl>(PrevDecl)->getDeclName();
368 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
369 return true;
370}
371
Douglas Gregor2943aed2009-03-03 04:44:36 +0000372/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000373/// the parameter D to reference the templated declaration and return a pointer
374/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000375TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor13d2d6c2009-10-06 21:27:51 +0000376 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000377 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000378 return Temp;
379 }
380 return 0;
381}
382
Douglas Gregor788cd062009-11-11 01:00:40 +0000383static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
384 const ParsedTemplateArgument &Arg) {
385
386 switch (Arg.getKind()) {
387 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000388 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000389 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
390 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000391 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000392 return TemplateArgumentLoc(TemplateArgument(T), DI);
393 }
394
395 case ParsedTemplateArgument::NonType: {
396 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
397 return TemplateArgumentLoc(TemplateArgument(E), E);
398 }
399
400 case ParsedTemplateArgument::Template: {
401 TemplateName Template
402 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
403 return TemplateArgumentLoc(TemplateArgument(Template),
404 Arg.getScopeSpec().getRange(),
405 Arg.getLocation());
406 }
407 }
408
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000409 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000410 return TemplateArgumentLoc();
411}
412
413/// \brief Translates template arguments as provided by the parser
414/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000415void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
416 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000417 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000418 TemplateArgs.addArgument(translateTemplateArgument(*this,
419 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000420}
421
Douglas Gregor72c3f312008-12-05 18:15:24 +0000422/// ActOnTypeParameter - Called when a C++ template type parameter
423/// (e.g., "typename T") has been parsed. Typename specifies whether
424/// the keyword "typename" was used to declare the type parameter
425/// (otherwise, "class" was used), and KeyLoc is the location of the
426/// "class" or "typename" keyword. ParamName is the name of the
427/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump1eb44332009-09-09 15:08:12 +0000428/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000429/// If the type parameter has a default argument, it will be added
430/// later via ActOnTypeParameterDefault.
Mike Stump1eb44332009-09-09 15:08:12 +0000431Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson941df7d2009-06-12 19:58:00 +0000432 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000433 SourceLocation KeyLoc,
434 IdentifierInfo *ParamName,
435 SourceLocation ParamNameLoc,
436 unsigned Depth, unsigned Position) {
Mike Stump1eb44332009-09-09 15:08:12 +0000437 assert(S->isTemplateParamScope() &&
438 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000439 bool Invalid = false;
440
441 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000442 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000443 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000444 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000445 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000446 }
447
Douglas Gregorddc29e12009-02-06 22:42:48 +0000448 SourceLocation Loc = ParamNameLoc;
449 if (!ParamName)
450 Loc = KeyLoc;
451
Douglas Gregor72c3f312008-12-05 18:15:24 +0000452 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000453 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
454 Loc, Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000455 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000456 if (Invalid)
457 Param->setInvalidDecl();
458
459 if (ParamName) {
460 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000461 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000462 IdResolver.AddDecl(Param);
463 }
464
Chris Lattnerb28317a2009-03-28 19:18:32 +0000465 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000466}
467
Douglas Gregord684b002009-02-10 19:49:53 +0000468/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump1eb44332009-09-09 15:08:12 +0000469/// Default) to the given template type parameter (TypeParam).
470void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000471 SourceLocation EqualLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000472 SourceLocation DefaultLoc,
Douglas Gregord684b002009-02-10 19:49:53 +0000473 TypeTy *DefaultT) {
Mike Stump1eb44332009-09-09 15:08:12 +0000474 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000475 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall833ca992009-10-29 08:12:44 +0000476
John McCalla93c9342009-12-07 02:54:59 +0000477 TypeSourceInfo *DefaultTInfo;
478 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall833ca992009-10-29 08:12:44 +0000479
John McCalla93c9342009-12-07 02:54:59 +0000480 assert(DefaultTInfo && "expected source information for type");
Douglas Gregord684b002009-02-10 19:49:53 +0000481
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000482 // C++0x [temp.param]p9:
483 // A default template-argument may be specified for any kind of
Mike Stump1eb44332009-09-09 15:08:12 +0000484 // template-parameter that is not a template parameter pack.
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000485 if (Parm->isParameterPack()) {
486 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000487 return;
488 }
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Douglas Gregord684b002009-02-10 19:49:53 +0000490 // C++ [temp.param]p14:
491 // A template-parameter shall not be used in its own default argument.
492 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Douglas Gregord684b002009-02-10 19:49:53 +0000494 // Check the template argument itself.
John McCalla93c9342009-12-07 02:54:59 +0000495 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000496 Parm->setInvalidDecl();
497 return;
498 }
499
John McCalla93c9342009-12-07 02:54:59 +0000500 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000501}
502
Douglas Gregor2943aed2009-03-03 04:44:36 +0000503/// \brief Check that the type of a non-type template parameter is
504/// well-formed.
505///
506/// \returns the (possibly-promoted) parameter type if valid;
507/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000508QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000509Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
510 // C++ [temp.param]p4:
511 //
512 // A non-type template-parameter shall have one of the following
513 // (optionally cv-qualified) types:
514 //
515 // -- integral or enumeration type,
516 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000517 // -- pointer to object or pointer to function,
518 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000519 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
520 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000521 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000522 T->isReferenceType() ||
523 // -- pointer to member.
524 T->isMemberPointerType() ||
525 // If T is a dependent type, we can't do the check now, so we
526 // assume that it is well-formed.
527 T->isDependentType())
528 return T;
529 // C++ [temp.param]p8:
530 //
531 // A non-type template-parameter of type "array of T" or
532 // "function returning T" is adjusted to be of type "pointer to
533 // T" or "pointer to function returning T", respectively.
534 else if (T->isArrayType())
535 // FIXME: Keep the type prior to promotion?
536 return Context.getArrayDecayedType(T);
537 else if (T->isFunctionType())
538 // FIXME: Keep the type prior to promotion?
539 return Context.getPointerType(T);
540
541 Diag(Loc, diag::err_template_nontype_parm_bad_type)
542 << T;
543
544 return QualType();
545}
546
Douglas Gregor72c3f312008-12-05 18:15:24 +0000547/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
548/// template parameter (e.g., "int Size" in "template<int Size>
549/// class Array") has been parsed. S is the current scope and D is
550/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000551Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump1eb44332009-09-09 15:08:12 +0000552 unsigned Depth,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000553 unsigned Position) {
John McCalla93c9342009-12-07 02:54:59 +0000554 TypeSourceInfo *TInfo = 0;
555 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000556
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000557 assert(S->isTemplateParamScope() &&
558 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000559 bool Invalid = false;
560
561 IdentifierInfo *ParamName = D.getIdentifier();
562 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000563 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000564 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000565 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000566 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000567 }
568
Douglas Gregor2943aed2009-03-03 04:44:36 +0000569 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000570 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000571 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000572 Invalid = true;
573 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000574
Douglas Gregor72c3f312008-12-05 18:15:24 +0000575 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000576 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
577 D.getIdentifierLoc(),
John McCalla93c9342009-12-07 02:54:59 +0000578 Depth, Position, ParamName, T, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000579 if (Invalid)
580 Param->setInvalidDecl();
581
582 if (D.getIdentifier()) {
583 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000584 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000585 IdResolver.AddDecl(Param);
586 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000587 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000588}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000589
Douglas Gregord684b002009-02-10 19:49:53 +0000590/// \brief Adds a default argument to the given non-type template
591/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000592void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000593 SourceLocation EqualLoc,
594 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000595 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000596 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000597 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000598
Douglas Gregord684b002009-02-10 19:49:53 +0000599 // C++ [temp.param]p14:
600 // A template-parameter shall not be used in its own default argument.
601 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000602
Douglas Gregord684b002009-02-10 19:49:53 +0000603 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000604 TemplateArgument Converted;
605 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
606 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000607 TemplateParm->setInvalidDecl();
608 return;
609 }
610
Anders Carlssone9146f22009-05-01 19:49:17 +0000611 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000612}
613
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000614
615/// ActOnTemplateTemplateParameter - Called when a C++ template template
616/// parameter (e.g. T in template <template <typename> class T> class array)
617/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000618Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
619 SourceLocation TmpLoc,
620 TemplateParamsTy *Params,
621 IdentifierInfo *Name,
622 SourceLocation NameLoc,
623 unsigned Depth,
Mike Stump1eb44332009-09-09 15:08:12 +0000624 unsigned Position) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000625 assert(S->isTemplateParamScope() &&
626 "Template template parameter not in template parameter scope!");
627
628 // Construct the parameter object.
629 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000630 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
631 TmpLoc, Depth, Position, Name,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000632 (TemplateParameterList*)Params);
633
634 // Make sure the parameter is valid.
635 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
636 // do anything yet. However, if the template parameter list or (eventual)
637 // default value is ever invalidated, that will propagate here.
638 bool Invalid = false;
639 if (Invalid) {
640 Param->setInvalidDecl();
641 }
642
643 // If the tt-param has a name, then link the identifier into the scope
644 // and lookup mechanisms.
645 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000646 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000647 IdResolver.AddDecl(Param);
648 }
649
Chris Lattnerb28317a2009-03-28 19:18:32 +0000650 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000651}
652
Douglas Gregord684b002009-02-10 19:49:53 +0000653/// \brief Adds a default argument to the given template template
654/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000655void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000656 SourceLocation EqualLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +0000657 const ParsedTemplateArgument &Default) {
Mike Stump1eb44332009-09-09 15:08:12 +0000658 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000659 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor788cd062009-11-11 01:00:40 +0000660
Douglas Gregord684b002009-02-10 19:49:53 +0000661 // C++ [temp.param]p14:
662 // A template-parameter shall not be used in its own default argument.
663 // FIXME: Implement this check! Needs a recursive walk over the types.
664
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000665 // Check only that we have a template template argument. We don't want to
666 // try to check well-formedness now, because our template template parameter
667 // might have dependent types in its template parameters, which we wouldn't
668 // be able to match now.
669 //
670 // If none of the template template parameter's template arguments mention
671 // other template parameters, we could actually perform more checking here.
672 // However, it isn't worth doing.
Douglas Gregor788cd062009-11-11 01:00:40 +0000673 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000674 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
675 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
676 << DefaultArg.getSourceRange();
Douglas Gregord684b002009-02-10 19:49:53 +0000677 return;
678 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000679
Douglas Gregor788cd062009-11-11 01:00:40 +0000680 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregord684b002009-02-10 19:49:53 +0000681}
682
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000683/// ActOnTemplateParameterList - Builds a TemplateParameterList that
684/// contains the template parameters in Params/NumParams.
685Sema::TemplateParamsTy *
686Sema::ActOnTemplateParameterList(unsigned Depth,
687 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000688 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000689 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000690 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000691 SourceLocation RAngleLoc) {
692 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000693 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000694
Douglas Gregorddc29e12009-02-06 22:42:48 +0000695 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000696 (NamedDecl**)Params, NumParams,
697 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000698}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000699
John McCallb6217662010-03-15 10:12:16 +0000700static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
701 if (SS.isSet())
702 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
703 SS.getRange());
704}
705
Douglas Gregor212e81c2009-03-25 00:13:59 +0000706Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000707Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000708 SourceLocation KWLoc, const CXXScopeSpec &SS,
709 IdentifierInfo *Name, SourceLocation NameLoc,
710 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000711 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000712 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000713 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000714 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000715 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000716 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000717
718 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000719 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000720 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000721
John McCall05b23ea2009-09-14 21:59:20 +0000722 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
723 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000724
725 // There is no such thing as an unnamed class template.
726 if (!Name) {
727 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000728 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000729 }
730
731 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000732 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000733 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000734 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000735 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregorf0510d42009-10-12 23:11:44 +0000736 if (RequireCompleteDeclContext(SS))
737 return true;
738
Douglas Gregor05396e22009-08-25 17:23:04 +0000739 SemanticContext = computeDeclContext(SS, true);
740 if (!SemanticContext) {
741 // FIXME: Produce a reasonable diagnostic here
742 return true;
743 }
Mike Stump1eb44332009-09-09 15:08:12 +0000744
John McCalla24dc2e2009-11-17 02:14:36 +0000745 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000746 } else {
747 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000748 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000749 }
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Douglas Gregorddc29e12009-02-06 22:42:48 +0000751 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
752 NamedDecl *PrevDecl = 0;
753 if (Previous.begin() != Previous.end())
754 PrevDecl = *Previous.begin();
755
Douglas Gregorddc29e12009-02-06 22:42:48 +0000756 // If there is a previous declaration with the same name, check
757 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000758 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000759 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000760
761 // We may have found the injected-class-name of a class template,
762 // class template partial specialization, or class template specialization.
763 // In these cases, grab the template that is being defined or specialized.
764 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
765 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
766 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
767 PrevClassTemplate
768 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
769 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
770 PrevClassTemplate
771 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
772 ->getSpecializedTemplate();
773 }
774 }
775
John McCall65c49462009-12-18 11:25:59 +0000776 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000777 // C++ [namespace.memdef]p3:
778 // [...] When looking for a prior declaration of a class or a function
779 // declared as a friend, and when the name of the friend class or
780 // function is neither a qualified name nor a template-id, scopes outside
781 // the innermost enclosing namespace scope are not considered.
782 DeclContext *OutermostContext = CurContext;
783 while (!OutermostContext->isFileContext())
784 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000785
786 if (PrevDecl &&
787 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
788 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
John McCalle129d442009-12-17 23:21:11 +0000789 SemanticContext = PrevDecl->getDeclContext();
790 } else {
791 // Declarations in outer scopes don't matter. However, the outermost
792 // context we computed is the semantic context for our new
793 // declaration.
794 PrevDecl = PrevClassTemplate = 0;
795 SemanticContext = OutermostContext;
796 }
797
798 if (CurContext->isDependentContext()) {
799 // If this is a dependent context, we don't want to link the friend
800 // class template to the template in scope, because that would perform
801 // checking of the template parameter lists that can't be performed
802 // until the outer context is instantiated.
803 PrevDecl = PrevClassTemplate = 0;
804 }
805 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
806 PrevDecl = PrevClassTemplate = 0;
807
Douglas Gregorddc29e12009-02-06 22:42:48 +0000808 if (PrevClassTemplate) {
809 // Ensure that the template parameter lists are compatible.
810 if (!TemplateParameterListsAreEqual(TemplateParams,
811 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000812 /*Complain=*/true,
813 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000814 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000815
816 // C++ [temp.class]p4:
817 // In a redeclaration, partial specialization, explicit
818 // specialization or explicit instantiation of a class template,
819 // the class-key shall agree in kind with the original class
820 // template declaration (7.1.5.3).
821 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000822 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000823 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000824 << Name
Mike Stump1eb44332009-09-09 15:08:12 +0000825 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +0000826 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000827 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000828 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000829 }
830
Douglas Gregorddc29e12009-02-06 22:42:48 +0000831 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000832 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000833 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000834 Diag(NameLoc, diag::err_redefinition) << Name;
835 Diag(Def->getLocation(), diag::note_previous_definition);
836 // FIXME: Would it make sense to try to "forget" the previous
837 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000838 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000839 }
840 }
841 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
842 // Maybe we will complain about the shadowed template parameter.
843 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
844 // Just pretend that we didn't see the previous declaration.
845 PrevDecl = 0;
846 } else if (PrevDecl) {
847 // C++ [temp]p5:
848 // A class template shall not have the same name as any other
849 // template, class, function, object, enumeration, enumerator,
850 // namespace, or type in the same scope (3.3), except as specified
851 // in (14.5.4).
852 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
853 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000854 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000855 }
856
Douglas Gregord684b002009-02-10 19:49:53 +0000857 // Check the template parameter list of this declaration, possibly
858 // merging in the template parameter list from the previous class
859 // template declaration.
860 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000861 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
862 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000863 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000864
Douglas Gregor7da97d02009-05-10 22:57:19 +0000865 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000866 // declaration!
867
Mike Stump1eb44332009-09-09 15:08:12 +0000868 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000869 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000870 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000871 PrevClassTemplate->getTemplatedDecl() : 0,
872 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000873 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000874
875 ClassTemplateDecl *NewTemplate
876 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
877 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000878 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000879 NewClass->setDescribedClassTemplate(NewTemplate);
880
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000881 // Build the type for the class template declaration now.
John McCall3cb0ebd2010-03-10 03:28:59 +0000882 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
883 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000884 assert(T->isDependentType() && "Class template type is not dependent?");
885 (void)T;
886
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000887 // If we are providing an explicit specialization of a member that is a
888 // class template, make a note of that.
889 if (PrevClassTemplate &&
890 PrevClassTemplate->getInstantiatedFromMemberTemplate())
891 PrevClassTemplate->setMemberSpecialization();
892
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000893 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000894 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000895 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Douglas Gregorddc29e12009-02-06 22:42:48 +0000897 // Set the lexical context of these templates
898 NewClass->setLexicalDeclContext(CurContext);
899 NewTemplate->setLexicalDeclContext(CurContext);
900
John McCall0f434ec2009-07-31 02:45:11 +0000901 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000902 NewClass->startDefinition();
903
904 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000905 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000906
John McCall05b23ea2009-09-14 21:59:20 +0000907 if (TUK != TUK_Friend)
908 PushOnScopeChains(NewTemplate, S);
909 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000910 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000911 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000912 NewClass->setAccess(PrevClassTemplate->getAccess());
913 }
John McCall05b23ea2009-09-14 21:59:20 +0000914
Douglas Gregord85bea22009-09-26 06:47:28 +0000915 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
916 PrevClassTemplate != NULL);
917
John McCall05b23ea2009-09-14 21:59:20 +0000918 // Friend templates are visible in fairly strange ways.
919 if (!CurContext->isDependentContext()) {
920 DeclContext *DC = SemanticContext->getLookupContext();
921 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
922 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
923 PushOnScopeChains(NewTemplate, EnclosingScope,
924 /* AddToContext = */ false);
925 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000926
927 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
928 NewClass->getLocation(),
929 NewTemplate,
930 /*FIXME:*/NewClass->getLocation());
931 Friend->setAccess(AS_public);
932 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000933 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000934
Douglas Gregord684b002009-02-10 19:49:53 +0000935 if (Invalid) {
936 NewTemplate->setInvalidDecl();
937 NewClass->setInvalidDecl();
938 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000939 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000940}
941
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000942/// \brief Diagnose the presence of a default template argument on a
943/// template parameter, which is ill-formed in certain contexts.
944///
945/// \returns true if the default template argument should be dropped.
946static bool DiagnoseDefaultTemplateArgument(Sema &S,
947 Sema::TemplateParamListContext TPC,
948 SourceLocation ParamLoc,
949 SourceRange DefArgRange) {
950 switch (TPC) {
951 case Sema::TPC_ClassTemplate:
952 return false;
953
954 case Sema::TPC_FunctionTemplate:
955 // C++ [temp.param]p9:
956 // A default template-argument shall not be specified in a
957 // function template declaration or a function template
958 // definition [...]
959 // (This sentence is not in C++0x, per DR226).
960 if (!S.getLangOptions().CPlusPlus0x)
961 S.Diag(ParamLoc,
962 diag::err_template_parameter_default_in_function_template)
963 << DefArgRange;
964 return false;
965
966 case Sema::TPC_ClassTemplateMember:
967 // C++0x [temp.param]p9:
968 // A default template-argument shall not be specified in the
969 // template-parameter-lists of the definition of a member of a
970 // class template that appears outside of the member's class.
971 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
972 << DefArgRange;
973 return true;
974
975 case Sema::TPC_FriendFunctionTemplate:
976 // C++ [temp.param]p9:
977 // A default template-argument shall not be specified in a
978 // friend template declaration.
979 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
980 << DefArgRange;
981 return true;
982
983 // FIXME: C++0x [temp.param]p9 allows default template-arguments
984 // for friend function templates if there is only a single
985 // declaration (and it is a definition). Strange!
986 }
987
988 return false;
989}
990
Douglas Gregord684b002009-02-10 19:49:53 +0000991/// \brief Checks the validity of a template parameter list, possibly
992/// considering the template parameter list from a previous
993/// declaration.
994///
995/// If an "old" template parameter list is provided, it must be
996/// equivalent (per TemplateParameterListsAreEqual) to the "new"
997/// template parameter list.
998///
999/// \param NewParams Template parameter list for a new template
1000/// declaration. This template parameter list will be updated with any
1001/// default arguments that are carried through from the previous
1002/// template parameter list.
1003///
1004/// \param OldParams If provided, template parameter list from a
1005/// previous declaration of the same template. Default template
1006/// arguments will be merged from the old template parameter list to
1007/// the new template parameter list.
1008///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001009/// \param TPC Describes the context in which we are checking the given
1010/// template parameter list.
1011///
Douglas Gregord684b002009-02-10 19:49:53 +00001012/// \returns true if an error occurred, false otherwise.
1013bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001014 TemplateParameterList *OldParams,
1015 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001016 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001017
Douglas Gregord684b002009-02-10 19:49:53 +00001018 // C++ [temp.param]p10:
1019 // The set of default template-arguments available for use with a
1020 // template declaration or definition is obtained by merging the
1021 // default arguments from the definition (if in scope) and all
1022 // declarations in scope in the same way default function
1023 // arguments are (8.3.6).
1024 bool SawDefaultArgument = false;
1025 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001026
Anders Carlsson49d25572009-06-12 23:20:15 +00001027 bool SawParameterPack = false;
1028 SourceLocation ParameterPackLoc;
1029
Mike Stump1a35fde2009-02-11 23:03:27 +00001030 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001031 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001032 if (OldParams)
1033 OldParam = OldParams->begin();
1034
1035 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1036 NewParamEnd = NewParams->end();
1037 NewParam != NewParamEnd; ++NewParam) {
1038 // Variables used to diagnose redundant default arguments
1039 bool RedundantDefaultArg = false;
1040 SourceLocation OldDefaultLoc;
1041 SourceLocation NewDefaultLoc;
1042
1043 // Variables used to diagnose missing default arguments
1044 bool MissingDefaultArg = false;
1045
Anders Carlsson49d25572009-06-12 23:20:15 +00001046 // C++0x [temp.param]p11:
1047 // If a template parameter of a class template is a template parameter pack,
1048 // it must be the last template parameter.
1049 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001050 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001051 diag::err_template_param_pack_must_be_last_template_parameter);
1052 Invalid = true;
1053 }
1054
Douglas Gregord684b002009-02-10 19:49:53 +00001055 if (TemplateTypeParmDecl *NewTypeParm
1056 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001057 // Check the presence of a default argument here.
1058 if (NewTypeParm->hasDefaultArgument() &&
1059 DiagnoseDefaultTemplateArgument(*this, TPC,
1060 NewTypeParm->getLocation(),
1061 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1062 .getFullSourceRange()))
1063 NewTypeParm->removeDefaultArgument();
1064
1065 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001066 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001067 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001068
Anders Carlsson49d25572009-06-12 23:20:15 +00001069 if (NewTypeParm->isParameterPack()) {
1070 assert(!NewTypeParm->hasDefaultArgument() &&
1071 "Parameter packs can't have a default argument!");
1072 SawParameterPack = true;
1073 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001074 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001075 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001076 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1077 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1078 SawDefaultArgument = true;
1079 RedundantDefaultArg = true;
1080 PreviousDefaultArgLoc = NewDefaultLoc;
1081 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1082 // Merge the default argument from the old declaration to the
1083 // new declaration.
1084 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001085 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001086 true);
1087 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1088 } else if (NewTypeParm->hasDefaultArgument()) {
1089 SawDefaultArgument = true;
1090 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1091 } else if (SawDefaultArgument)
1092 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001093 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001094 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001095 // Check the presence of a default argument here.
1096 if (NewNonTypeParm->hasDefaultArgument() &&
1097 DiagnoseDefaultTemplateArgument(*this, TPC,
1098 NewNonTypeParm->getLocation(),
1099 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1100 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1101 NewNonTypeParm->setDefaultArgument(0);
1102 }
1103
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001104 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001105 NonTypeTemplateParmDecl *OldNonTypeParm
1106 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001107 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001108 NewNonTypeParm->hasDefaultArgument()) {
1109 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1110 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1111 SawDefaultArgument = true;
1112 RedundantDefaultArg = true;
1113 PreviousDefaultArgLoc = NewDefaultLoc;
1114 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1115 // Merge the default argument from the old declaration to the
1116 // new declaration.
1117 SawDefaultArgument = true;
1118 // FIXME: We need to create a new kind of "default argument"
1119 // expression that points to a previous template template
1120 // parameter.
1121 NewNonTypeParm->setDefaultArgument(
1122 OldNonTypeParm->getDefaultArgument());
1123 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1124 } else if (NewNonTypeParm->hasDefaultArgument()) {
1125 SawDefaultArgument = true;
1126 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1127 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001128 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001129 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001130 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001131 TemplateTemplateParmDecl *NewTemplateParm
1132 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001133 if (NewTemplateParm->hasDefaultArgument() &&
1134 DiagnoseDefaultTemplateArgument(*this, TPC,
1135 NewTemplateParm->getLocation(),
1136 NewTemplateParm->getDefaultArgument().getSourceRange()))
1137 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1138
1139 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001140 TemplateTemplateParmDecl *OldTemplateParm
1141 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001142 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001143 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001144 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1145 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001146 SawDefaultArgument = true;
1147 RedundantDefaultArg = true;
1148 PreviousDefaultArgLoc = NewDefaultLoc;
1149 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1150 // Merge the default argument from the old declaration to the
1151 // new declaration.
1152 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001153 // FIXME: We need to create a new kind of "default argument" expression
1154 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001155 NewTemplateParm->setDefaultArgument(
1156 OldTemplateParm->getDefaultArgument());
Douglas Gregor788cd062009-11-11 01:00:40 +00001157 PreviousDefaultArgLoc
1158 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001159 } else if (NewTemplateParm->hasDefaultArgument()) {
1160 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001161 PreviousDefaultArgLoc
1162 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001163 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001164 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001165 }
1166
1167 if (RedundantDefaultArg) {
1168 // C++ [temp.param]p12:
1169 // A template-parameter shall not be given default arguments
1170 // by two different declarations in the same scope.
1171 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1172 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1173 Invalid = true;
1174 } else if (MissingDefaultArg) {
1175 // C++ [temp.param]p11:
1176 // If a template-parameter has a default template-argument,
1177 // all subsequent template-parameters shall have a default
1178 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001179 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001180 diag::err_template_param_default_arg_missing);
1181 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1182 Invalid = true;
1183 }
1184
1185 // If we have an old template parameter list that we're merging
1186 // in, move on to the next parameter.
1187 if (OldParams)
1188 ++OldParam;
1189 }
1190
1191 return Invalid;
1192}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001193
Mike Stump1eb44332009-09-09 15:08:12 +00001194/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001195/// specifier, returning the template parameter list that applies to the
1196/// name.
1197///
1198/// \param DeclStartLoc the start of the declaration that has a scope
1199/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001200///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001201/// \param SS the scope specifier that will be matched to the given template
1202/// parameter lists. This scope specifier precedes a qualified name that is
1203/// being declared.
1204///
1205/// \param ParamLists the template parameter lists, from the outermost to the
1206/// innermost template parameter lists.
1207///
1208/// \param NumParamLists the number of template parameter lists in ParamLists.
1209///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001210/// \param IsExplicitSpecialization will be set true if the entity being
1211/// declared is an explicit specialization, false otherwise.
1212///
Mike Stump1eb44332009-09-09 15:08:12 +00001213/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001214/// name that is preceded by the scope specifier @p SS. This template
1215/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001216/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001217/// template specialization), or may be NULL (if we were's declaring isn't
1218/// itself a template).
1219TemplateParameterList *
1220Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1221 const CXXScopeSpec &SS,
1222 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001223 unsigned NumParamLists,
1224 bool &IsExplicitSpecialization) {
1225 IsExplicitSpecialization = false;
1226
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001227 // Find the template-ids that occur within the nested-name-specifier. These
1228 // template-ids will match up with the template parameter lists.
1229 llvm::SmallVector<const TemplateSpecializationType *, 4>
1230 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001231 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1232 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001233 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1234 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001235 const Type *T = NNS->getAsType();
1236 if (!T) break;
1237
1238 // C++0x [temp.expl.spec]p17:
1239 // A member or a member template may be nested within many
1240 // enclosing class templates. In an explicit specialization for
1241 // such a member, the member declaration shall be preceded by a
1242 // template<> for each enclosing class template that is
1243 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001244 //
1245 // Following the existing practice of GNU and EDG, we allow a typedef of a
1246 // template specialization type.
1247 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1248 T = TT->LookThroughTypedefs().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001249
Mike Stump1eb44332009-09-09 15:08:12 +00001250 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001251 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001252 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1253 if (!Template)
1254 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001255
Ted Kremenek6217b802009-07-29 21:53:49 +00001256 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001257 ClassTemplateSpecializationDecl *SpecDecl
1258 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1259 // If the nested name specifier refers to an explicit specialization,
1260 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001261 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1262 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001263 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001264 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001265 }
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001267 TemplateIdsInSpecifier.push_back(SpecType);
1268 }
1269 }
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001271 // Reverse the list of template-ids in the scope specifier, so that we can
1272 // more easily match up the template-ids and the template parameter lists.
1273 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001275 SourceLocation FirstTemplateLoc = DeclStartLoc;
1276 if (NumParamLists)
1277 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001278
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001279 // Match the template-ids found in the specifier to the template parameter
1280 // lists.
1281 unsigned Idx = 0;
1282 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1283 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001284 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1285 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001286 if (Idx >= NumParamLists) {
1287 // We have a template-id without a corresponding template parameter
1288 // list.
1289 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001290 // FIXME: the location information here isn't great.
1291 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001292 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001293 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001294 << SS.getRange();
1295 } else {
1296 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1297 << SS.getRange()
1298 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1299 "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001300 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001301 }
1302 return 0;
1303 }
Mike Stump1eb44332009-09-09 15:08:12 +00001304
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001305 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001306 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001307 TemplateDecl *Template
Douglas Gregorb88e8882009-07-30 17:40:51 +00001308 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1309
Mike Stump1eb44332009-09-09 15:08:12 +00001310 if (ClassTemplateDecl *ClassTemplate
Douglas Gregorb88e8882009-07-30 17:40:51 +00001311 = dyn_cast<ClassTemplateDecl>(Template)) {
1312 TemplateParameterList *ExpectedTemplateParams = 0;
1313 // Is this template-id naming the primary template?
1314 if (Context.hasSameType(TemplateId,
John McCall3cb0ebd2010-03-10 03:28:59 +00001315 ClassTemplate->getInjectedClassNameSpecialization(Context)))
Douglas Gregorb88e8882009-07-30 17:40:51 +00001316 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1317 // ... or a partial specialization?
1318 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1319 = ClassTemplate->findPartialSpecialization(TemplateId))
1320 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1321
1322 if (ExpectedTemplateParams)
Mike Stump1eb44332009-09-09 15:08:12 +00001323 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregorb88e8882009-07-30 17:40:51 +00001324 ExpectedTemplateParams,
Douglas Gregorfb898e12009-11-12 16:20:59 +00001325 true, TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00001326 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001327
1328 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregorb88e8882009-07-30 17:40:51 +00001329 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001330 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001331 diag::err_template_param_list_matches_nontemplate)
1332 << TemplateId
1333 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001334 else
1335 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001336 }
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001338 // If there were at least as many template-ids as there were template
1339 // parameter lists, then there are no template parameter lists remaining for
1340 // the declaration itself.
1341 if (Idx >= NumParamLists)
1342 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001343
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001344 // If there were too many template parameter lists, complain about that now.
1345 if (Idx != NumParamLists - 1) {
1346 while (Idx < NumParamLists - 1) {
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001347 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001348 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001349 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1350 : diag::err_template_spec_extra_headers)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001351 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1352 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001353
1354 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1355 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1356 diag::note_explicit_template_spec_does_not_need_header)
1357 << ExplicitSpecializationsInSpecifier.back();
1358 ExplicitSpecializationsInSpecifier.pop_back();
1359 }
1360
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001361 ++Idx;
1362 }
1363 }
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001365 // Return the last template parameter list, which corresponds to the
1366 // entity being declared.
1367 return ParamLists[NumParamLists - 1];
1368}
1369
Douglas Gregor7532dc62009-03-30 22:58:21 +00001370QualType Sema::CheckTemplateIdType(TemplateName Name,
1371 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001372 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001373 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001374 if (!Template) {
1375 // The template name does not resolve to a template, so we just
1376 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001377 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001378 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001379
Douglas Gregor40808ce2009-03-09 23:48:35 +00001380 // Check that the template argument list is well-formed for this
1381 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001382 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCalld5532b62009-11-23 01:53:49 +00001383 TemplateArgs.size());
1384 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001385 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001386 return QualType();
1387
Mike Stump1eb44332009-09-09 15:08:12 +00001388 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001389 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001390 "Converted template argument list is too short!");
1391
1392 QualType CanonType;
1393
Douglas Gregorcaddba02009-11-12 18:38:13 +00001394 if (Name.isDependent() ||
1395 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001396 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001397 // This class template specialization is a dependent
1398 // type. Therefore, its canonical type is another class template
1399 // specialization type that contains all of the converted
1400 // arguments in canonical form. This ensures that, e.g., A<T> and
1401 // A<T, T> have identical types when A is declared as:
1402 //
1403 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001404 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001405 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001406 Converted.getFlatArguments(),
1407 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Douglas Gregor1275ae02009-07-28 23:00:59 +00001409 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001410 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001411 // In the future, we need to teach getTemplateSpecializationType to only
1412 // build the canonical type and return that to us.
1413 CanonType = Context.getCanonicalType(CanonType);
Mike Stump1eb44332009-09-09 15:08:12 +00001414 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001415 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001416 // Find the class template specialization declaration that
1417 // corresponds to these arguments.
1418 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001419 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001420 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001421 Converted.flatSize(),
1422 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001423 void *InsertPos = 0;
1424 ClassTemplateSpecializationDecl *Decl
1425 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1426 if (!Decl) {
1427 // This is the first time we have referenced this class template
1428 // specialization. Create the canonical declaration and add it to
1429 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001430 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001431 ClassTemplate->getDeclContext(),
John McCall9cc78072009-09-11 07:25:08 +00001432 ClassTemplate->getLocation(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001433 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00001434 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001435 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1436 Decl->setLexicalDeclContext(CurContext);
1437 }
1438
1439 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001440 assert(isa<RecordType>(CanonType) &&
1441 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001442 }
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Douglas Gregor40808ce2009-03-09 23:48:35 +00001444 // Build the fully-sugared type for this class template
1445 // specialization, which refers back to the class template
1446 // specialization we created or found.
John McCalld5532b62009-11-23 01:53:49 +00001447 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001448}
1449
Douglas Gregorcc636682009-02-17 23:15:12 +00001450Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001451Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001452 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001453 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001454 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001455 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001456
Douglas Gregor40808ce2009-03-09 23:48:35 +00001457 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001458 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001459 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001460
John McCalld5532b62009-11-23 01:53:49 +00001461 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001462 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001463
1464 if (Result.isNull())
1465 return true;
1466
John McCalla93c9342009-12-07 02:54:59 +00001467 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001468 TemplateSpecializationTypeLoc TL
1469 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1470 TL.setTemplateNameLoc(TemplateLoc);
1471 TL.setLAngleLoc(LAngleLoc);
1472 TL.setRAngleLoc(RAngleLoc);
1473 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1474 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1475
1476 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCall6b2becf2009-09-08 17:47:29 +00001477}
John McCallf1bbbb42009-09-04 01:14:41 +00001478
John McCall6b2becf2009-09-08 17:47:29 +00001479Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1480 TagUseKind TUK,
1481 DeclSpec::TST TagSpec,
1482 SourceLocation TagLoc) {
1483 if (TypeResult.isInvalid())
1484 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001485
John McCall833ca992009-10-29 08:12:44 +00001486 // FIXME: preserve source info, ideally without copying the DI.
John McCalla93c9342009-12-07 02:54:59 +00001487 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001488 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001489
John McCall6b2becf2009-09-08 17:47:29 +00001490 // Verify the tag specifier.
1491 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001492
John McCall6b2becf2009-09-08 17:47:29 +00001493 if (const RecordType *RT = Type->getAs<RecordType>()) {
1494 RecordDecl *D = RT->getDecl();
1495
1496 IdentifierInfo *Id = D->getIdentifier();
1497 assert(Id && "templated class must have an identifier");
1498
1499 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1500 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001501 << Type
John McCall6b2becf2009-09-08 17:47:29 +00001502 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1503 D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001504 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001505 }
1506 }
1507
John McCall6b2becf2009-09-08 17:47:29 +00001508 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1509
1510 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001511}
1512
John McCallf7a1a742009-11-24 19:00:30 +00001513Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1514 LookupResult &R,
1515 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001516 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001517 // FIXME: Can we do any checking at this point? I guess we could check the
1518 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001519 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001520 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001521
1522 // These should be filtered out by our callers.
1523 assert(!R.empty() && "empty lookup results when building templateid");
1524 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1525
1526 NestedNameSpecifier *Qualifier = 0;
1527 SourceRange QualifierRange;
1528 if (SS.isSet()) {
1529 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1530 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001531 }
John McCallc373d482010-01-27 01:50:18 +00001532
1533 // We don't want lookup warnings at this point.
1534 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001535
John McCallf7a1a742009-11-24 19:00:30 +00001536 bool Dependent
1537 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1538 &TemplateArgs);
1539 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001540 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001541 Qualifier, QualifierRange,
1542 R.getLookupName(), R.getNameLoc(),
1543 RequiresADL, TemplateArgs);
John McCallc373d482010-01-27 01:50:18 +00001544 ULE->addDecls(R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001545
1546 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001547}
1548
John McCallf7a1a742009-11-24 19:00:30 +00001549// We actually only call this from template instantiation.
1550Sema::OwningExprResult
1551Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1552 DeclarationName Name,
1553 SourceLocation NameLoc,
1554 const TemplateArgumentListInfo &TemplateArgs) {
1555 DeclContext *DC;
1556 if (!(DC = computeDeclContext(SS, false)) ||
1557 DC->isDependentContext() ||
1558 RequireCompleteDeclContext(SS))
1559 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001560
John McCallf7a1a742009-11-24 19:00:30 +00001561 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1562 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00001563
John McCallf7a1a742009-11-24 19:00:30 +00001564 if (R.isAmbiguous())
1565 return ExprError();
1566
1567 if (R.empty()) {
1568 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1569 << Name << SS.getRange();
1570 return ExprError();
1571 }
1572
1573 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1574 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1575 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1576 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1577 return ExprError();
1578 }
1579
1580 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001581}
1582
Douglas Gregorc45c2322009-03-31 00:43:58 +00001583/// \brief Form a dependent template name.
1584///
1585/// This action forms a dependent template name given the template
1586/// name and its (presumably dependent) scope specifier. For
1587/// example, given "MetaFun::template apply", the scope specifier \p
1588/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1589/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump1eb44332009-09-09 15:08:12 +00001590Sema::TemplateTy
Douglas Gregorc45c2322009-03-31 00:43:58 +00001591Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001592 const CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +00001593 UnqualifiedId &Name,
Douglas Gregora481edb2009-11-20 23:39:24 +00001594 TypeTy *ObjectType,
1595 bool EnteringContext) {
Douglas Gregor0707bc52010-01-19 16:01:07 +00001596 DeclContext *LookupCtx = 0;
1597 if (SS.isSet())
1598 LookupCtx = computeDeclContext(SS, EnteringContext);
1599 if (!LookupCtx && ObjectType)
1600 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1601 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001602 // C++0x [temp.names]p5:
1603 // If a name prefixed by the keyword template is not the name of
1604 // a template, the program is ill-formed. [Note: the keyword
1605 // template may not be applied to non-template members of class
1606 // templates. -end note ] [ Note: as is the case with the
1607 // typename prefix, the template prefix is allowed in cases
1608 // where it is not strictly necessary; i.e., when the
1609 // nested-name-specifier or the expression on the left of the ->
1610 // or . is not dependent on a template-parameter, or the use
1611 // does not appear in the scope of a template. -end note]
1612 //
1613 // Note: C++03 was more strict here, because it banned the use of
1614 // the "template" keyword prior to a template-name that was not a
1615 // dependent name. C++ DR468 relaxed this requirement (the
1616 // "template" keyword is now permitted). We follow the C++0x
1617 // rules, even in C++03 mode, retroactively applying the DR.
1618 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001619 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregora481edb2009-11-20 23:39:24 +00001620 EnteringContext, Template);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001621 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1622 isa<CXXRecordDecl>(LookupCtx) &&
1623 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001624 // This is a dependent template.
1625 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001626 Diag(Name.getSourceRange().getBegin(),
1627 diag::err_template_kw_refers_to_non_template)
1628 << GetNameFromUnqualifiedId(Name)
1629 << Name.getSourceRange();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001630 return TemplateTy();
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001631 } else {
1632 // We found something; return it.
1633 return Template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001634 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001635 }
1636
Mike Stump1eb44332009-09-09 15:08:12 +00001637 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001638 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001639
1640 switch (Name.getKind()) {
1641 case UnqualifiedId::IK_Identifier:
1642 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1643 Name.Identifier));
1644
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001645 case UnqualifiedId::IK_OperatorFunctionId:
1646 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1647 Name.OperatorFunctionId.Operator));
Sean Hunte6252d12009-11-28 08:58:14 +00001648
1649 case UnqualifiedId::IK_LiteralOperatorId:
1650 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1651
Douglas Gregor014e88d2009-11-03 23:16:33 +00001652 default:
1653 break;
1654 }
1655
1656 Diag(Name.getSourceRange().getBegin(),
1657 diag::err_template_kw_refers_to_non_template)
1658 << GetNameFromUnqualifiedId(Name)
1659 << Name.getSourceRange();
1660 return TemplateTy();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001661}
1662
Mike Stump1eb44332009-09-09 15:08:12 +00001663bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001664 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001665 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001666 const TemplateArgument &Arg = AL.getArgument();
1667
Anders Carlsson436b1562009-06-13 00:33:33 +00001668 // Check template type parameter.
1669 if (Arg.getKind() != TemplateArgument::Type) {
1670 // C++ [temp.arg.type]p1:
1671 // A template-argument for a template-parameter which is a
1672 // type shall be a type-id.
1673
1674 // We have a template type parameter but the template argument
1675 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001676 SourceRange SR = AL.getSourceRange();
1677 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001678 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001679
Anders Carlsson436b1562009-06-13 00:33:33 +00001680 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001681 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001682
John McCalla93c9342009-12-07 02:54:59 +00001683 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001684 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Anders Carlsson436b1562009-06-13 00:33:33 +00001686 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001687 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001688 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001689 return false;
1690}
1691
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001692/// \brief Substitute template arguments into the default template argument for
1693/// the given template type parameter.
1694///
1695/// \param SemaRef the semantic analysis object for which we are performing
1696/// the substitution.
1697///
1698/// \param Template the template that we are synthesizing template arguments
1699/// for.
1700///
1701/// \param TemplateLoc the location of the template name that started the
1702/// template-id we are checking.
1703///
1704/// \param RAngleLoc the location of the right angle bracket ('>') that
1705/// terminates the template-id.
1706///
1707/// \param Param the template template parameter whose default we are
1708/// substituting into.
1709///
1710/// \param Converted the list of template arguments provided for template
1711/// parameters that precede \p Param in the template parameter list.
1712///
1713/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001714static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001715SubstDefaultTemplateArgument(Sema &SemaRef,
1716 TemplateDecl *Template,
1717 SourceLocation TemplateLoc,
1718 SourceLocation RAngleLoc,
1719 TemplateTypeParmDecl *Param,
1720 TemplateArgumentListBuilder &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001721 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001722
1723 // If the argument type is dependent, instantiate it now based
1724 // on the previously-computed template arguments.
1725 if (ArgType->getType()->isDependentType()) {
1726 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1727 /*TakeArgs=*/false);
1728
1729 MultiLevelTemplateArgumentList AllTemplateArgs
1730 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1731
1732 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1733 Template, Converted.getFlatArguments(),
1734 Converted.flatSize(),
1735 SourceRange(TemplateLoc, RAngleLoc));
1736
1737 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1738 Param->getDefaultArgumentLoc(),
1739 Param->getDeclName());
1740 }
1741
1742 return ArgType;
1743}
1744
1745/// \brief Substitute template arguments into the default template argument for
1746/// the given non-type template parameter.
1747///
1748/// \param SemaRef the semantic analysis object for which we are performing
1749/// the substitution.
1750///
1751/// \param Template the template that we are synthesizing template arguments
1752/// for.
1753///
1754/// \param TemplateLoc the location of the template name that started the
1755/// template-id we are checking.
1756///
1757/// \param RAngleLoc the location of the right angle bracket ('>') that
1758/// terminates the template-id.
1759///
Douglas Gregor788cd062009-11-11 01:00:40 +00001760/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001761/// substituting into.
1762///
1763/// \param Converted the list of template arguments provided for template
1764/// parameters that precede \p Param in the template parameter list.
1765///
1766/// \returns the substituted template argument, or NULL if an error occurred.
1767static Sema::OwningExprResult
1768SubstDefaultTemplateArgument(Sema &SemaRef,
1769 TemplateDecl *Template,
1770 SourceLocation TemplateLoc,
1771 SourceLocation RAngleLoc,
1772 NonTypeTemplateParmDecl *Param,
1773 TemplateArgumentListBuilder &Converted) {
1774 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1775 /*TakeArgs=*/false);
1776
1777 MultiLevelTemplateArgumentList AllTemplateArgs
1778 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1779
1780 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1781 Template, Converted.getFlatArguments(),
1782 Converted.flatSize(),
1783 SourceRange(TemplateLoc, RAngleLoc));
1784
1785 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1786}
1787
Douglas Gregor788cd062009-11-11 01:00:40 +00001788/// \brief Substitute template arguments into the default template argument for
1789/// the given template template parameter.
1790///
1791/// \param SemaRef the semantic analysis object for which we are performing
1792/// the substitution.
1793///
1794/// \param Template the template that we are synthesizing template arguments
1795/// for.
1796///
1797/// \param TemplateLoc the location of the template name that started the
1798/// template-id we are checking.
1799///
1800/// \param RAngleLoc the location of the right angle bracket ('>') that
1801/// terminates the template-id.
1802///
1803/// \param Param the template template parameter whose default we are
1804/// substituting into.
1805///
1806/// \param Converted the list of template arguments provided for template
1807/// parameters that precede \p Param in the template parameter list.
1808///
1809/// \returns the substituted template argument, or NULL if an error occurred.
1810static TemplateName
1811SubstDefaultTemplateArgument(Sema &SemaRef,
1812 TemplateDecl *Template,
1813 SourceLocation TemplateLoc,
1814 SourceLocation RAngleLoc,
1815 TemplateTemplateParmDecl *Param,
1816 TemplateArgumentListBuilder &Converted) {
1817 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1818 /*TakeArgs=*/false);
1819
1820 MultiLevelTemplateArgumentList AllTemplateArgs
1821 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1822
1823 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1824 Template, Converted.getFlatArguments(),
1825 Converted.flatSize(),
1826 SourceRange(TemplateLoc, RAngleLoc));
1827
1828 return SemaRef.SubstTemplateName(
1829 Param->getDefaultArgument().getArgument().getAsTemplate(),
1830 Param->getDefaultArgument().getTemplateNameLoc(),
1831 AllTemplateArgs);
1832}
1833
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001834/// \brief If the given template parameter has a default template
1835/// argument, substitute into that default template argument and
1836/// return the corresponding template argument.
1837TemplateArgumentLoc
1838Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1839 SourceLocation TemplateLoc,
1840 SourceLocation RAngleLoc,
1841 Decl *Param,
1842 TemplateArgumentListBuilder &Converted) {
1843 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1844 if (!TypeParm->hasDefaultArgument())
1845 return TemplateArgumentLoc();
1846
John McCalla93c9342009-12-07 02:54:59 +00001847 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001848 TemplateLoc,
1849 RAngleLoc,
1850 TypeParm,
1851 Converted);
1852 if (DI)
1853 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1854
1855 return TemplateArgumentLoc();
1856 }
1857
1858 if (NonTypeTemplateParmDecl *NonTypeParm
1859 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1860 if (!NonTypeParm->hasDefaultArgument())
1861 return TemplateArgumentLoc();
1862
1863 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1864 TemplateLoc,
1865 RAngleLoc,
1866 NonTypeParm,
1867 Converted);
1868 if (Arg.isInvalid())
1869 return TemplateArgumentLoc();
1870
1871 Expr *ArgE = Arg.takeAs<Expr>();
1872 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1873 }
1874
1875 TemplateTemplateParmDecl *TempTempParm
1876 = cast<TemplateTemplateParmDecl>(Param);
1877 if (!TempTempParm->hasDefaultArgument())
1878 return TemplateArgumentLoc();
1879
1880 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1881 TemplateLoc,
1882 RAngleLoc,
1883 TempTempParm,
1884 Converted);
1885 if (TName.isNull())
1886 return TemplateArgumentLoc();
1887
1888 return TemplateArgumentLoc(TemplateArgument(TName),
1889 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1890 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1891}
1892
Douglas Gregore7526412009-11-11 19:31:23 +00001893/// \brief Check that the given template argument corresponds to the given
1894/// template parameter.
1895bool Sema::CheckTemplateArgument(NamedDecl *Param,
1896 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00001897 TemplateDecl *Template,
1898 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00001899 SourceLocation RAngleLoc,
Douglas Gregor02024a92010-03-28 02:42:43 +00001900 TemplateArgumentListBuilder &Converted,
1901 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00001902 // Check template type parameters.
1903 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00001904 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00001905
Douglas Gregord9e15302009-11-11 19:41:09 +00001906 // Check non-type template parameters.
1907 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00001908 // Do substitution on the type of the non-type template parameter
1909 // with the template arguments we've seen thus far.
1910 QualType NTTPType = NTTP->getType();
1911 if (NTTPType->isDependentType()) {
1912 // Do substitution on the type of the non-type template parameter.
1913 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1914 NTTP, Converted.getFlatArguments(),
1915 Converted.flatSize(),
1916 SourceRange(TemplateLoc, RAngleLoc));
1917
1918 TemplateArgumentList TemplateArgs(Context, Converted,
1919 /*TakeArgs=*/false);
1920 NTTPType = SubstType(NTTPType,
1921 MultiLevelTemplateArgumentList(TemplateArgs),
1922 NTTP->getLocation(),
1923 NTTP->getDeclName());
1924 // If that worked, check the non-type template parameter type
1925 // for validity.
1926 if (!NTTPType.isNull())
1927 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1928 NTTP->getLocation());
1929 if (NTTPType.isNull())
1930 return true;
1931 }
1932
1933 switch (Arg.getArgument().getKind()) {
1934 case TemplateArgument::Null:
1935 assert(false && "Should never see a NULL template argument here");
1936 return true;
1937
1938 case TemplateArgument::Expression: {
1939 Expr *E = Arg.getArgument().getAsExpr();
1940 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00001941 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00001942 return true;
1943
1944 Converted.Append(Result);
1945 break;
1946 }
1947
1948 case TemplateArgument::Declaration:
1949 case TemplateArgument::Integral:
1950 // We've already checked this template argument, so just copy
1951 // it to the list of converted arguments.
1952 Converted.Append(Arg.getArgument());
1953 break;
1954
1955 case TemplateArgument::Template:
1956 // We were given a template template argument. It may not be ill-formed;
1957 // see below.
1958 if (DependentTemplateName *DTN
1959 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1960 // We have a template argument such as \c T::template X, which we
1961 // parsed as a template template argument. However, since we now
1962 // know that we need a non-type template argument, convert this
1963 // template name into an expression.
John McCallf7a1a742009-11-24 19:00:30 +00001964 Expr *E = DependentScopeDeclRefExpr::Create(Context,
1965 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00001966 Arg.getTemplateQualifierRange(),
John McCallf7a1a742009-11-24 19:00:30 +00001967 DTN->getIdentifier(),
1968 Arg.getTemplateNameLoc());
Douglas Gregore7526412009-11-11 19:31:23 +00001969
1970 TemplateArgument Result;
1971 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1972 return true;
1973
1974 Converted.Append(Result);
1975 break;
1976 }
1977
1978 // We have a template argument that actually does refer to a class
1979 // template, template alias, or template template parameter, and
1980 // therefore cannot be a non-type template argument.
1981 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1982 << Arg.getSourceRange();
1983
1984 Diag(Param->getLocation(), diag::note_template_param_here);
1985 return true;
1986
1987 case TemplateArgument::Type: {
1988 // We have a non-type template parameter but the template
1989 // argument is a type.
1990
1991 // C++ [temp.arg]p2:
1992 // In a template-argument, an ambiguity between a type-id and
1993 // an expression is resolved to a type-id, regardless of the
1994 // form of the corresponding template-parameter.
1995 //
1996 // We warn specifically about this case, since it can be rather
1997 // confusing for users.
1998 QualType T = Arg.getArgument().getAsType();
1999 SourceRange SR = Arg.getSourceRange();
2000 if (T->isFunctionType())
2001 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2002 else
2003 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2004 Diag(Param->getLocation(), diag::note_template_param_here);
2005 return true;
2006 }
2007
2008 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002009 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002010 break;
2011 }
2012
2013 return false;
2014 }
2015
2016
2017 // Check template template parameters.
2018 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2019
2020 // Substitute into the template parameter list of the template
2021 // template parameter, since previously-supplied template arguments
2022 // may appear within the template template parameter.
2023 {
2024 // Set up a template instantiation context.
2025 LocalInstantiationScope Scope(*this);
2026 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2027 TempParm, Converted.getFlatArguments(),
2028 Converted.flatSize(),
2029 SourceRange(TemplateLoc, RAngleLoc));
2030
2031 TemplateArgumentList TemplateArgs(Context, Converted,
2032 /*TakeArgs=*/false);
2033 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2034 SubstDecl(TempParm, CurContext,
2035 MultiLevelTemplateArgumentList(TemplateArgs)));
2036 if (!TempParm)
2037 return true;
2038
2039 // FIXME: TempParam is leaked.
2040 }
2041
2042 switch (Arg.getArgument().getKind()) {
2043 case TemplateArgument::Null:
2044 assert(false && "Should never see a NULL template argument here");
2045 return true;
2046
2047 case TemplateArgument::Template:
2048 if (CheckTemplateArgument(TempParm, Arg))
2049 return true;
2050
2051 Converted.Append(Arg.getArgument());
2052 break;
2053
2054 case TemplateArgument::Expression:
2055 case TemplateArgument::Type:
2056 // We have a template template parameter but the template
2057 // argument does not refer to a template.
2058 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2059 return true;
2060
2061 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002062 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002063 "Declaration argument with template template parameter");
2064 break;
2065 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002066 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002067 "Integral argument with template template parameter");
2068 break;
2069
2070 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002071 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002072 break;
2073 }
2074
2075 return false;
2076}
2077
Douglas Gregorc15cb382009-02-09 23:23:08 +00002078/// \brief Check that the given template argument list is well-formed
2079/// for specializing the given template.
2080bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2081 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002082 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002083 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002084 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002085 TemplateParameterList *Params = Template->getTemplateParameters();
2086 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002087 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002088 bool Invalid = false;
2089
John McCalld5532b62009-11-23 01:53:49 +00002090 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2091
Mike Stump1eb44332009-09-09 15:08:12 +00002092 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002093 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002095 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002096 (NumArgs < Params->getMinRequiredArguments() &&
2097 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002098 // FIXME: point at either the first arg beyond what we can handle,
2099 // or the '>', depending on whether we have too many or too few
2100 // arguments.
2101 SourceRange Range;
2102 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002103 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002104 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2105 << (NumArgs > NumParams)
2106 << (isa<ClassTemplateDecl>(Template)? 0 :
2107 isa<FunctionTemplateDecl>(Template)? 1 :
2108 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2109 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002110 Diag(Template->getLocation(), diag::note_template_decl_here)
2111 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002112 Invalid = true;
2113 }
Mike Stump1eb44332009-09-09 15:08:12 +00002114
2115 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002116 // [...] The type and form of each template-argument specified in
2117 // a template-id shall match the type and form specified for the
2118 // corresponding parameter declared by the template in its
2119 // template-parameter-list.
2120 unsigned ArgIdx = 0;
2121 for (TemplateParameterList::iterator Param = Params->begin(),
2122 ParamEnd = Params->end();
2123 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002124 if (ArgIdx > NumArgs && PartialTemplateArgs)
2125 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Douglas Gregord9e15302009-11-11 19:41:09 +00002127 // If we have a template parameter pack, check every remaining template
2128 // argument against that template parameter pack.
2129 if ((*Param)->isTemplateParameterPack()) {
2130 Converted.BeginPack();
2131 for (; ArgIdx < NumArgs; ++ArgIdx) {
2132 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2133 TemplateLoc, RAngleLoc, Converted)) {
2134 Invalid = true;
2135 break;
2136 }
2137 }
2138 Converted.EndPack();
2139 continue;
2140 }
2141
Douglas Gregorf35f8282009-11-11 21:54:23 +00002142 if (ArgIdx < NumArgs) {
2143 // Check the template argument we were given.
2144 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2145 TemplateLoc, RAngleLoc, Converted))
2146 return true;
2147
2148 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002149 }
Douglas Gregore7526412009-11-11 19:31:23 +00002150
Douglas Gregorf35f8282009-11-11 21:54:23 +00002151 // We have a default template argument that we will use.
2152 TemplateArgumentLoc Arg;
2153
2154 // Retrieve the default template argument from the template
2155 // parameter. For each kind of template parameter, we substitute the
2156 // template arguments provided thus far and any "outer" template arguments
2157 // (when the template parameter was part of a nested template) into
2158 // the default argument.
2159 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2160 if (!TTP->hasDefaultArgument()) {
2161 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2162 break;
2163 }
2164
John McCalla93c9342009-12-07 02:54:59 +00002165 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002166 Template,
2167 TemplateLoc,
2168 RAngleLoc,
2169 TTP,
2170 Converted);
2171 if (!ArgType)
2172 return true;
2173
2174 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2175 ArgType);
2176 } else if (NonTypeTemplateParmDecl *NTTP
2177 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2178 if (!NTTP->hasDefaultArgument()) {
2179 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2180 break;
2181 }
2182
2183 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2184 TemplateLoc,
2185 RAngleLoc,
2186 NTTP,
2187 Converted);
2188 if (E.isInvalid())
2189 return true;
2190
2191 Expr *Ex = E.takeAs<Expr>();
2192 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2193 } else {
2194 TemplateTemplateParmDecl *TempParm
2195 = cast<TemplateTemplateParmDecl>(*Param);
2196
2197 if (!TempParm->hasDefaultArgument()) {
2198 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2199 break;
2200 }
2201
2202 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2203 TemplateLoc,
2204 RAngleLoc,
2205 TempParm,
2206 Converted);
2207 if (Name.isNull())
2208 return true;
2209
2210 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2211 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2212 TempParm->getDefaultArgument().getTemplateNameLoc());
2213 }
2214
2215 // Introduce an instantiation record that describes where we are using
2216 // the default template argument.
2217 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2218 Converted.getFlatArguments(),
2219 Converted.flatSize(),
2220 SourceRange(TemplateLoc, RAngleLoc));
2221
2222 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002223 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002224 RAngleLoc, Converted))
2225 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002226 }
2227
2228 return Invalid;
2229}
2230
2231/// \brief Check a template argument against its corresponding
2232/// template type parameter.
2233///
2234/// This routine implements the semantics of C++ [temp.arg.type]. It
2235/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002236bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002237 TypeSourceInfo *ArgInfo) {
2238 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002239 QualType Arg = ArgInfo->getType();
2240
Douglas Gregorc15cb382009-02-09 23:23:08 +00002241 // C++ [temp.arg.type]p2:
2242 // A local type, a type with no linkage, an unnamed type or a type
2243 // compounded from any of these types shall not be used as a
2244 // template-argument for a template type-parameter.
2245 //
2246 // FIXME: Perform the recursive and no-linkage type checks.
2247 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00002248 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002249 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00002250 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002251 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00002252 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2253 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2254 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2255 << QualType(Tag, 0) << SR;
2256 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00002257 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall833ca992009-10-29 08:12:44 +00002258 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2259 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002260 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2261 return true;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002262 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2263 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2264 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002265 }
2266
2267 return false;
2268}
2269
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002270/// \brief Checks whether the given template argument is the address
2271/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002272bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2273 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002274 bool Invalid = false;
2275
2276 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002277 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002278 Arg = Cast->getSubExpr();
2279
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002280 // C++0x allows nullptr, and there's no further checking to be done for that.
2281 if (Arg->getType()->isNullPtrType())
2282 return false;
2283
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002284 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002285 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002286 // A template-argument for a non-type, non-template
2287 // template-parameter shall be one of: [...]
2288 //
2289 // -- the address of an object or function with external
2290 // linkage, including function templates and function
2291 // template-ids but excluding non-static class members,
2292 // expressed as & id-expression where the & is optional if
2293 // the name refers to a function or array, or if the
2294 // corresponding template-parameter is a reference; or
2295 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002296
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002297 // Ignore (and complain about) any excess parentheses.
2298 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2299 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002300 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002301 diag::err_template_arg_extra_parens)
2302 << Arg->getSourceRange();
2303 Invalid = true;
2304 }
2305
2306 Arg = Parens->getSubExpr();
2307 }
2308
2309 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2310 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2311 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2312 } else
2313 DRE = dyn_cast<DeclRefExpr>(Arg);
2314
Chandler Carruth038cc392010-01-31 10:01:20 +00002315 if (!DRE)
2316 return Diag(Arg->getSourceRange().getBegin(),
2317 diag::err_template_arg_not_decl_ref)
2318 << Arg->getSourceRange();
2319
2320 // Stop checking the precise nature of the argument if it is value dependent,
2321 // it should be checked when instantiated.
2322 if (Arg->isValueDependent())
2323 return false;
2324
2325 if (!isa<ValueDecl>(DRE->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00002326 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002327 diag::err_template_arg_not_object_or_func_form)
2328 << Arg->getSourceRange();
2329
2330 // Cannot refer to non-static data members
2331 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2332 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2333 << Field << Arg->getSourceRange();
2334
2335 // Cannot refer to non-static member functions
2336 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2337 if (!Method->isStatic())
Mike Stump1eb44332009-09-09 15:08:12 +00002338 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002339 diag::err_template_arg_method)
2340 << Method << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002341
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002342 // Functions must have external linkage.
2343 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002344 if (!isExternalLinkage(Func->getLinkage())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002345 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002346 diag::err_template_arg_function_not_extern)
2347 << Func << Arg->getSourceRange();
2348 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2349 << true;
2350 return true;
2351 }
2352
2353 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002354 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002355 return Invalid;
2356 }
2357
2358 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002359 if (!isExternalLinkage(Var->getLinkage())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002360 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002361 diag::err_template_arg_object_not_extern)
2362 << Var << Arg->getSourceRange();
2363 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2364 << true;
2365 return true;
2366 }
2367
2368 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002369 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002370 return Invalid;
2371 }
Mike Stump1eb44332009-09-09 15:08:12 +00002372
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002373 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002374 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002375 diag::err_template_arg_not_object_or_func)
2376 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002377 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002378 diag::note_template_arg_refers_here);
2379 return true;
2380}
2381
2382/// \brief Checks whether the given template argument is a pointer to
2383/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002384bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2385 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002386 bool Invalid = false;
2387
2388 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002389 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002390 Arg = Cast->getSubExpr();
2391
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002392 // C++0x allows nullptr, and there's no further checking to be done for that.
2393 if (Arg->getType()->isNullPtrType())
2394 return false;
2395
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002396 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002397 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002398 // A template-argument for a non-type, non-template
2399 // template-parameter shall be one of: [...]
2400 //
2401 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002402 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002403
2404 // Ignore (and complain about) any excess parentheses.
2405 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2406 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002407 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002408 diag::err_template_arg_extra_parens)
2409 << Arg->getSourceRange();
2410 Invalid = true;
2411 }
2412
2413 Arg = Parens->getSubExpr();
2414 }
2415
Douglas Gregorcaddba02009-11-12 18:38:13 +00002416 // A pointer-to-member constant written &Class::member.
2417 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002418 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2419 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2420 if (DRE && !DRE->getQualifier())
2421 DRE = 0;
2422 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002423 }
2424 // A constant of pointer-to-member type.
2425 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2426 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2427 if (VD->getType()->isMemberPointerType()) {
2428 if (isa<NonTypeTemplateParmDecl>(VD) ||
2429 (isa<VarDecl>(VD) &&
2430 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2431 if (Arg->isTypeDependent() || Arg->isValueDependent())
2432 Converted = TemplateArgument(Arg->Retain());
2433 else
2434 Converted = TemplateArgument(VD->getCanonicalDecl());
2435 return Invalid;
2436 }
2437 }
2438 }
2439
2440 DRE = 0;
2441 }
2442
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002443 if (!DRE)
2444 return Diag(Arg->getSourceRange().getBegin(),
2445 diag::err_template_arg_not_pointer_to_member_form)
2446 << Arg->getSourceRange();
2447
2448 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2449 assert((isa<FieldDecl>(DRE->getDecl()) ||
2450 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2451 "Only non-static member pointers can make it here");
2452
2453 // Okay: this is the address of a non-static member, and therefore
2454 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002455 if (Arg->isTypeDependent() || Arg->isValueDependent())
2456 Converted = TemplateArgument(Arg->Retain());
2457 else
2458 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002459 return Invalid;
2460 }
2461
2462 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002463 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002464 diag::err_template_arg_not_pointer_to_member_form)
2465 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002466 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002467 diag::note_template_arg_refers_here);
2468 return true;
2469}
2470
Douglas Gregorc15cb382009-02-09 23:23:08 +00002471/// \brief Check a template argument against its corresponding
2472/// non-type template parameter.
2473///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002474/// This routine implements the semantics of C++ [temp.arg.nontype].
2475/// It returns true if an error occurred, and false otherwise. \p
2476/// InstantiatedParamType is the type of the non-type template
2477/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002478///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002479/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002480bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002481 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00002482 TemplateArgument &Converted,
2483 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002484 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2485
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002486 // If either the parameter has a dependent type or the argument is
2487 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002488 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00002489 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2490 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002491 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002492 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002493 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002494
2495 // C++ [temp.arg.nontype]p5:
2496 // The following conversions are performed on each expression used
2497 // as a non-type template-argument. If a non-type
2498 // template-argument cannot be converted to the type of the
2499 // corresponding template-parameter then the program is
2500 // ill-formed.
2501 //
2502 // -- for a non-type template-parameter of integral or
2503 // enumeration type, integral promotions (4.5) and integral
2504 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002505 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002506 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002507 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002508 // C++ [temp.arg.nontype]p1:
2509 // A template-argument for a non-type, non-template
2510 // template-parameter shall be one of:
2511 //
2512 // -- an integral constant-expression of integral or enumeration
2513 // type; or
2514 // -- the name of a non-type template-parameter; or
2515 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002516 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002517 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002518 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002519 diag::err_template_arg_not_integral_or_enumeral)
2520 << ArgType << Arg->getSourceRange();
2521 Diag(Param->getLocation(), diag::note_template_param_here);
2522 return true;
2523 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002524 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002525 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2526 << ArgType << Arg->getSourceRange();
2527 return true;
2528 }
2529
Douglas Gregor02024a92010-03-28 02:42:43 +00002530 // From here on out, all we care about are the unqualified forms
2531 // of the parameter and argument types.
2532 ParamType = ParamType.getUnqualifiedType();
2533 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002534
2535 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002536 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002537 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00002538 } else if (CTAK == CTAK_Deduced) {
2539 // C++ [temp.deduct.type]p17:
2540 // If, in the declaration of a function template with a non-type
2541 // template-parameter, the non-type template- parameter is used
2542 // in an expression in the function parameter-list and, if the
2543 // corresponding template-argument is deduced, the
2544 // template-argument type shall match the type of the
2545 // template-parameter exactly, except that a template-argument
2546 // deduced from an array bound may be of any integral type.
2547 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2548 << ArgType << ParamType;
2549 Diag(Param->getLocation(), diag::note_template_param_here);
2550 return true;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002551 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2552 !ParamType->isEnumeralType()) {
2553 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002554 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002555 } else {
2556 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002557 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002558 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002559 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002560 Diag(Param->getLocation(), diag::note_template_param_here);
2561 return true;
2562 }
2563
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002564 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002565 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002566 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002567
2568 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002569 llvm::APSInt OldValue = Value;
2570
2571 // Coerce the template argument's value to the value it will have
2572 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002573 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002574 if (Value.getBitWidth() != AllowedBits)
2575 Value.extOrTrunc(AllowedBits);
2576 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002577
2578 // Complain if an unsigned parameter received a negative value.
2579 if (IntegerType->isUnsignedIntegerType()
2580 && (OldValue.isSigned() && OldValue.isNegative())) {
2581 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2582 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2583 << Arg->getSourceRange();
2584 Diag(Param->getLocation(), diag::note_template_param_here);
2585 }
2586
2587 // Complain if we overflowed the template parameter's type.
2588 unsigned RequiredBits;
2589 if (IntegerType->isUnsignedIntegerType())
2590 RequiredBits = OldValue.getActiveBits();
2591 else if (OldValue.isUnsigned())
2592 RequiredBits = OldValue.getActiveBits() + 1;
2593 else
2594 RequiredBits = OldValue.getMinSignedBits();
2595 if (RequiredBits > AllowedBits) {
2596 Diag(Arg->getSourceRange().getBegin(),
2597 diag::warn_template_arg_too_large)
2598 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2599 << Arg->getSourceRange();
2600 Diag(Param->getLocation(), diag::note_template_param_here);
2601 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002602 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002603
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002604 // Add the value of this argument to the list of converted
2605 // arguments. We use the bitwidth and signedness of the template
2606 // parameter.
2607 if (Arg->isValueDependent()) {
2608 // The argument is value-dependent. Create a new
2609 // TemplateArgument with the converted expression.
2610 Converted = TemplateArgument(Arg);
2611 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002612 }
2613
John McCall833ca992009-10-29 08:12:44 +00002614 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002615 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002616 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002617 return false;
2618 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002619
John McCall6bb80172010-03-30 21:47:33 +00002620 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2621
Douglas Gregorb86b0572009-02-11 01:18:59 +00002622 // Handle pointer-to-function, reference-to-function, and
2623 // pointer-to-member-function all in (roughly) the same way.
2624 if (// -- For a non-type template-parameter of type pointer to
2625 // function, only the function-to-pointer conversion (4.3) is
2626 // applied. If the template-argument represents a set of
2627 // overloaded functions (or a pointer to such), the matching
2628 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002629 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002630 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002631 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002632 // -- For a non-type template-parameter of type reference to
2633 // function, no conversions apply. If the template-argument
2634 // represents a set of overloaded functions, the matching
2635 // function is selected from the set (13.4).
2636 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002637 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002638 // -- For a non-type template-parameter of type pointer to
2639 // member function, no conversions apply. If the
2640 // template-argument represents a set of overloaded member
2641 // functions, the matching member function is selected from
2642 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002643 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002644 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002645 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002646 ->isFunctionType())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002647 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002648 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002649 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002650 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2651 ParamType->isMemberPointerType())) {
2652 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002653 if (ParamType->isMemberPointerType())
2654 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2655 else
2656 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002657 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002658 ArgType = Context.getPointerType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002659 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump1eb44332009-09-09 15:08:12 +00002660 } else if (FunctionDecl *Fn
John McCall6bb80172010-03-30 21:47:33 +00002661 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true,
2662 FoundResult)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002663 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2664 return true;
2665
John McCall6bb80172010-03-30 21:47:33 +00002666 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00002667 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002668 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002669 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman73c39ab2009-10-20 08:27:19 +00002670 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregora35284b2009-02-11 00:19:33 +00002671 }
2672 }
2673
Mike Stump1eb44332009-09-09 15:08:12 +00002674 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002675 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002676 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002677 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002678 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002679 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002680 Diag(Param->getLocation(), diag::note_template_param_here);
2681 return true;
2682 }
Mike Stump1eb44332009-09-09 15:08:12 +00002683
Douglas Gregorcaddba02009-11-12 18:38:13 +00002684 if (ParamType->isMemberPointerType())
2685 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump1eb44332009-09-09 15:08:12 +00002686
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002687 NamedDecl *Entity = 0;
2688 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2689 return true;
2690
Chandler Carruth038cc392010-01-31 10:01:20 +00002691 if (Arg->isValueDependent()) {
2692 Converted = TemplateArgument(Arg);
2693 } else {
2694 if (Entity)
2695 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2696 Converted = TemplateArgument(Entity);
2697 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002698 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00002699 }
2700
Chris Lattnerfe90de72009-02-20 21:37:53 +00002701 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002702 // -- for a non-type template-parameter of type pointer to
2703 // object, qualification conversions (4.4) and the
2704 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002705 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002706 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002707 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002708
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002709 if (ArgType->isNullPtrType()) {
2710 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002711 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002712 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002713 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002714 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002715 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002716
Douglas Gregorb86b0572009-02-11 01:18:59 +00002717 if (IsQualificationConversion(ArgType, ParamType)) {
2718 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002719 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002720 }
Mike Stump1eb44332009-09-09 15:08:12 +00002721
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002722 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002723 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002724 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002725 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002726 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002727 Diag(Param->getLocation(), diag::note_template_param_here);
2728 return true;
2729 }
Mike Stump1eb44332009-09-09 15:08:12 +00002730
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002731 NamedDecl *Entity = 0;
2732 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2733 return true;
2734
Chandler Carruth038cc392010-01-31 10:01:20 +00002735 if (Arg->isValueDependent()) {
2736 Converted = TemplateArgument(Arg);
2737 } else {
2738 if (Entity)
2739 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2740 Converted = TemplateArgument(Entity);
2741 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002742 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002743 }
Mike Stump1eb44332009-09-09 15:08:12 +00002744
Ted Kremenek6217b802009-07-29 21:53:49 +00002745 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002746 // -- For a non-type template-parameter of type reference to
2747 // object, no conversions apply. The type referred to by the
2748 // reference may be more cv-qualified than the (otherwise
2749 // identical) type of the template-argument. The
2750 // template-parameter is bound directly to the
2751 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002752 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002753 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002754
Chandler Carruth5147fa62010-02-03 09:37:33 +00002755 QualType ReferredType = ParamRefType->getPointeeType();
2756 if (!Context.hasSameUnqualifiedType(ReferredType, ArgType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002757 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002758 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002759 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002760 << Arg->getSourceRange();
2761 Diag(Param->getLocation(), diag::note_template_param_here);
2762 return true;
2763 }
2764
Mike Stump1eb44332009-09-09 15:08:12 +00002765 unsigned ParamQuals
Chandler Carruth5147fa62010-02-03 09:37:33 +00002766 = Context.getCanonicalType(ReferredType).getCVRQualifiers();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002767 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00002768
Douglas Gregorb86b0572009-02-11 01:18:59 +00002769 if ((ParamQuals | ArgQuals) != ParamQuals) {
2770 Diag(Arg->getSourceRange().getBegin(),
2771 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002772 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002773 << Arg->getSourceRange();
2774 Diag(Param->getLocation(), diag::note_template_param_here);
2775 return true;
2776 }
Mike Stump1eb44332009-09-09 15:08:12 +00002777
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002778 NamedDecl *Entity = 0;
2779 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2780 return true;
2781
Chandler Carruth038cc392010-01-31 10:01:20 +00002782 if (Arg->isValueDependent()) {
2783 Converted = TemplateArgument(Arg);
2784 } else {
2785 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2786 Converted = TemplateArgument(Entity);
2787 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002788 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002789 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002790
2791 // -- For a non-type template-parameter of type pointer to data
2792 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002793 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00002794 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2795
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002796 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002797 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002798 } else if (ArgType->isNullPtrType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002799 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002800 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002801 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002802 } else {
2803 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002804 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00002805 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002806 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00002807 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002808 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00002809 }
2810
Douglas Gregorcaddba02009-11-12 18:38:13 +00002811 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002812}
2813
2814/// \brief Check a template argument against its corresponding
2815/// template template parameter.
2816///
2817/// This routine implements the semantics of C++ [temp.arg.template].
2818/// It returns true if an error occurred, and false otherwise.
2819bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00002820 const TemplateArgumentLoc &Arg) {
2821 TemplateName Name = Arg.getArgument().getAsTemplate();
2822 TemplateDecl *Template = Name.getAsTemplateDecl();
2823 if (!Template) {
2824 // Any dependent template name is fine.
2825 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2826 return false;
2827 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002828
2829 // C++ [temp.arg.template]p1:
2830 // A template-argument for a template template-parameter shall be
2831 // the name of a class template, expressed as id-expression. Only
2832 // primary class templates are considered when matching the
2833 // template template argument with the corresponding parameter;
2834 // partial specializations are not considered even if their
2835 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002836 //
2837 // Note that we also allow template template parameters here, which
2838 // will happen when we are dealing with, e.g., class template
2839 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00002840 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002841 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002842 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00002843 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00002844 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00002845 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002846 << Template;
2847 }
2848
2849 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2850 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00002851 true,
2852 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00002853 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00002854}
2855
Douglas Gregor02024a92010-03-28 02:42:43 +00002856/// \brief Given a non-type template argument that refers to a
2857/// declaration and the type of its corresponding non-type template
2858/// parameter, produce an expression that properly refers to that
2859/// declaration.
2860Sema::OwningExprResult
2861Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
2862 QualType ParamType,
2863 SourceLocation Loc) {
2864 assert(Arg.getKind() == TemplateArgument::Declaration &&
2865 "Only declaration template arguments permitted here");
2866 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
2867
2868 if (VD->getDeclContext()->isRecord() &&
2869 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
2870 // If the value is a class member, we might have a pointer-to-member.
2871 // Determine whether the non-type template template parameter is of
2872 // pointer-to-member type. If so, we need to build an appropriate
2873 // expression for a pointer-to-member, since a "normal" DeclRefExpr
2874 // would refer to the member itself.
2875 if (ParamType->isMemberPointerType()) {
2876 QualType ClassType
2877 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
2878 NestedNameSpecifier *Qualifier
2879 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
2880 CXXScopeSpec SS;
2881 SS.setScopeRep(Qualifier);
2882 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
2883 VD->getType().getNonReferenceType(),
2884 Loc,
2885 &SS);
2886 if (RefExpr.isInvalid())
2887 return ExprError();
2888
2889 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
2890 assert(!RefExpr.isInvalid() &&
2891 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
2892 ParamType));
2893 return move(RefExpr);
2894 }
2895 }
2896
2897 QualType T = VD->getType().getNonReferenceType();
2898 if (ParamType->isPointerType()) {
2899 // C++03 [temp.arg.nontype]p5:
2900 // - For a non-type template-parameter of type pointer to
2901 // object, qualification conversions and the array-to-pointer
2902 // conversion are applied.
2903 // - For a non-type template-parameter of type pointer to
2904 // function, only the function-to-pointer conversion is
2905 // applied.
2906 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
2907 if (RefExpr.isInvalid())
2908 return ExprError();
2909
2910 // Decay functions and arrays.
2911 Expr *RefE = (Expr *)RefExpr.get();
2912 DefaultFunctionArrayConversion(RefE);
2913 if (RefE != RefExpr.get()) {
2914 RefExpr.release();
2915 RefExpr = Owned(RefE);
2916 }
2917
2918 // Qualification conversions.
2919 RefExpr.release();
2920 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CastExpr::CK_NoOp);
2921 return Owned(RefE);
2922 }
2923
2924 // If the non-type template parameter has reference type, qualify the
2925 // resulting declaration reference with the extra qualifiers on the
2926 // type that the reference refers to.
2927 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
2928 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
2929
2930 return BuildDeclRefExpr(VD, T, Loc);
2931}
2932
2933/// \brief Construct a new expression that refers to the given
2934/// integral template argument with the given source-location
2935/// information.
2936///
2937/// This routine takes care of the mapping from an integral template
2938/// argument (which may have any integral type) to the appropriate
2939/// literal value.
2940Sema::OwningExprResult
2941Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
2942 SourceLocation Loc) {
2943 assert(Arg.getKind() == TemplateArgument::Integral &&
2944 "Operation is only value for integral template arguments");
2945 QualType T = Arg.getIntegralType();
2946 if (T->isCharType() || T->isWideCharType())
2947 return Owned(new (Context) CharacterLiteral(
2948 Arg.getAsIntegral()->getZExtValue(),
2949 T->isWideCharType(),
2950 T,
2951 Loc));
2952 if (T->isBooleanType())
2953 return Owned(new (Context) CXXBoolLiteralExpr(
2954 Arg.getAsIntegral()->getBoolValue(),
2955 T,
2956 Loc));
2957
2958 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
2959}
2960
2961
Douglas Gregorddc29e12009-02-06 22:42:48 +00002962/// \brief Determine whether the given template parameter lists are
2963/// equivalent.
2964///
Mike Stump1eb44332009-09-09 15:08:12 +00002965/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00002966/// source code as part of a new template declaration.
2967///
2968/// \param Old The old template parameter list, typically found via
2969/// name lookup of the template declared with this template parameter
2970/// list.
2971///
2972/// \param Complain If true, this routine will produce a diagnostic if
2973/// the template parameter lists are not equivalent.
2974///
Douglas Gregorfb898e12009-11-12 16:20:59 +00002975/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00002976///
2977/// \param TemplateArgLoc If this source location is valid, then we
2978/// are actually checking the template parameter list of a template
2979/// argument (New) against the template parameter list of its
2980/// corresponding template template parameter (Old). We produce
2981/// slightly different diagnostics in this scenario.
2982///
Douglas Gregorddc29e12009-02-06 22:42:48 +00002983/// \returns True if the template parameter lists are equal, false
2984/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002985bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00002986Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2987 TemplateParameterList *Old,
2988 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00002989 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002990 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002991 if (Old->size() != New->size()) {
2992 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002993 unsigned NextDiag = diag::err_template_param_list_different_arity;
2994 if (TemplateArgLoc.isValid()) {
2995 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2996 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00002997 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002998 Diag(New->getTemplateLoc(), NextDiag)
2999 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00003000 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003001 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00003002 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003003 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003004 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3005 }
3006
3007 return false;
3008 }
3009
3010 for (TemplateParameterList::iterator OldParm = Old->begin(),
3011 OldParmEnd = Old->end(), NewParm = New->begin();
3012 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3013 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003014 if (Complain) {
3015 unsigned NextDiag = diag::err_template_param_different_kind;
3016 if (TemplateArgLoc.isValid()) {
3017 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3018 NextDiag = diag::note_template_param_different_kind;
3019 }
3020 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003021 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003022 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003023 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00003024 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003025 return false;
3026 }
3027
3028 if (isa<TemplateTypeParmDecl>(*OldParm)) {
3029 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00003030 // know we're at the same index).
Mike Stump1eb44332009-09-09 15:08:12 +00003031 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003032 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3033 // The types of non-type template parameters must agree.
3034 NonTypeTemplateParmDecl *NewNTTP
3035 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00003036
3037 // If we are matching a template template argument to a template
3038 // template parameter and one of the non-type template parameter types
3039 // is dependent, then we must wait until template instantiation time
3040 // to actually compare the arguments.
3041 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3042 (OldNTTP->getType()->isDependentType() ||
3043 NewNTTP->getType()->isDependentType()))
3044 continue;
3045
Douglas Gregorddc29e12009-02-06 22:42:48 +00003046 if (Context.getCanonicalType(OldNTTP->getType()) !=
3047 Context.getCanonicalType(NewNTTP->getType())) {
3048 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003049 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3050 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003051 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003052 diag::err_template_arg_template_params_mismatch);
3053 NextDiag = diag::note_template_nontype_parm_different_type;
3054 }
3055 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003056 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00003057 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00003058 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00003059 diag::note_template_nontype_parm_prev_declaration)
3060 << OldNTTP->getType();
3061 }
3062 return false;
3063 }
3064 } else {
3065 // The template parameter lists of template template
3066 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00003067 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00003068 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00003069 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003070 = cast<TemplateTemplateParmDecl>(*OldParm);
3071 TemplateTemplateParmDecl *NewTTP
3072 = cast<TemplateTemplateParmDecl>(*NewParm);
3073 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3074 OldTTP->getTemplateParameters(),
3075 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003076 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00003077 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003078 return false;
3079 }
3080 }
3081
3082 return true;
3083}
3084
3085/// \brief Check whether a template can be declared within this scope.
3086///
3087/// If the template declaration is valid in this scope, returns
3088/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003089bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003090Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003091 // Find the nearest enclosing declaration scope.
3092 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3093 (S->getFlags() & Scope::TemplateParamScope) != 0)
3094 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003095
Douglas Gregorddc29e12009-02-06 22:42:48 +00003096 // C++ [temp]p2:
3097 // A template-declaration can appear only as a namespace scope or
3098 // class scope declaration.
3099 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003100 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3101 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003102 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003103 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003104
Eli Friedman1503f772009-07-31 01:43:05 +00003105 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003106 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003107
3108 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3109 return false;
3110
Mike Stump1eb44332009-09-09 15:08:12 +00003111 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003112 diag::err_template_outside_namespace_or_class_scope)
3113 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003114}
Douglas Gregorcc636682009-02-17 23:15:12 +00003115
Douglas Gregord5cb8762009-10-07 00:13:32 +00003116/// \brief Determine what kind of template specialization the given declaration
3117/// is.
3118static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3119 if (!D)
3120 return TSK_Undeclared;
3121
Douglas Gregorf6b11852009-10-08 15:14:33 +00003122 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3123 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003124 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3125 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003126 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3127 return Var->getTemplateSpecializationKind();
3128
Douglas Gregord5cb8762009-10-07 00:13:32 +00003129 return TSK_Undeclared;
3130}
3131
Douglas Gregor9302da62009-10-14 23:50:59 +00003132/// \brief Check whether a specialization is well-formed in the current
3133/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003134///
Douglas Gregor9302da62009-10-14 23:50:59 +00003135/// This routine determines whether a template specialization can be declared
3136/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003137///
3138/// \param S the semantic analysis object for which this check is being
3139/// performed.
3140///
3141/// \param Specialized the entity being specialized or instantiated, which
3142/// may be a kind of template (class template, function template, etc.) or
3143/// a member of a class template (member function, static data member,
3144/// member class).
3145///
3146/// \param PrevDecl the previous declaration of this entity, if any.
3147///
3148/// \param Loc the location of the explicit specialization or instantiation of
3149/// this entity.
3150///
3151/// \param IsPartialSpecialization whether this is a partial specialization of
3152/// a class template.
3153///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003154/// \returns true if there was an error that we cannot recover from, false
3155/// otherwise.
3156static bool CheckTemplateSpecializationScope(Sema &S,
3157 NamedDecl *Specialized,
3158 NamedDecl *PrevDecl,
3159 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003160 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003161 // Keep these "kind" numbers in sync with the %select statements in the
3162 // various diagnostics emitted by this routine.
3163 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003164 bool isTemplateSpecialization = false;
3165 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003166 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003167 isTemplateSpecialization = true;
3168 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003169 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003170 isTemplateSpecialization = true;
3171 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003172 EntityKind = 3;
3173 else if (isa<VarDecl>(Specialized))
3174 EntityKind = 4;
3175 else if (isa<RecordDecl>(Specialized))
3176 EntityKind = 5;
3177 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003178 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3179 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003180 return true;
3181 }
3182
Douglas Gregor88b70942009-02-25 22:02:03 +00003183 // C++ [temp.expl.spec]p2:
3184 // An explicit specialization shall be declared in the namespace
3185 // of which the template is a member, or, for member templates, in
3186 // the namespace of which the enclosing class or enclosing class
3187 // template is a member. An explicit specialization of a member
3188 // function, member class or static data member of a class
3189 // template shall be declared in the namespace of which the class
3190 // template is a member. Such a declaration may also be a
3191 // definition. If the declaration is not a definition, the
3192 // specialization may be defined later in the name- space in which
3193 // the explicit specialization was declared, or in a namespace
3194 // that encloses the one in which the explicit specialization was
3195 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003196 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3197 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003198 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003199 return true;
3200 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003201
Douglas Gregor0a407472009-10-07 17:30:37 +00003202 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3203 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003204 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003205 return true;
3206 }
3207
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003208 // C++ [temp.class.spec]p6:
3209 // A class template partial specialization may be declared or redeclared
3210 // in any namespace scope in which its definition may be defined (14.5.1
3211 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003212 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003213 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003214 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003215 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003216 if ((!PrevDecl ||
3217 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3218 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3219 // There is no prior declaration of this entity, so this
3220 // specialization must be in the same context as the template
3221 // itself.
3222 if (!DC->Equals(SpecializedContext)) {
3223 if (isa<TranslationUnitDecl>(SpecializedContext))
3224 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3225 << EntityKind << Specialized;
3226 else if (isa<NamespaceDecl>(SpecializedContext))
3227 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3228 << EntityKind << Specialized
3229 << cast<NamedDecl>(SpecializedContext);
3230
3231 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3232 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003233 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003234 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003235
3236 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003237 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003238 // Note that HandleDeclarator() performs this check for explicit
3239 // specializations of function templates, static data members, and member
3240 // functions, so we skip the check here for those kinds of entities.
3241 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003242 // Should we refactor that check, so that it occurs later?
3243 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003244 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3245 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003246 if (isa<TranslationUnitDecl>(SpecializedContext))
3247 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3248 << EntityKind << Specialized;
3249 else if (isa<NamespaceDecl>(SpecializedContext))
3250 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3251 << EntityKind << Specialized
3252 << cast<NamedDecl>(SpecializedContext);
3253
Douglas Gregor9302da62009-10-14 23:50:59 +00003254 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003255 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003256
3257 // FIXME: check for specialization-after-instantiation errors and such.
3258
Douglas Gregor88b70942009-02-25 22:02:03 +00003259 return false;
3260}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003261
Douglas Gregore94866f2009-06-12 21:21:02 +00003262/// \brief Check the non-type template arguments of a class template
3263/// partial specialization according to C++ [temp.class.spec]p9.
3264///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003265/// \param TemplateParams the template parameters of the primary class
3266/// template.
3267///
3268/// \param TemplateArg the template arguments of the class template
3269/// partial specialization.
3270///
3271/// \param MirrorsPrimaryTemplate will be set true if the class
3272/// template partial specialization arguments are identical to the
3273/// implicit template arguments of the primary template. This is not
3274/// necessarily an error (C++0x), and it is left to the caller to diagnose
3275/// this condition when it is an error.
3276///
Douglas Gregore94866f2009-06-12 21:21:02 +00003277/// \returns true if there was an error, false otherwise.
3278bool Sema::CheckClassTemplatePartialSpecializationArgs(
3279 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00003280 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003281 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003282 // FIXME: the interface to this function will have to change to
3283 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003284 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003285
Anders Carlssonfb250522009-06-23 01:26:57 +00003286 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00003287
Douglas Gregore94866f2009-06-12 21:21:02 +00003288 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003289 // Determine whether the template argument list of the partial
3290 // specialization is identical to the implicit argument list of
3291 // the primary template. The caller may need to diagnostic this as
3292 // an error per C++ [temp.class.spec]p9b3.
3293 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003294 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003295 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3296 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003297 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003298 MirrorsPrimaryTemplate = false;
3299 } else if (TemplateTemplateParmDecl *TTP
3300 = dyn_cast<TemplateTemplateParmDecl>(
3301 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003302 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003303 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003304 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003305 if (!ArgDecl ||
3306 ArgDecl->getIndex() != TTP->getIndex() ||
3307 ArgDecl->getDepth() != TTP->getDepth())
3308 MirrorsPrimaryTemplate = false;
3309 }
3310 }
3311
Mike Stump1eb44332009-09-09 15:08:12 +00003312 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003313 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003314 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003315 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003316 }
3317
Anders Carlsson6360be72009-06-13 18:20:51 +00003318 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003319 if (!ArgExpr) {
3320 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003321 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003322 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003323
3324 // C++ [temp.class.spec]p8:
3325 // A non-type argument is non-specialized if it is the name of a
3326 // non-type parameter. All other non-type arguments are
3327 // specialized.
3328 //
3329 // Below, we check the two conditions that only apply to
3330 // specialized non-type arguments, so skip any non-specialized
3331 // arguments.
3332 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003333 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003334 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003335 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003336 (Param->getIndex() != NTTP->getIndex() ||
3337 Param->getDepth() != NTTP->getDepth()))
3338 MirrorsPrimaryTemplate = false;
3339
Douglas Gregore94866f2009-06-12 21:21:02 +00003340 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003341 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003342
3343 // C++ [temp.class.spec]p9:
3344 // Within the argument list of a class template partial
3345 // specialization, the following restrictions apply:
3346 // -- A partially specialized non-type argument expression
3347 // shall not involve a template parameter of the partial
3348 // specialization except when the argument expression is a
3349 // simple identifier.
3350 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003351 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003352 diag::err_dependent_non_type_arg_in_partial_spec)
3353 << ArgExpr->getSourceRange();
3354 return true;
3355 }
3356
3357 // -- The type of a template parameter corresponding to a
3358 // specialized non-type argument shall not be dependent on a
3359 // parameter of the specialization.
3360 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003361 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003362 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3363 << Param->getType()
3364 << ArgExpr->getSourceRange();
3365 Diag(Param->getLocation(), diag::note_template_param_here);
3366 return true;
3367 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003368
3369 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003370 }
3371
3372 return false;
3373}
3374
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003375/// \brief Retrieve the previous declaration of the given declaration.
3376static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3377 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3378 return VD->getPreviousDeclaration();
3379 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3380 return FD->getPreviousDeclaration();
3381 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3382 return TD->getPreviousDeclaration();
3383 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3384 return TD->getPreviousDeclaration();
3385 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3386 return FTD->getPreviousDeclaration();
3387 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3388 return CTD->getPreviousDeclaration();
3389 return 0;
3390}
3391
Douglas Gregor212e81c2009-03-25 00:13:59 +00003392Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003393Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3394 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00003395 SourceLocation KWLoc,
Douglas Gregorcc636682009-02-17 23:15:12 +00003396 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003397 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00003398 SourceLocation TemplateNameLoc,
3399 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00003400 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00003401 SourceLocation RAngleLoc,
3402 AttributeList *Attr,
3403 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003404 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00003405
Douglas Gregorcc636682009-02-17 23:15:12 +00003406 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00003407 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003408 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00003409 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3410
3411 if (!ClassTemplate) {
3412 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3413 << (Name.getAsTemplateDecl() &&
3414 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3415 return true;
3416 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003417
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003418 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003419 bool isPartialSpecialization = false;
3420
Douglas Gregor88b70942009-02-25 22:02:03 +00003421 // Check the validity of the template headers that introduce this
3422 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003423 // FIXME: We probably shouldn't complain about these headers for
3424 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00003425 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00003426 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3427 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003428 TemplateParameterLists.size(),
3429 isExplicitSpecialization);
Douglas Gregor05396e22009-08-25 17:23:04 +00003430 if (TemplateParams && TemplateParams->size() > 0) {
3431 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003432
Douglas Gregor05396e22009-08-25 17:23:04 +00003433 // C++ [temp.class.spec]p10:
3434 // The template parameter list of a specialization shall not
3435 // contain default template argument values.
3436 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3437 Decl *Param = TemplateParams->getParam(I);
3438 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3439 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003440 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003441 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00003442 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003443 }
3444 } else if (NonTypeTemplateParmDecl *NTTP
3445 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3446 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003447 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003448 diag::err_default_arg_in_partial_spec)
3449 << DefArg->getSourceRange();
3450 NTTP->setDefaultArgument(0);
3451 DefArg->Destroy(Context);
3452 }
3453 } else {
3454 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003455 if (TTP->hasDefaultArgument()) {
3456 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003457 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003458 << TTP->getDefaultArgument().getSourceRange();
3459 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003460 }
3461 }
3462 }
Douglas Gregora735b202009-10-13 14:39:41 +00003463 } else if (TemplateParams) {
3464 if (TUK == TUK_Friend)
3465 Diag(KWLoc, diag::err_template_spec_friend)
3466 << CodeModificationHint::CreateRemoval(
3467 SourceRange(TemplateParams->getTemplateLoc(),
3468 TemplateParams->getRAngleLoc()))
3469 << SourceRange(LAngleLoc, RAngleLoc);
3470 else
3471 isExplicitSpecialization = true;
3472 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003473 Diag(KWLoc, diag::err_template_spec_needs_header)
3474 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003475 isExplicitSpecialization = true;
3476 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003477
Douglas Gregorcc636682009-02-17 23:15:12 +00003478 // Check that the specialization uses the same tag kind as the
3479 // original template.
3480 TagDecl::TagKind Kind;
3481 switch (TagSpec) {
3482 default: assert(0 && "Unknown tag type!");
3483 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3484 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3485 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3486 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003487 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003488 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003489 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003490 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003491 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00003492 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003493 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003494 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003495 diag::note_previous_use);
3496 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3497 }
3498
Douglas Gregor40808ce2009-03-09 23:48:35 +00003499 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00003500 TemplateArgumentListInfo TemplateArgs;
3501 TemplateArgs.setLAngleLoc(LAngleLoc);
3502 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00003503 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003504
Douglas Gregorcc636682009-02-17 23:15:12 +00003505 // Check that the template argument list is well-formed for this
3506 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003507 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3508 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00003509 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3510 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003511 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003512
Mike Stump1eb44332009-09-09 15:08:12 +00003513 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003514 ClassTemplate->getTemplateParameters()->size()) &&
3515 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003516
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003517 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003518 // corresponds to these arguments.
3519 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003520 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003521 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003522 if (CheckClassTemplatePartialSpecializationArgs(
3523 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003524 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003525 return true;
3526
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003527 if (MirrorsPrimaryTemplate) {
3528 // C++ [temp.class.spec]p9b3:
3529 //
Mike Stump1eb44332009-09-09 15:08:12 +00003530 // -- The argument list of the specialization shall not be identical
3531 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003532 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003533 << (TUK == TUK_Definition)
Mike Stump1eb44332009-09-09 15:08:12 +00003534 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003535 RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003536 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003537 ClassTemplate->getIdentifier(),
3538 TemplateNameLoc,
3539 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003540 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003541 AS_none);
3542 }
3543
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003544 // FIXME: Diagnose friend partial specializations
3545
Douglas Gregorde090962010-02-09 00:37:32 +00003546 if (!Name.isDependent() &&
3547 !TemplateSpecializationType::anyDependentTemplateArguments(
3548 TemplateArgs.getArgumentArray(),
3549 TemplateArgs.size())) {
3550 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3551 << ClassTemplate->getDeclName();
3552 isPartialSpecialization = false;
3553 } else {
3554 // FIXME: Template parameter list matters, too
3555 ClassTemplatePartialSpecializationDecl::Profile(ID,
3556 Converted.getFlatArguments(),
3557 Converted.flatSize(),
3558 Context);
3559 }
3560 }
3561
3562 if (!isPartialSpecialization)
Anders Carlsson1c5976e2009-06-05 03:43:12 +00003563 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003564 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003565 Converted.flatSize(),
3566 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00003567 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003568 ClassTemplateSpecializationDecl *PrevDecl = 0;
3569
3570 if (isPartialSpecialization)
3571 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00003572 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003573 InsertPos);
3574 else
3575 PrevDecl
3576 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003577
3578 ClassTemplateSpecializationDecl *Specialization = 0;
3579
Douglas Gregor88b70942009-02-25 22:02:03 +00003580 // Check whether we can declare a class template specialization in
3581 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003582 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003583 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003584 TemplateNameLoc,
3585 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003586 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003587
Douglas Gregorb88e8882009-07-30 17:40:51 +00003588 // The canonical type
3589 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003590 if (PrevDecl &&
3591 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00003592 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003593 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003594 // arguments was referenced but not declared, or we're only
3595 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003596 // declaration node as our own, updating its source location to
3597 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003598 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003599 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003600 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003601 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003602 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003603 // Build the canonical type that describes the converted template
3604 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00003605 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3606 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb88e8882009-07-30 17:40:51 +00003607 Converted.getFlatArguments(),
3608 Converted.flatSize());
3609
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003610 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003611 ClassTemplatePartialSpecializationDecl *PrevPartial
3612 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00003613 ClassTemplatePartialSpecializationDecl *Partial
3614 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003615 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003616 TemplateNameLoc,
3617 TemplateParams,
3618 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003619 Converted,
John McCalld5532b62009-11-23 01:53:49 +00003620 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00003621 CanonType,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003622 PrevPartial);
John McCallb6217662010-03-15 10:12:16 +00003623 SetNestedNameSpecifier(Partial, SS);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003624
3625 if (PrevPartial) {
3626 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3627 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3628 } else {
3629 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3630 }
3631 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003632
Douglas Gregored9c0f92009-10-29 00:04:11 +00003633 // If we are providing an explicit specialization of a member class
3634 // template specialization, make a note of that.
3635 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3636 PrevPartial->setMemberSpecialization();
3637
Douglas Gregor031a5882009-06-13 00:26:55 +00003638 // Check that all of the template parameters of the class template
3639 // partial specialization are deducible from the template
3640 // arguments. If not, this class template partial specialization
3641 // will never be used.
3642 llvm::SmallVector<bool, 8> DeducibleParams;
3643 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003644 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003645 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003646 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003647 unsigned NumNonDeducible = 0;
3648 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3649 if (!DeducibleParams[I])
3650 ++NumNonDeducible;
3651
3652 if (NumNonDeducible) {
3653 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3654 << (NumNonDeducible > 1)
3655 << SourceRange(TemplateNameLoc, RAngleLoc);
3656 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3657 if (!DeducibleParams[I]) {
3658 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3659 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003660 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003661 diag::note_partial_spec_unused_parameter)
3662 << Param->getDeclName();
3663 else
Mike Stump1eb44332009-09-09 15:08:12 +00003664 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003665 diag::note_partial_spec_unused_parameter)
3666 << std::string("<anonymous>");
3667 }
3668 }
3669 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003670 } else {
3671 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003672 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003673 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00003674 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorcc636682009-02-17 23:15:12 +00003675 ClassTemplate->getDeclContext(),
3676 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003677 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003678 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003679 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00003680 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregorcc636682009-02-17 23:15:12 +00003681
3682 if (PrevDecl) {
3683 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3684 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3685 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003686 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00003687 InsertPos);
3688 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00003689
3690 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003691 }
3692
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003693 // C++ [temp.expl.spec]p6:
3694 // If a template, a member template or the member of a class template is
3695 // explicitly specialized then that specialization shall be declared
3696 // before the first use of that specialization that would cause an implicit
3697 // instantiation to take place, in every translation unit in which such a
3698 // use occurs; no diagnostic is required.
3699 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003700 bool Okay = false;
3701 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3702 // Is there any previous explicit specialization declaration?
3703 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3704 Okay = true;
3705 break;
3706 }
3707 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003708
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003709 if (!Okay) {
3710 SourceRange Range(TemplateNameLoc, RAngleLoc);
3711 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3712 << Context.getTypeDeclType(Specialization) << Range;
3713
3714 Diag(PrevDecl->getPointOfInstantiation(),
3715 diag::note_instantiation_required_here)
3716 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003717 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003718 return true;
3719 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003720 }
3721
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003722 // If this is not a friend, note that this is an explicit specialization.
3723 if (TUK != TUK_Friend)
3724 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003725
3726 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003727 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00003728 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003729 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003730 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003731 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003732 Diag(Def->getLocation(), diag::note_previous_definition);
3733 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003734 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003735 }
3736 }
3737
Douglas Gregorfc705b82009-02-26 22:19:44 +00003738 // Build the fully-sugared type for this class template
3739 // specialization as the user wrote in the specialization
3740 // itself. This means that we'll pretty-print the type retrieved
3741 // from the specialization's declaration the way that the user
3742 // actually wrote the specialization, rather than formatting the
3743 // name based on the "canonical" representation used to store the
3744 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00003745 TypeSourceInfo *WrittenTy
3746 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3747 TemplateArgs, CanonType);
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003748 if (TUK != TUK_Friend)
3749 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003750 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00003751
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003752 // C++ [temp.expl.spec]p9:
3753 // A template explicit specialization is in the scope of the
3754 // namespace in which the template was defined.
3755 //
3756 // We actually implement this paragraph where we set the semantic
3757 // context (in the creation of the ClassTemplateSpecializationDecl),
3758 // but we also maintain the lexical context where the actual
3759 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00003760 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003761
Douglas Gregorcc636682009-02-17 23:15:12 +00003762 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003763 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00003764 Specialization->startDefinition();
3765
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003766 if (TUK == TUK_Friend) {
3767 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3768 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00003769 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003770 /*FIXME:*/KWLoc);
3771 Friend->setAccess(AS_public);
3772 CurContext->addDecl(Friend);
3773 } else {
3774 // Add the specialization into its lexical context, so that it can
3775 // be seen when iterating through the list of declarations in that
3776 // context. However, specializations are not found by name lookup.
3777 CurContext->addDecl(Specialization);
3778 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003779 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003780}
Douglas Gregord57959a2009-03-27 23:10:48 +00003781
Mike Stump1eb44332009-09-09 15:08:12 +00003782Sema::DeclPtrTy
3783Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00003784 MultiTemplateParamsArg TemplateParameterLists,
3785 Declarator &D) {
3786 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3787}
3788
Mike Stump1eb44332009-09-09 15:08:12 +00003789Sema::DeclPtrTy
3790Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003791 MultiTemplateParamsArg TemplateParameterLists,
3792 Declarator &D) {
3793 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3794 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3795 "Not a function declarator!");
3796 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00003797
Douglas Gregor52591bf2009-06-24 00:54:41 +00003798 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00003799 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00003800 }
Mike Stump1eb44332009-09-09 15:08:12 +00003801
Douglas Gregor52591bf2009-06-24 00:54:41 +00003802 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003803
3804 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003805 move(TemplateParameterLists),
3806 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003807 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003808 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00003809 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00003810 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003811 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3812 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00003813 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00003814}
3815
John McCall75042392010-02-11 01:33:53 +00003816/// \brief Strips various properties off an implicit instantiation
3817/// that has just been explicitly specialized.
3818static void StripImplicitInstantiation(NamedDecl *D) {
3819 D->invalidateAttrs();
3820
3821 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3822 FD->setInlineSpecified(false);
3823 }
3824}
3825
Douglas Gregor454885e2009-10-15 15:54:05 +00003826/// \brief Diagnose cases where we have an explicit template specialization
3827/// before/after an explicit template instantiation, producing diagnostics
3828/// for those cases where they are required and determining whether the
3829/// new specialization/instantiation will have any effect.
3830///
Douglas Gregor454885e2009-10-15 15:54:05 +00003831/// \param NewLoc the location of the new explicit specialization or
3832/// instantiation.
3833///
3834/// \param NewTSK the kind of the new explicit specialization or instantiation.
3835///
3836/// \param PrevDecl the previous declaration of the entity.
3837///
3838/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3839///
3840/// \param PrevPointOfInstantiation if valid, indicates where the previus
3841/// declaration was instantiated (either implicitly or explicitly).
3842///
3843/// \param SuppressNew will be set to true to indicate that the new
3844/// specialization or instantiation has no effect and should be ignored.
3845///
3846/// \returns true if there was an error that should prevent the introduction of
3847/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00003848bool
3849Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3850 TemplateSpecializationKind NewTSK,
3851 NamedDecl *PrevDecl,
3852 TemplateSpecializationKind PrevTSK,
3853 SourceLocation PrevPointOfInstantiation,
3854 bool &SuppressNew) {
Douglas Gregor454885e2009-10-15 15:54:05 +00003855 SuppressNew = false;
3856
3857 switch (NewTSK) {
3858 case TSK_Undeclared:
3859 case TSK_ImplicitInstantiation:
3860 assert(false && "Don't check implicit instantiations here");
3861 return false;
3862
3863 case TSK_ExplicitSpecialization:
3864 switch (PrevTSK) {
3865 case TSK_Undeclared:
3866 case TSK_ExplicitSpecialization:
3867 // Okay, we're just specializing something that is either already
3868 // explicitly specialized or has merely been mentioned without any
3869 // instantiation.
3870 return false;
3871
3872 case TSK_ImplicitInstantiation:
3873 if (PrevPointOfInstantiation.isInvalid()) {
3874 // The declaration itself has not actually been instantiated, so it is
3875 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00003876 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00003877 return false;
3878 }
3879 // Fall through
3880
3881 case TSK_ExplicitInstantiationDeclaration:
3882 case TSK_ExplicitInstantiationDefinition:
3883 assert((PrevTSK == TSK_ImplicitInstantiation ||
3884 PrevPointOfInstantiation.isValid()) &&
3885 "Explicit instantiation without point of instantiation?");
3886
3887 // C++ [temp.expl.spec]p6:
3888 // If a template, a member template or the member of a class template
3889 // is explicitly specialized then that specialization shall be declared
3890 // before the first use of that specialization that would cause an
3891 // implicit instantiation to take place, in every translation unit in
3892 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003893 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3894 // Is there any previous explicit specialization declaration?
3895 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
3896 return false;
3897 }
3898
Douglas Gregor0d035142009-10-27 18:42:08 +00003899 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00003900 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003901 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00003902 << (PrevTSK != TSK_ImplicitInstantiation);
3903
3904 return true;
3905 }
3906 break;
3907
3908 case TSK_ExplicitInstantiationDeclaration:
3909 switch (PrevTSK) {
3910 case TSK_ExplicitInstantiationDeclaration:
3911 // This explicit instantiation declaration is redundant (that's okay).
3912 SuppressNew = true;
3913 return false;
3914
3915 case TSK_Undeclared:
3916 case TSK_ImplicitInstantiation:
3917 // We're explicitly instantiating something that may have already been
3918 // implicitly instantiated; that's fine.
3919 return false;
3920
3921 case TSK_ExplicitSpecialization:
3922 // C++0x [temp.explicit]p4:
3923 // For a given set of template parameters, if an explicit instantiation
3924 // of a template appears after a declaration of an explicit
3925 // specialization for that template, the explicit instantiation has no
3926 // effect.
John McCalle97c32f2010-03-02 23:09:38 +00003927 SuppressNew = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00003928 return false;
3929
3930 case TSK_ExplicitInstantiationDefinition:
3931 // C++0x [temp.explicit]p10:
3932 // If an entity is the subject of both an explicit instantiation
3933 // declaration and an explicit instantiation definition in the same
3934 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00003935 Diag(NewLoc,
3936 diag::err_explicit_instantiation_declaration_after_definition);
3937 Diag(PrevPointOfInstantiation,
3938 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00003939 assert(PrevPointOfInstantiation.isValid() &&
3940 "Explicit instantiation without point of instantiation?");
3941 SuppressNew = true;
3942 return false;
3943 }
3944 break;
3945
3946 case TSK_ExplicitInstantiationDefinition:
3947 switch (PrevTSK) {
3948 case TSK_Undeclared:
3949 case TSK_ImplicitInstantiation:
3950 // We're explicitly instantiating something that may have already been
3951 // implicitly instantiated; that's fine.
3952 return false;
3953
3954 case TSK_ExplicitSpecialization:
3955 // C++ DR 259, C++0x [temp.explicit]p4:
3956 // For a given set of template parameters, if an explicit
3957 // instantiation of a template appears after a declaration of
3958 // an explicit specialization for that template, the explicit
3959 // instantiation has no effect.
3960 //
3961 // In C++98/03 mode, we only give an extension warning here, because it
3962 // is not not harmful to try to explicitly instantiate something that
3963 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00003964 if (!getLangOptions().CPlusPlus0x) {
3965 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00003966 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003967 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00003968 diag::note_previous_template_specialization);
3969 }
3970 SuppressNew = true;
3971 return false;
3972
3973 case TSK_ExplicitInstantiationDeclaration:
3974 // We're explicity instantiating a definition for something for which we
3975 // were previously asked to suppress instantiations. That's fine.
3976 return false;
3977
3978 case TSK_ExplicitInstantiationDefinition:
3979 // C++0x [temp.spec]p5:
3980 // For a given template and a given set of template-arguments,
3981 // - an explicit instantiation definition shall appear at most once
3982 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00003983 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00003984 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003985 Diag(PrevPointOfInstantiation,
3986 diag::note_previous_explicit_instantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00003987 SuppressNew = true;
3988 return false;
3989 }
3990 break;
3991 }
3992
3993 assert(false && "Missing specialization/instantiation case?");
3994
3995 return false;
3996}
3997
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003998/// \brief Perform semantic analysis for the given function template
3999/// specialization.
4000///
4001/// This routine performs all of the semantic analysis required for an
4002/// explicit function template specialization. On successful completion,
4003/// the function declaration \p FD will become a function template
4004/// specialization.
4005///
4006/// \param FD the function declaration, which will be updated to become a
4007/// function template specialization.
4008///
4009/// \param HasExplicitTemplateArgs whether any template arguments were
4010/// explicitly provided.
4011///
4012/// \param LAngleLoc the location of the left angle bracket ('<'), if
4013/// template arguments were explicitly provided.
4014///
4015/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4016/// if any.
4017///
4018/// \param NumExplicitTemplateArgs the number of explicitly-provided template
4019/// arguments. This number may be zero even when HasExplicitTemplateArgs is
4020/// true as in, e.g., \c void sort<>(char*, char*);
4021///
4022/// \param RAngleLoc the location of the right angle bracket ('>'), if
4023/// template arguments were explicitly provided.
4024///
4025/// \param PrevDecl the set of declarations that
4026bool
4027Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004028 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004029 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004030 // The set of function template specializations that could match this
4031 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004032 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004033
4034 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall68263142009-11-18 22:49:29 +00004035 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4036 I != E; ++I) {
4037 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4038 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004039 // Only consider templates found within the same semantic lookup scope as
4040 // FD.
4041 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4042 continue;
4043
4044 // C++ [temp.expl.spec]p11:
4045 // A trailing template-argument can be left unspecified in the
4046 // template-id naming an explicit function template specialization
4047 // provided it can be deduced from the function argument type.
4048 // Perform template argument deduction to determine whether we may be
4049 // specializing this template.
4050 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004051 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004052 FunctionDecl *Specialization = 0;
4053 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004054 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004055 FD->getType(),
4056 Specialization,
4057 Info)) {
4058 // FIXME: Template argument deduction failed; record why it failed, so
4059 // that we can provide nifty diagnostics.
4060 (void)TDK;
4061 continue;
4062 }
4063
4064 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004065 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004066 }
4067 }
4068
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004069 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004070 UnresolvedSetIterator Result
4071 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4072 TPOC_Other, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004073 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004074 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004075 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004076 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004077 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004078 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004079 return true;
John McCallc373d482010-01-27 01:50:18 +00004080
4081 // Ignore access information; it doesn't figure into redeclaration checking.
4082 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004083
4084 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004085 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004086
4087 // If this is a friend declaration, then we're not really declaring
4088 // an explicit specialization.
4089 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004090
Douglas Gregord5cb8762009-10-07 00:13:32 +00004091 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004092 if (!isFriend &&
4093 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004094 Specialization->getPrimaryTemplate(),
4095 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004096 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004097 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004098
4099 // C++ [temp.expl.spec]p6:
4100 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004101 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004102 // before the first use of that specialization that would cause an implicit
4103 // instantiation to take place, in every translation unit in which such a
4104 // use occurs; no diagnostic is required.
4105 FunctionTemplateSpecializationInfo *SpecInfo
4106 = Specialization->getTemplateSpecializationInfo();
4107 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004108
4109 bool SuppressNew = false;
John McCall7ad650f2010-03-24 07:46:06 +00004110 if (!isFriend &&
4111 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004112 TSK_ExplicitSpecialization,
4113 Specialization,
4114 SpecInfo->getTemplateSpecializationKind(),
4115 SpecInfo->getPointOfInstantiation(),
4116 SuppressNew))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004117 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004118
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004119 // Mark the prior declaration as an explicit specialization, so that later
4120 // clients know that this is an explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004121 if (!isFriend)
4122 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004123
4124 // Turn the given function declaration into a function template
4125 // specialization, with the template arguments from the previous
4126 // specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00004127 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004128 new (Context) TemplateArgumentList(
4129 *Specialization->getTemplateSpecializationArgs()),
4130 /*InsertPos=*/0,
John McCall7ad650f2010-03-24 07:46:06 +00004131 SpecInfo->getTemplateSpecializationKind());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004132
4133 // The "previous declaration" for this function template specialization is
4134 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004135 Previous.clear();
4136 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004137 return false;
4138}
4139
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004140/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004141/// specialization.
4142///
4143/// This routine performs all of the semantic analysis required for an
4144/// explicit member function specialization. On successful completion,
4145/// the function declaration \p FD will become a member function
4146/// specialization.
4147///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004148/// \param Member the member declaration, which will be updated to become a
4149/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004150///
John McCall68263142009-11-18 22:49:29 +00004151/// \param Previous the set of declarations, one of which may be specialized
4152/// by this function specialization; the set will be modified to contain the
4153/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004154bool
John McCall68263142009-11-18 22:49:29 +00004155Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004156 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
4157
4158 // Try to find the member we are instantiating.
4159 NamedDecl *Instantiation = 0;
4160 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004161 MemberSpecializationInfo *MSInfo = 0;
4162
John McCall68263142009-11-18 22:49:29 +00004163 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004164 // Nowhere to look anyway.
4165 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004166 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4167 I != E; ++I) {
4168 NamedDecl *D = (*I)->getUnderlyingDecl();
4169 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004170 if (Context.hasSameType(Function->getType(), Method->getType())) {
4171 Instantiation = Method;
4172 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004173 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004174 break;
4175 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004176 }
4177 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004178 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004179 VarDecl *PrevVar;
4180 if (Previous.isSingleResult() &&
4181 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004182 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004183 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004184 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004185 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004186 }
4187 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004188 CXXRecordDecl *PrevRecord;
4189 if (Previous.isSingleResult() &&
4190 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4191 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004192 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004193 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004194 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004195 }
4196
4197 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004198 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004199 // specializations are always out-of-line, the caller will complain about
4200 // this mismatch later.
4201 return false;
4202 }
4203
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004204 // Make sure that this is a specialization of a member.
4205 if (!InstantiatedFrom) {
4206 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4207 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004208 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4209 return true;
4210 }
4211
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004212 // C++ [temp.expl.spec]p6:
4213 // If a template, a member template or the member of a class template is
4214 // explicitly specialized then that spe- cialization shall be declared
4215 // before the first use of that specialization that would cause an implicit
4216 // instantiation to take place, in every translation unit in which such a
4217 // use occurs; no diagnostic is required.
4218 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004219
4220 bool SuppressNew = false;
4221 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4222 TSK_ExplicitSpecialization,
4223 Instantiation,
4224 MSInfo->getTemplateSpecializationKind(),
4225 MSInfo->getPointOfInstantiation(),
4226 SuppressNew))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004227 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004228
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004229 // Check the scope of this explicit specialization.
4230 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004231 InstantiatedFrom,
4232 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004233 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004234 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004235
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004236 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004237 // the original declaration to note that it is an explicit specialization
4238 // (if it was previously an implicit instantiation). This latter step
4239 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004240 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004241 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4242 if (InstantiationFunction->getTemplateSpecializationKind() ==
4243 TSK_ImplicitInstantiation) {
4244 InstantiationFunction->setTemplateSpecializationKind(
4245 TSK_ExplicitSpecialization);
4246 InstantiationFunction->setLocation(Member->getLocation());
4247 }
4248
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004249 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4250 cast<CXXMethodDecl>(InstantiatedFrom),
4251 TSK_ExplicitSpecialization);
4252 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004253 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4254 if (InstantiationVar->getTemplateSpecializationKind() ==
4255 TSK_ImplicitInstantiation) {
4256 InstantiationVar->setTemplateSpecializationKind(
4257 TSK_ExplicitSpecialization);
4258 InstantiationVar->setLocation(Member->getLocation());
4259 }
4260
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004261 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4262 cast<VarDecl>(InstantiatedFrom),
4263 TSK_ExplicitSpecialization);
4264 } else {
4265 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004266 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4267 if (InstantiationClass->getTemplateSpecializationKind() ==
4268 TSK_ImplicitInstantiation) {
4269 InstantiationClass->setTemplateSpecializationKind(
4270 TSK_ExplicitSpecialization);
4271 InstantiationClass->setLocation(Member->getLocation());
4272 }
4273
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004274 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004275 cast<CXXRecordDecl>(InstantiatedFrom),
4276 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004277 }
4278
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004279 // Save the caller the trouble of having to figure out which declaration
4280 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004281 Previous.clear();
4282 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004283 return false;
4284}
4285
Douglas Gregor558c0322009-10-14 23:41:34 +00004286/// \brief Check the scope of an explicit instantiation.
4287static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4288 SourceLocation InstLoc,
4289 bool WasQualifiedName) {
4290 DeclContext *ExpectedContext
4291 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4292 DeclContext *CurContext = S.CurContext->getLookupContext();
4293
4294 // C++0x [temp.explicit]p2:
4295 // An explicit instantiation shall appear in an enclosing namespace of its
4296 // template.
4297 //
4298 // This is DR275, which we do not retroactively apply to C++98/03.
4299 if (S.getLangOptions().CPlusPlus0x &&
4300 !CurContext->Encloses(ExpectedContext)) {
4301 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4302 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4303 << D << NS;
4304 else
4305 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4306 << D;
4307 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4308 return;
4309 }
4310
4311 // C++0x [temp.explicit]p2:
4312 // If the name declared in the explicit instantiation is an unqualified
4313 // name, the explicit instantiation shall appear in the namespace where
4314 // its template is declared or, if that namespace is inline (7.3.1), any
4315 // namespace from its enclosing namespace set.
4316 if (WasQualifiedName)
4317 return;
4318
4319 if (CurContext->Equals(ExpectedContext))
4320 return;
4321
4322 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4323 << D << ExpectedContext;
4324 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4325}
4326
4327/// \brief Determine whether the given scope specifier has a template-id in it.
4328static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4329 if (!SS.isSet())
4330 return false;
4331
4332 // C++0x [temp.explicit]p2:
4333 // If the explicit instantiation is for a member function, a member class
4334 // or a static data member of a class template specialization, the name of
4335 // the class template specialization in the qualified-id for the member
4336 // name shall be a simple-template-id.
4337 //
4338 // C++98 has the same restriction, just worded differently.
4339 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4340 NNS; NNS = NNS->getPrefix())
4341 if (Type *T = NNS->getAsType())
4342 if (isa<TemplateSpecializationType>(T))
4343 return true;
4344
4345 return false;
4346}
4347
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004348// Explicit instantiation of a class template specialization
Douglas Gregor45f96552009-09-04 06:33:52 +00004349// FIXME: Implement extern template semantics
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004350Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004351Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004352 SourceLocation ExternLoc,
4353 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004354 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004355 SourceLocation KWLoc,
4356 const CXXScopeSpec &SS,
4357 TemplateTy TemplateD,
4358 SourceLocation TemplateNameLoc,
4359 SourceLocation LAngleLoc,
4360 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004361 SourceLocation RAngleLoc,
4362 AttributeList *Attr) {
4363 // Find the class template we're specializing
4364 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004365 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004366 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4367
4368 // Check that the specialization uses the same tag kind as the
4369 // original template.
4370 TagDecl::TagKind Kind;
4371 switch (TagSpec) {
4372 default: assert(0 && "Unknown tag type!");
4373 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4374 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4375 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4376 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004377 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004378 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004379 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004380 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004381 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00004382 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004383 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004384 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004385 diag::note_previous_use);
4386 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4387 }
4388
Douglas Gregor558c0322009-10-14 23:41:34 +00004389 // C++0x [temp.explicit]p2:
4390 // There are two forms of explicit instantiation: an explicit instantiation
4391 // definition and an explicit instantiation declaration. An explicit
4392 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00004393 TemplateSpecializationKind TSK
4394 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4395 : TSK_ExplicitInstantiationDeclaration;
4396
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004397 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004398 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004399 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004400
4401 // Check that the template argument list is well-formed for this
4402 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00004403 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4404 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00004405 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4406 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004407 return true;
4408
Mike Stump1eb44332009-09-09 15:08:12 +00004409 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004410 ClassTemplate->getTemplateParameters()->size()) &&
4411 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004412
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004413 // Find the class template specialization declaration that
4414 // corresponds to these arguments.
4415 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00004416 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00004417 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00004418 Converted.flatSize(),
4419 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004420 void *InsertPos = 0;
4421 ClassTemplateSpecializationDecl *PrevDecl
4422 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4423
Douglas Gregord5cb8762009-10-07 00:13:32 +00004424 // C++0x [temp.explicit]p2:
4425 // [...] An explicit instantiation shall appear in an enclosing
4426 // namespace of its template. [...]
4427 //
4428 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004429 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4430 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00004431
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004432 ClassTemplateSpecializationDecl *Specialization = 0;
4433
Douglas Gregord78f5982009-11-25 06:01:46 +00004434 bool ReusedDecl = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004435 if (PrevDecl) {
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004436 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004437 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004438 PrevDecl,
4439 PrevDecl->getSpecializationKind(),
4440 PrevDecl->getPointOfInstantiation(),
4441 SuppressNew))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004442 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004443
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004444 if (SuppressNew)
Douglas Gregor52604ab2009-09-11 21:19:12 +00004445 return DeclPtrTy::make(PrevDecl);
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004446
Douglas Gregor52604ab2009-09-11 21:19:12 +00004447 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4448 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4449 // Since the only prior class template specialization with these
4450 // arguments was referenced but not declared, reuse that
4451 // declaration node as our own, updating its source location to
4452 // reflect our new declaration.
4453 Specialization = PrevDecl;
4454 Specialization->setLocation(TemplateNameLoc);
4455 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00004456 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00004457 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004458 }
Douglas Gregor52604ab2009-09-11 21:19:12 +00004459
4460 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004461 // Create a new class template specialization declaration node for
4462 // this explicit specialization.
4463 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00004464 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004465 ClassTemplate->getDeclContext(),
4466 TemplateNameLoc,
4467 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00004468 Converted, PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004469 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004470
Douglas Gregor52604ab2009-09-11 21:19:12 +00004471 if (PrevDecl) {
4472 // Remove the previous declaration from the folding set, since we want
4473 // to introduce a new declaration.
4474 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4475 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4476 }
4477
4478 // Insert the new specialization.
4479 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004480 }
4481
4482 // Build the fully-sugared type for this explicit instantiation as
4483 // the user wrote in the explicit instantiation itself. This means
4484 // that we'll pretty-print the type retrieved from the
4485 // specialization's declaration the way that the user actually wrote
4486 // the explicit instantiation, rather than formatting the name based
4487 // on the "canonical" representation used to store the template
4488 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004489 TypeSourceInfo *WrittenTy
4490 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4491 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004492 Context.getTypeDeclType(Specialization));
4493 Specialization->setTypeAsWritten(WrittenTy);
4494 TemplateArgsIn.release();
4495
Douglas Gregord78f5982009-11-25 06:01:46 +00004496 if (!ReusedDecl) {
4497 // Add the explicit instantiation into its lexical context. However,
4498 // since explicit instantiations are never found by name lookup, we
4499 // just put it into the declaration context directly.
4500 Specialization->setLexicalDeclContext(CurContext);
4501 CurContext->addDecl(Specialization);
4502 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004503
4504 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004505 // A definition of a class template or class member template
4506 // shall be in scope at the point of the explicit instantiation of
4507 // the class template or class member template.
4508 //
4509 // This check comes when we actually try to perform the
4510 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004511 ClassTemplateSpecializationDecl *Def
4512 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004513 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004514 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004515 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor0d035142009-10-27 18:42:08 +00004516
4517 // Instantiate the members of this class template specialization.
4518 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004519 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004520 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00004521 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4522
4523 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4524 // TSK_ExplicitInstantiationDefinition
4525 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4526 TSK == TSK_ExplicitInstantiationDefinition)
4527 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004528
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004529 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004530 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004531
4532 return DeclPtrTy::make(Specialization);
4533}
4534
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004535// Explicit instantiation of a member class of a class template.
4536Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004537Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004538 SourceLocation ExternLoc,
4539 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004540 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004541 SourceLocation KWLoc,
4542 const CXXScopeSpec &SS,
4543 IdentifierInfo *Name,
4544 SourceLocation NameLoc,
4545 AttributeList *Attr) {
4546
Douglas Gregor402abb52009-05-28 23:31:59 +00004547 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004548 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00004549 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004550 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00004551 MultiTemplateParamsArg(*this, 0, 0),
4552 Owned, IsDependent);
4553 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4554
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004555 if (!TagD)
4556 return true;
4557
4558 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4559 if (Tag->isEnum()) {
4560 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4561 << Context.getTypeDeclType(Tag);
4562 return true;
4563 }
4564
Douglas Gregord0c87372009-05-27 17:30:49 +00004565 if (Tag->isInvalidDecl())
4566 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004567
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004568 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4569 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4570 if (!Pattern) {
4571 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4572 << Context.getTypeDeclType(Record);
4573 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4574 return true;
4575 }
4576
Douglas Gregor558c0322009-10-14 23:41:34 +00004577 // C++0x [temp.explicit]p2:
4578 // If the explicit instantiation is for a class or member class, the
4579 // elaborated-type-specifier in the declaration shall include a
4580 // simple-template-id.
4581 //
4582 // C++98 has the same restriction, just worded differently.
4583 if (!ScopeSpecifierHasTemplateId(SS))
4584 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4585 << Record << SS.getRange();
4586
4587 // C++0x [temp.explicit]p2:
4588 // There are two forms of explicit instantiation: an explicit instantiation
4589 // definition and an explicit instantiation declaration. An explicit
4590 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004591 TemplateSpecializationKind TSK
4592 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4593 : TSK_ExplicitInstantiationDeclaration;
4594
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004595 // C++0x [temp.explicit]p2:
4596 // [...] An explicit instantiation shall appear in an enclosing
4597 // namespace of its template. [...]
4598 //
4599 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004600 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004601
4602 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004603 CXXRecordDecl *PrevDecl
4604 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00004605 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00004606 PrevDecl = Record;
4607 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004608 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4609 bool SuppressNew = false;
4610 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004611 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004612 PrevDecl,
4613 MSInfo->getTemplateSpecializationKind(),
4614 MSInfo->getPointOfInstantiation(),
4615 SuppressNew))
4616 return true;
4617 if (SuppressNew)
4618 return TagD;
4619 }
4620
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004621 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00004622 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004623 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004624 // C++ [temp.explicit]p3:
4625 // A definition of a member class of a class template shall be in scope
4626 // at the point of an explicit instantiation of the member class.
4627 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00004628 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004629 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004630 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4631 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004632 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4633 << Pattern;
4634 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004635 } else {
4636 if (InstantiateClass(NameLoc, Record, Def,
4637 getTemplateInstantiationArgs(Record),
4638 TSK))
4639 return true;
4640
Douglas Gregor952b0172010-02-11 01:04:33 +00004641 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00004642 if (!RecordDef)
4643 return true;
4644 }
4645 }
4646
4647 // Instantiate all of the members of the class.
4648 InstantiateClassMembers(NameLoc, RecordDef,
4649 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004650
Mike Stump390b4cc2009-05-16 07:39:55 +00004651 // FIXME: We don't have any representation for explicit instantiations of
4652 // member classes. Such a representation is not needed for compilation, but it
4653 // should be available for clients that want to see all of the declarations in
4654 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004655 return TagD;
4656}
4657
Douglas Gregord5a423b2009-09-25 18:43:00 +00004658Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4659 SourceLocation ExternLoc,
4660 SourceLocation TemplateLoc,
4661 Declarator &D) {
4662 // Explicit instantiations always require a name.
4663 DeclarationName Name = GetNameForDeclarator(D);
4664 if (!Name) {
4665 if (!D.isInvalidType())
4666 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4667 diag::err_explicit_instantiation_requires_name)
4668 << D.getDeclSpec().getSourceRange()
4669 << D.getSourceRange();
4670
4671 return true;
4672 }
4673
4674 // The scope passed in may not be a decl scope. Zip up the scope tree until
4675 // we find one that is.
4676 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4677 (S->getFlags() & Scope::TemplateParamScope) != 0)
4678 S = S->getParent();
4679
4680 // Determine the type of the declaration.
4681 QualType R = GetTypeForDeclarator(D, S, 0);
4682 if (R.isNull())
4683 return true;
4684
4685 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4686 // Cannot explicitly instantiate a typedef.
4687 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4688 << Name;
4689 return true;
4690 }
4691
Douglas Gregor663b5a02009-10-14 20:14:33 +00004692 // C++0x [temp.explicit]p1:
4693 // [...] An explicit instantiation of a function template shall not use the
4694 // inline or constexpr specifiers.
4695 // Presumably, this also applies to member functions of class templates as
4696 // well.
4697 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4698 Diag(D.getDeclSpec().getInlineSpecLoc(),
4699 diag::err_explicit_instantiation_inline)
Chris Lattner29d9c1a2009-12-06 17:36:05 +00004700 <<CodeModificationHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00004701
4702 // FIXME: check for constexpr specifier.
4703
Douglas Gregor558c0322009-10-14 23:41:34 +00004704 // C++0x [temp.explicit]p2:
4705 // There are two forms of explicit instantiation: an explicit instantiation
4706 // definition and an explicit instantiation declaration. An explicit
4707 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00004708 TemplateSpecializationKind TSK
4709 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4710 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00004711
John McCalla24dc2e2009-11-17 02:14:36 +00004712 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4713 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004714
4715 if (!R->isFunctionType()) {
4716 // C++ [temp.explicit]p1:
4717 // A [...] static data member of a class template can be explicitly
4718 // instantiated from the member definition associated with its class
4719 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00004720 if (Previous.isAmbiguous())
4721 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004722
John McCall1bcee0a2009-12-02 08:25:40 +00004723 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004724 if (!Prev || !Prev->isStaticDataMember()) {
4725 // We expect to see a data data member here.
4726 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4727 << Name;
4728 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4729 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00004730 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004731 return true;
4732 }
4733
4734 if (!Prev->getInstantiatedFromStaticDataMember()) {
4735 // FIXME: Check for explicit specialization?
4736 Diag(D.getIdentifierLoc(),
4737 diag::err_explicit_instantiation_data_member_not_instantiated)
4738 << Prev;
4739 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4740 // FIXME: Can we provide a note showing where this was declared?
4741 return true;
4742 }
4743
Douglas Gregor558c0322009-10-14 23:41:34 +00004744 // C++0x [temp.explicit]p2:
4745 // If the explicit instantiation is for a member function, a member class
4746 // or a static data member of a class template specialization, the name of
4747 // the class template specialization in the qualified-id for the member
4748 // name shall be a simple-template-id.
4749 //
4750 // C++98 has the same restriction, just worded differently.
4751 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4752 Diag(D.getIdentifierLoc(),
4753 diag::err_explicit_instantiation_without_qualified_id)
4754 << Prev << D.getCXXScopeSpec().getRange();
4755
4756 // Check the scope of this explicit instantiation.
4757 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4758
Douglas Gregor454885e2009-10-15 15:54:05 +00004759 // Verify that it is okay to explicitly instantiate here.
4760 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4761 assert(MSInfo && "Missing static data member specialization info?");
4762 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004763 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00004764 MSInfo->getTemplateSpecializationKind(),
4765 MSInfo->getPointOfInstantiation(),
4766 SuppressNew))
4767 return true;
4768 if (SuppressNew)
4769 return DeclPtrTy();
4770
Douglas Gregord5a423b2009-09-25 18:43:00 +00004771 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004772 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004773 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004774 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4775 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004776
4777 // FIXME: Create an ExplicitInstantiation node?
4778 return DeclPtrTy();
4779 }
4780
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004781 // If the declarator is a template-id, translate the parser's template
4782 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00004783 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00004784 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004785 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4786 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00004787 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4788 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00004789 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4790 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00004791 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00004792 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00004793 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00004794 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00004795 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004796
Douglas Gregord5a423b2009-09-25 18:43:00 +00004797 // C++ [temp.explicit]p1:
4798 // A [...] function [...] can be explicitly instantiated from its template.
4799 // A member function [...] of a class template can be explicitly
4800 // instantiated from the member definition associated with its class
4801 // template.
John McCallc373d482010-01-27 01:50:18 +00004802 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004803 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4804 P != PEnd; ++P) {
4805 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00004806 if (!HasExplicitTemplateArgs) {
4807 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4808 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4809 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00004810
John McCallc373d482010-01-27 01:50:18 +00004811 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00004812 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
4813 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00004814 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00004815 }
4816 }
4817
4818 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4819 if (!FunTmpl)
4820 continue;
4821
John McCall5769d612010-02-08 23:07:23 +00004822 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004823 FunctionDecl *Specialization = 0;
4824 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00004825 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00004826 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00004827 R, Specialization, Info)) {
4828 // FIXME: Keep track of almost-matches?
4829 (void)TDK;
4830 continue;
4831 }
4832
John McCallc373d482010-01-27 01:50:18 +00004833 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004834 }
4835
4836 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004837 UnresolvedSetIterator Result
4838 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregord5a423b2009-09-25 18:43:00 +00004839 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004840 PDiag(diag::err_explicit_instantiation_not_known) << Name,
4841 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
4842 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00004843
John McCallc373d482010-01-27 01:50:18 +00004844 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00004845 return true;
John McCallc373d482010-01-27 01:50:18 +00004846
4847 // Ignore access control bits, we don't need them for redeclaration checking.
4848 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004849
Douglas Gregor0a897e32009-10-15 17:21:20 +00004850 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00004851 Diag(D.getIdentifierLoc(),
4852 diag::err_explicit_instantiation_member_function_not_instantiated)
4853 << Specialization
4854 << (Specialization->getTemplateSpecializationKind() ==
4855 TSK_ExplicitSpecialization);
4856 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4857 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00004858 }
Douglas Gregor558c0322009-10-14 23:41:34 +00004859
Douglas Gregor0a897e32009-10-15 17:21:20 +00004860 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00004861 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4862 PrevDecl = Specialization;
4863
Douglas Gregor0a897e32009-10-15 17:21:20 +00004864 if (PrevDecl) {
4865 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004866 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00004867 PrevDecl,
4868 PrevDecl->getTemplateSpecializationKind(),
4869 PrevDecl->getPointOfInstantiation(),
4870 SuppressNew))
4871 return true;
4872
4873 // FIXME: We may still want to build some representation of this
4874 // explicit specialization.
4875 if (SuppressNew)
4876 return DeclPtrTy();
4877 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00004878
4879 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00004880
4881 if (TSK == TSK_ExplicitInstantiationDefinition)
4882 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4883 false, /*DefinitionRequired=*/true);
Douglas Gregor0a897e32009-10-15 17:21:20 +00004884
Douglas Gregor558c0322009-10-14 23:41:34 +00004885 // C++0x [temp.explicit]p2:
4886 // If the explicit instantiation is for a member function, a member class
4887 // or a static data member of a class template specialization, the name of
4888 // the class template specialization in the qualified-id for the member
4889 // name shall be a simple-template-id.
4890 //
4891 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004892 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004893 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00004894 D.getCXXScopeSpec().isSet() &&
4895 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4896 Diag(D.getIdentifierLoc(),
4897 diag::err_explicit_instantiation_without_qualified_id)
4898 << Specialization << D.getCXXScopeSpec().getRange();
4899
4900 CheckExplicitInstantiationScope(*this,
4901 FunTmpl? (NamedDecl *)FunTmpl
4902 : Specialization->getInstantiatedFromMemberFunction(),
4903 D.getIdentifierLoc(),
4904 D.getCXXScopeSpec().isSet());
4905
Douglas Gregord5a423b2009-09-25 18:43:00 +00004906 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4907 return DeclPtrTy();
4908}
4909
Douglas Gregord57959a2009-03-27 23:10:48 +00004910Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00004911Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4912 const CXXScopeSpec &SS, IdentifierInfo *Name,
4913 SourceLocation TagLoc, SourceLocation NameLoc) {
4914 // This has to hold, because SS is expected to be defined.
4915 assert(Name && "Expected a name in a dependent tag");
4916
4917 NestedNameSpecifier *NNS
4918 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4919 if (!NNS)
4920 return true;
4921
4922 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4923 if (T.isNull())
4924 return true;
4925
4926 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4927 QualType ElabType = Context.getElaboratedType(T, TagKind);
4928
4929 return ElabType.getAsOpaquePtr();
4930}
4931
4932Sema::TypeResult
Douglas Gregord57959a2009-03-27 23:10:48 +00004933Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4934 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00004935 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00004936 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4937 if (!NNS)
4938 return true;
4939
4940 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00004941 if (T.isNull())
4942 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00004943 return T.getAsOpaquePtr();
4944}
4945
Douglas Gregor17343172009-04-01 00:28:59 +00004946Sema::TypeResult
4947Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4948 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00004949 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004950 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00004951 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +00004952 const TemplateSpecializationType *TemplateId
John McCall183700f2009-09-21 23:43:11 +00004953 = T->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00004954 assert(TemplateId && "Expected a template specialization type");
4955
Douglas Gregor6946baf2009-09-02 13:05:45 +00004956 if (computeDeclContext(SS, false)) {
4957 // If we can compute a declaration context, then the "typename"
4958 // keyword was superfluous. Just build a QualifiedNameType to keep
4959 // track of the nested-name-specifier.
Mike Stump1eb44332009-09-09 15:08:12 +00004960
Douglas Gregor6946baf2009-09-02 13:05:45 +00004961 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4962 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4963 }
Mike Stump1eb44332009-09-09 15:08:12 +00004964
Douglas Gregor6946baf2009-09-02 13:05:45 +00004965 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00004966}
4967
Douglas Gregord57959a2009-03-27 23:10:48 +00004968/// \brief Build the type that describes a C++ typename specifier,
4969/// e.g., "typename T::type".
4970QualType
4971Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4972 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00004973 CXXRecordDecl *CurrentInstantiation = 0;
4974 if (NNS->isDependent()) {
4975 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00004976
Douglas Gregor42af25f2009-05-11 19:58:34 +00004977 // If the nested-name-specifier does not refer to the current
4978 // instantiation, then build a typename type.
4979 if (!CurrentInstantiation)
4980 return Context.getTypenameType(NNS, &II);
Mike Stump1eb44332009-09-09 15:08:12 +00004981
Douglas Gregorde18d122009-09-02 13:12:51 +00004982 // The nested-name-specifier refers to the current instantiation, so the
4983 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump1eb44332009-09-09 15:08:12 +00004984 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorde18d122009-09-02 13:12:51 +00004985 // extraneous "typename" keywords, and we retroactively apply this DR to
4986 // C++03 code.
Douglas Gregor42af25f2009-05-11 19:58:34 +00004987 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004988
Douglas Gregor42af25f2009-05-11 19:58:34 +00004989 DeclContext *Ctx = 0;
4990
4991 if (CurrentInstantiation)
4992 Ctx = CurrentInstantiation;
4993 else {
4994 CXXScopeSpec SS;
4995 SS.setScopeRep(NNS);
4996 SS.setRange(Range);
4997 if (RequireCompleteDeclContext(SS))
4998 return QualType();
4999
5000 Ctx = computeDeclContext(SS);
5001 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005002 assert(Ctx && "No declaration context?");
5003
5004 DeclarationName Name(&II);
John McCalla24dc2e2009-11-17 02:14:36 +00005005 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
5006 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005007 unsigned DiagID = 0;
5008 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005009 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005010 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005011 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005012 break;
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005013
5014 case LookupResult::NotFoundInCurrentInstantiation:
5015 // Okay, it's a member of an unknown instantiation.
5016 return Context.getTypenameType(NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00005017
5018 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +00005019 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005020 // We found a type. Build a QualifiedNameType, since the
5021 // typename-specifier was just sugar. FIXME: Tell
5022 // QualifiedNameType that it has a "typename" prefix.
5023 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
5024 }
5025
5026 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00005027 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00005028 break;
5029
John McCall7ba107a2009-11-18 02:36:19 +00005030 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005031 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00005032 return QualType();
5033
Douglas Gregord57959a2009-03-27 23:10:48 +00005034 case LookupResult::FoundOverloaded:
5035 DiagID = diag::err_typename_nested_not_type;
5036 Referenced = *Result.begin();
5037 break;
5038
John McCall6e247262009-10-10 05:48:19 +00005039 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00005040 return QualType();
5041 }
5042
5043 // If we get here, it's because name lookup did not find a
5044 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor3f093272009-10-13 21:16:44 +00005045 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00005046 if (Referenced)
5047 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5048 << Name;
5049 return QualType();
5050}
Douglas Gregor4a959d82009-08-06 16:20:37 +00005051
5052namespace {
5053 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00005054 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00005055 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00005056 SourceLocation Loc;
5057 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00005058
Douglas Gregor4a959d82009-08-06 16:20:37 +00005059 public:
Mike Stump1eb44332009-09-09 15:08:12 +00005060 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005061 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005062 DeclarationName Entity)
5063 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00005064 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00005065
5066 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00005067 /// transformed.
5068 ///
5069 /// For the purposes of type reconstruction, a type has already been
5070 /// transformed if it is NULL or if it is not dependent.
5071 bool AlreadyTransformed(QualType T) {
5072 return T.isNull() || !T->isDependentType();
5073 }
Mike Stump1eb44332009-09-09 15:08:12 +00005074
5075 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00005076 /// rebuilt.
5077 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00005078
Douglas Gregor4a959d82009-08-06 16:20:37 +00005079 /// \brief Returns the name of the entity whose type is being rebuilt.
5080 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00005081
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005082 /// \brief Sets the "base" location and entity when that
5083 /// information is known based on another transformation.
5084 void setBase(SourceLocation Loc, DeclarationName Entity) {
5085 this->Loc = Loc;
5086 this->Entity = Entity;
5087 }
5088
Douglas Gregor4a959d82009-08-06 16:20:37 +00005089 /// \brief Transforms an expression by returning the expression itself
5090 /// (an identity function).
5091 ///
5092 /// FIXME: This is completely unsafe; we will need to actually clone the
5093 /// expressions.
5094 Sema::OwningExprResult TransformExpr(Expr *E) {
5095 return getSema().Owned(E);
5096 }
Mike Stump1eb44332009-09-09 15:08:12 +00005097
Douglas Gregor4a959d82009-08-06 16:20:37 +00005098 /// \brief Transforms a typename type by determining whether the type now
5099 /// refers to a member of the current instantiation, and then
5100 /// type-checking and building a QualifiedNameType (when possible).
Douglas Gregor124b8782010-02-16 19:09:40 +00005101 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL,
5102 QualType ObjectType);
Douglas Gregor4a959d82009-08-06 16:20:37 +00005103 };
5104}
5105
Mike Stump1eb44332009-09-09 15:08:12 +00005106QualType
John McCalla2becad2009-10-21 00:40:46 +00005107CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
Douglas Gregor124b8782010-02-16 19:09:40 +00005108 TypenameTypeLoc TL,
5109 QualType ObjectType) {
John McCall833ca992009-10-29 08:12:44 +00005110 TypenameType *T = TL.getTypePtr();
John McCalla2becad2009-10-21 00:40:46 +00005111
Douglas Gregor4a959d82009-08-06 16:20:37 +00005112 NestedNameSpecifier *NNS
5113 = TransformNestedNameSpecifier(T->getQualifier(),
Douglas Gregor124b8782010-02-16 19:09:40 +00005114 /*FIXME:*/SourceRange(getBaseLocation()),
5115 ObjectType);
Douglas Gregor4a959d82009-08-06 16:20:37 +00005116 if (!NNS)
5117 return QualType();
5118
5119 // If the nested-name-specifier did not change, and we cannot compute the
5120 // context corresponding to the nested-name-specifier, then this
5121 // typename type will not change; exit early.
5122 CXXScopeSpec SS;
5123 SS.setRange(SourceRange(getBaseLocation()));
5124 SS.setScopeRep(NNS);
John McCall833ca992009-10-29 08:12:44 +00005125
5126 QualType Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00005127 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall833ca992009-10-29 08:12:44 +00005128 Result = QualType(T, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00005129
5130 // Rebuild the typename type, which will probably turn into a
Douglas Gregor4a959d82009-08-06 16:20:37 +00005131 // QualifiedNameType.
John McCall833ca992009-10-29 08:12:44 +00005132 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005133 QualType NewTemplateId
Douglas Gregor4a959d82009-08-06 16:20:37 +00005134 = TransformType(QualType(TemplateId, 0));
5135 if (NewTemplateId.isNull())
5136 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005137
Douglas Gregor4a959d82009-08-06 16:20:37 +00005138 if (NNS == T->getQualifier() &&
5139 NewTemplateId == QualType(TemplateId, 0))
John McCall833ca992009-10-29 08:12:44 +00005140 Result = QualType(T, 0);
5141 else
5142 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
5143 } else
5144 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
5145 SourceRange(TL.getNameLoc()));
Mike Stump1eb44332009-09-09 15:08:12 +00005146
Douglas Gregora50ce322010-03-07 23:26:22 +00005147 if (Result.isNull())
5148 return QualType();
5149
John McCall833ca992009-10-29 08:12:44 +00005150 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
5151 NewTL.setNameLoc(TL.getNameLoc());
5152 return Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00005153}
5154
5155/// \brief Rebuilds a type within the context of the current instantiation.
5156///
Mike Stump1eb44332009-09-09 15:08:12 +00005157/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00005158/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00005159/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00005160/// partial specialization thereof). This routine will rebuild that type now
5161/// that we have entered the declarator's scope, which may produce different
5162/// canonical types, e.g.,
5163///
5164/// \code
5165/// template<typename T>
5166/// struct X {
5167/// typedef T* pointer;
5168/// pointer data();
5169/// };
5170///
5171/// template<typename T>
5172/// typename X<T>::pointer X<T>::data() { ... }
5173/// \endcode
5174///
5175/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
5176/// since we do not know that we can look into X<T> when we parsed the type.
5177/// This function will rebuild the type, performing the lookup of "pointer"
5178/// in X<T> and returning a QualifiedNameType whose canonical type is the same
5179/// as the canonical type of T*, allowing the return types of the out-of-line
5180/// definition and the declaration to match.
5181QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
5182 DeclarationName Name) {
5183 if (T.isNull() || !T->isDependentType())
5184 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00005185
Douglas Gregor4a959d82009-08-06 16:20:37 +00005186 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5187 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00005188}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005189
5190/// \brief Produces a formatted string that describes the binding of
5191/// template parameters to template arguments.
5192std::string
5193Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5194 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005195 // FIXME: For variadic templates, we'll need to get the structured list.
5196 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5197 Args.flat_size());
5198}
5199
5200std::string
5201Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5202 const TemplateArgument *Args,
5203 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005204 std::string Result;
5205
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005206 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005207 return Result;
5208
5209 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005210 if (I >= NumArgs)
5211 break;
5212
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005213 if (I == 0)
5214 Result += "[with ";
5215 else
5216 Result += ", ";
5217
5218 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5219 Result += Id->getName();
5220 } else {
5221 Result += '$';
5222 Result += llvm::utostr(I);
5223 }
5224
5225 Result += " = ";
5226
5227 switch (Args[I].getKind()) {
5228 case TemplateArgument::Null:
5229 Result += "<no value>";
5230 break;
5231
5232 case TemplateArgument::Type: {
5233 std::string TypeStr;
5234 Args[I].getAsType().getAsStringInternal(TypeStr,
5235 Context.PrintingPolicy);
5236 Result += TypeStr;
5237 break;
5238 }
5239
5240 case TemplateArgument::Declaration: {
5241 bool Unnamed = true;
5242 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5243 if (ND->getDeclName()) {
5244 Unnamed = false;
5245 Result += ND->getNameAsString();
5246 }
5247 }
5248
5249 if (Unnamed) {
5250 Result += "<anonymous>";
5251 }
5252 break;
5253 }
5254
Douglas Gregor788cd062009-11-11 01:00:40 +00005255 case TemplateArgument::Template: {
5256 std::string Str;
5257 llvm::raw_string_ostream OS(Str);
5258 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5259 Result += OS.str();
5260 break;
5261 }
5262
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005263 case TemplateArgument::Integral: {
5264 Result += Args[I].getAsIntegral()->toString(10);
5265 break;
5266 }
5267
5268 case TemplateArgument::Expression: {
5269 assert(false && "No expressions in deduced template arguments!");
5270 Result += "<expression>";
5271 break;
5272 }
5273
5274 case TemplateArgument::Pack:
5275 // FIXME: Format template argument packs
5276 Result += "<template argument pack>";
5277 break;
5278 }
5279 }
5280
5281 Result += ']';
5282 return Result;
5283}