blob: ba9e3c7df9d328bac15ec8b61ffa051f1feb7e84 [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-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 Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000018#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000020#include "clang/Parse/DeclSpec.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000021#include "clang/Parse/Template.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregorb7bfe792009-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 Stump11289f42009-09-09 15:08:12 +000033
Douglas Gregorb7bfe792009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
35 return D;
Mike Stump11289f42009-09-09 15:08:12 +000036
Douglas Gregorb7bfe792009-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 Gregor568a0712009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-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 Stump11289f42009-09-09 15:08:12 +000058
Douglas Gregorb7bfe792009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump11289f42009-09-09 15:08:12 +000061
Douglas Gregorb7bfe792009-09-02 22:59:36 +000062 return 0;
63}
64
John McCalle66edc12009-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 Gregorb7bfe792009-09-02 22:59:36 +000078TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor3cf81312009-11-03 23:16:33 +000079 const CXXScopeSpec &SS,
80 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +000081 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +000082 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +000083 TemplateTy &TemplateResult) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +000084 assert(getLangOptions().CPlusPlus && "No template names in C!");
85
Douglas Gregor3cf81312009-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
Alexis Hunted0530f2009-11-28 08:58:14 +000098 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +000099 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
100 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000101
Douglas Gregor3cf81312009-11-03 23:16:33 +0000102 default:
103 return TNK_Non_template;
104 }
Mike Stump11289f42009-09-09 15:08:12 +0000105
John McCalle66edc12009-11-24 19:00:30 +0000106 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump11289f42009-09-09 15:08:12 +0000107
Douglas Gregorff18cc12009-12-31 08:11:17 +0000108 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
109 LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +0000110 R.suppressDiagnostics();
111 LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
112 if (R.empty())
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000113 return TNK_Non_template;
114
John McCalld28ae272009-12-02 08:04:21 +0000115 TemplateName Template;
116 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000117
John McCalld28ae272009-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 Gregorb7bfe792009-09-02 22:59:36 +0000124 } else {
John McCalld28ae272009-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 Gregorb7bfe792009-09-02 22:59:36 +0000141 }
Mike Stump11289f42009-09-09 15:08:12 +0000142
John McCalld28ae272009-12-02 08:04:21 +0000143 TemplateResult = TemplateTy::make(Template);
144 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000145}
146
Douglas Gregor18473f32010-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 McCalle66edc12009-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 Gregorc119dd52010-01-12 17:06:20 +0000222 // We cannot look into a dependent object type or nested nme
223 // specifier.
John McCalle66edc12009-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 Gregorc119dd52010-01-12 17:06:20 +0000234 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-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 Gregor6da83622010-01-07 00:17:44 +0000250 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
251 Diag(Template->getLocation(), diag::note_previous_decl)
252 << Template->getDeclName();
Douglas Gregorff18cc12009-12-31 08:11:17 +0000253 } else
254 Found.clear();
255 } else {
256 Found.clear();
257 }
258 }
259
John McCalle66edc12009-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 McCallcd4b4772009-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 McCalle66edc12009-11-24 19:00:30 +0000309Sema::OwningExprResult
310Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
311 DeclarationName Name,
312 SourceLocation NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +0000313 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000314 const TemplateArgumentListInfo *TemplateArgs) {
315 NestedNameSpecifier *Qualifier
316 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
317
John McCallcd4b4772009-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 McCalle66edc12009-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 McCall2d74de92009-12-01 22:10:20 +0000327 return Owned(CXXDependentScopeMemberExpr::Create(Context,
328 /*This*/ 0, ThisType,
329 /*IsArrow*/ true,
John McCalle66edc12009-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 Gregor55ad91f2008-12-18 19:37:40 +0000350}
351
Douglas Gregor5101c242008-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 Gregor5daeee22008-12-08 18:40:42 +0000357 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-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 Stump11289f42009-09-09 15:08:12 +0000366 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-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 Gregor463421d2009-03-03 04:44:36 +0000372/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-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 Lattner83f095c2009-03-28 19:18:32 +0000375TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000376 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000377 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000378 return Temp;
379 }
380 return 0;
381}
382
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000383static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
384 const ParsedTemplateArgument &Arg) {
385
386 switch (Arg.getKind()) {
387 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000388 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000389 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
390 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000391 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-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 Yasskin1615d452009-12-12 05:05:38 +0000409 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-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 McCall6b51f282009-11-23 01:53:49 +0000415void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
416 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000417 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000418 TemplateArgs.addArgument(translateTemplateArgument(*this,
419 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000420}
421
Douglas Gregor5101c242008-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 Stump11289f42009-09-09 15:08:12 +0000428/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000429/// If the type parameter has a default argument, it will be added
430/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000431Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000432 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000433 SourceLocation KeyLoc,
434 IdentifierInfo *ParamName,
435 SourceLocation ParamNameLoc,
436 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000437 assert(S->isTemplateParamScope() &&
438 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000439 bool Invalid = false;
440
441 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000442 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000443 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000444 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000445 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000446 }
447
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000448 SourceLocation Loc = ParamNameLoc;
449 if (!ParamName)
450 Loc = KeyLoc;
451
Douglas Gregor5101c242008-12-05 18:15:24 +0000452 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000453 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
454 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000455 Ellipsis);
Douglas Gregor5101c242008-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 Lattner83f095c2009-03-28 19:18:32 +0000461 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000462 IdResolver.AddDecl(Param);
463 }
464
Chris Lattner83f095c2009-03-28 19:18:32 +0000465 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000466}
467
Douglas Gregordba32632009-02-10 19:49:53 +0000468/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000469/// Default) to the given template type parameter (TypeParam).
470void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000471 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000472 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000473 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000474 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000475 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000476
John McCallbcd03502009-12-07 02:54:59 +0000477 TypeSourceInfo *DefaultTInfo;
478 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall0ad16662009-10-29 08:12:44 +0000479
John McCallbcd03502009-12-07 02:54:59 +0000480 assert(DefaultTInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000481
Anders Carlssond3824352009-06-12 22:30:13 +0000482 // C++0x [temp.param]p9:
483 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000484 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000485 if (Parm->isParameterPack()) {
486 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000487 return;
488 }
Mike Stump11289f42009-09-09 15:08:12 +0000489
Douglas Gregordba32632009-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 Stump11289f42009-09-09 15:08:12 +0000493
Douglas Gregordba32632009-02-10 19:49:53 +0000494 // Check the template argument itself.
John McCallbcd03502009-12-07 02:54:59 +0000495 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000496 Parm->setInvalidDecl();
497 return;
498 }
499
John McCallbcd03502009-12-07 02:54:59 +0000500 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000501}
502
Douglas Gregor463421d2009-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 Stump11289f42009-09-09 15:08:12 +0000508QualType
Douglas Gregor463421d2009-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 Stump11289f42009-09-09 15:08:12 +0000517 // -- pointer to object or pointer to function,
518 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000519 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
520 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000521 // -- reference to object or reference to function,
Douglas Gregor463421d2009-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 Gregor5101c242008-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 Lattner83f095c2009-03-28 19:18:32 +0000551Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000552 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000553 unsigned Position) {
John McCallbcd03502009-12-07 02:54:59 +0000554 TypeSourceInfo *TInfo = 0;
555 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000556
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000557 assert(S->isTemplateParamScope() &&
558 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000559 bool Invalid = false;
560
561 IdentifierInfo *ParamName = D.getIdentifier();
562 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000563 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000564 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000565 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000566 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000567 }
568
Douglas Gregor463421d2009-03-03 04:44:36 +0000569 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000570 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000571 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000572 Invalid = true;
573 }
Douglas Gregor81338792009-02-10 17:43:50 +0000574
Douglas Gregor5101c242008-12-05 18:15:24 +0000575 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000576 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
577 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000578 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-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 Lattner83f095c2009-03-28 19:18:32 +0000584 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000585 IdResolver.AddDecl(Param);
586 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000587 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000588}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000589
Douglas Gregordba32632009-02-10 19:49:53 +0000590/// \brief Adds a default argument to the given non-type template
591/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000592void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000593 SourceLocation EqualLoc,
594 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000595 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000596 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000597 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000598
Douglas Gregordba32632009-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 Stump11289f42009-09-09 15:08:12 +0000602
Douglas Gregordba32632009-02-10 19:49:53 +0000603 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000604 TemplateArgument Converted;
605 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
606 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000607 TemplateParm->setInvalidDecl();
608 return;
609 }
610
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000611 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000612}
613
Douglas Gregorded2d7b2009-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 Lattner83f095c2009-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 Stump11289f42009-09-09 15:08:12 +0000624 unsigned Position) {
Douglas Gregorded2d7b2009-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 McCallf7b2fb52010-01-22 00:28:27 +0000630 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
631 TmpLoc, Depth, Position, Name,
Douglas Gregorded2d7b2009-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 Lattner83f095c2009-03-28 19:18:32 +0000646 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000647 IdResolver.AddDecl(Param);
648 }
649
Chris Lattner83f095c2009-03-28 19:18:32 +0000650 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000651}
652
Douglas Gregordba32632009-02-10 19:49:53 +0000653/// \brief Adds a default argument to the given template template
654/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000655void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000656 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000657 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000658 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000659 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000660
Douglas Gregordba32632009-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 Gregore62e6a02009-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 Gregor9167f8b2009-11-11 01:00:40 +0000673 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-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 Gregordba32632009-02-10 19:49:53 +0000677 return;
678 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000679
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000680 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000681}
682
Douglas Gregorb9bd8a92008-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 Stump11289f42009-09-09 15:08:12 +0000688 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000689 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000690 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000691 SourceLocation RAngleLoc) {
692 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000693 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000694
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000695 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000696 (NamedDecl**)Params, NumParams,
697 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000698}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000699
John McCall3e11ebe2010-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 Gregorc08f4892009-03-25 00:13:59 +0000706Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000707Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000708 SourceLocation KWLoc, const CXXScopeSpec &SS,
709 IdentifierInfo *Name, SourceLocation NameLoc,
710 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000711 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000712 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000713 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000714 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000715 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000716 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000717
718 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000719 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000720 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000721
John McCall27b5c252009-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 Gregorcd72ba92009-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 Gregorc08f4892009-03-25 00:13:59 +0000728 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000729 }
730
731 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000732 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000733 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000734 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000735 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000736 if (RequireCompleteDeclContext(SS))
737 return true;
738
Douglas Gregor1d5e9f92009-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 Stump11289f42009-09-09 15:08:12 +0000744
John McCall27b18f82009-11-17 02:14:36 +0000745 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000746 } else {
747 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000748 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000749 }
Mike Stump11289f42009-09-09 15:08:12 +0000750
Douglas Gregorcd72ba92009-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 Gregorcd72ba92009-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 Stump11289f42009-09-09 15:08:12 +0000758 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000759 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-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 McCalld43784f2009-12-18 11:25:59 +0000776 if (TUK == TUK_Friend) {
John McCall90d3bb92009-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 McCalld43784f2009-12-18 11:25:59 +0000785
786 if (PrevDecl &&
787 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
788 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
John McCall90d3bb92009-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 Gregorcd72ba92009-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 Gregor19ac2d62009-11-12 16:20:59 +0000812 /*Complain=*/true,
813 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000814 return true;
Douglas Gregorcd72ba92009-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 Gregord9034f02009-05-14 16:41:31 +0000822 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000823 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000824 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000825 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000826 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000827 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000828 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000829 }
830
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000831 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000832 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000833 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-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 Gregorc08f4892009-03-25 00:13:59 +0000838 return true;
Douglas Gregorcd72ba92009-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 Gregorc08f4892009-03-25 00:13:59 +0000854 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000855 }
856
Douglas Gregordba32632009-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 Gregored5731f2009-11-25 17:50:39 +0000861 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
862 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000863 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000864
Douglas Gregore362cea2009-05-10 22:57:19 +0000865 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000866 // declaration!
867
Mike Stump11289f42009-09-09 15:08:12 +0000868 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000869 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000870 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000871 PrevClassTemplate->getTemplatedDecl() : 0,
872 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000873 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000874
875 ClassTemplateDecl *NewTemplate
876 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
877 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000878 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000879 NewClass->setDescribedClassTemplate(NewTemplate);
880
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000881 // Build the type for the class template declaration now.
John McCalle78aac42010-03-10 03:28:59 +0000882 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
883 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000884 assert(T->isDependentType() && "Class template type is not dependent?");
885 (void)T;
886
Douglas Gregorcf915552009-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 Carlsson137108d2009-03-26 01:24:28 +0000893 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000894 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000895 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000896
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000897 // Set the lexical context of these templates
898 NewClass->setLexicalDeclContext(CurContext);
899 NewTemplate->setLexicalDeclContext(CurContext);
900
John McCall9bb74a52009-07-31 02:45:11 +0000901 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000902 NewClass->startDefinition();
903
904 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000905 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000906
John McCall27b5c252009-09-14 21:59:20 +0000907 if (TUK != TUK_Friend)
908 PushOnScopeChains(NewTemplate, S);
909 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000910 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000911 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000912 NewClass->setAccess(PrevClassTemplate->getAccess());
913 }
John McCall27b5c252009-09-14 21:59:20 +0000914
Douglas Gregor3dad8422009-09-26 06:47:28 +0000915 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
916 PrevClassTemplate != NULL);
917
John McCall27b5c252009-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 Gregor3dad8422009-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 McCall27b5c252009-09-14 21:59:20 +0000933 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000934
Douglas Gregordba32632009-02-10 19:49:53 +0000935 if (Invalid) {
936 NewTemplate->setInvalidDecl();
937 NewClass->setInvalidDecl();
938 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000939 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000940}
941
Douglas Gregored5731f2009-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 Gregordba32632009-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 Gregored5731f2009-11-25 17:50:39 +00001009/// \param TPC Describes the context in which we are checking the given
1010/// template parameter list.
1011///
Douglas Gregordba32632009-02-10 19:49:53 +00001012/// \returns true if an error occurred, false otherwise.
1013bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001014 TemplateParameterList *OldParams,
1015 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001016 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001017
Douglas Gregordba32632009-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 Gregord32e0282009-02-09 23:23:08 +00001026
Anders Carlsson327865d2009-06-12 23:20:15 +00001027 bool SawParameterPack = false;
1028 SourceLocation ParameterPackLoc;
1029
Mike Stumpc89c8e32009-02-11 23:03:27 +00001030 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001031 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-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 Carlsson327865d2009-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 Stump11289f42009-09-09 15:08:12 +00001050 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001051 diag::err_template_param_pack_must_be_last_template_parameter);
1052 Invalid = true;
1053 }
1054
Douglas Gregordba32632009-02-10 19:49:53 +00001055 if (TemplateTypeParmDecl *NewTypeParm
1056 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-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 Stump11289f42009-09-09 15:08:12 +00001066 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001067 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001068
Anders Carlsson327865d2009-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 Stump11289f42009-09-09 15:08:12 +00001074 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001075 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-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 McCall0ad16662009-10-29 08:12:44 +00001085 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-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 Stump12b8ce12009-08-04 21:02:39 +00001093 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001094 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-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 Stump12b8ce12009-08-04 21:02:39 +00001104 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001105 NonTypeTemplateParmDecl *OldNonTypeParm
1106 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001107 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-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 Stump11289f42009-09-09 15:08:12 +00001128 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001129 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001130 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001131 TemplateTemplateParmDecl *NewTemplateParm
1132 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-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 Gregordba32632009-02-10 19:49:53 +00001140 TemplateTemplateParmDecl *OldTemplateParm
1141 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001142 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001143 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001144 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1145 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-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 Stump87c57ac2009-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 Gregordba32632009-02-10 19:49:53 +00001155 NewTemplateParm->setDefaultArgument(
1156 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001157 PreviousDefaultArgLoc
1158 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001159 } else if (NewTemplateParm->hasDefaultArgument()) {
1160 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001161 PreviousDefaultArgLoc
1162 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001163 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001164 MissingDefaultArg = true;
Douglas Gregordba32632009-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 Stump11289f42009-09-09 15:08:12 +00001179 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-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 Gregord32e0282009-02-09 23:23:08 +00001193
Mike Stump11289f42009-09-09 15:08:12 +00001194/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-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 Stump11289f42009-09-09 15:08:12 +00001200///
Douglas Gregord8d297c2009-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 Gregor5c0405d2009-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 Stump11289f42009-09-09 15:08:12 +00001213/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-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 Stump11289f42009-09-09 15:08:12 +00001216/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-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 Gregor5c0405d2009-10-07 22:35:40 +00001223 unsigned NumParamLists,
1224 bool &IsExplicitSpecialization) {
1225 IsExplicitSpecialization = false;
1226
Douglas Gregord8d297c2009-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 Gregor65911492009-11-23 12:11:45 +00001231 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1232 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001233 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1234 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-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 Gregoraf050cb2010-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 McCall90034062009-12-15 02:19:47 +00001249
Mike Stump11289f42009-09-09 15:08:12 +00001250 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001251 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001252 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1253 if (!Template)
1254 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001255
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001256 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-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 Gregor65911492009-11-23 12:11:45 +00001261 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1262 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001263 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001264 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001265 }
Mike Stump11289f42009-09-09 15:08:12 +00001266
Douglas Gregord8d297c2009-07-21 23:53:31 +00001267 TemplateIdsInSpecifier.push_back(SpecType);
1268 }
1269 }
Mike Stump11289f42009-09-09 15:08:12 +00001270
Douglas Gregord8d297c2009-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 Stump11289f42009-09-09 15:08:12 +00001274
Douglas Gregord8d297c2009-07-21 23:53:31 +00001275 SourceLocation FirstTemplateLoc = DeclStartLoc;
1276 if (NumParamLists)
1277 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001278
Douglas Gregord8d297c2009-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 Gregor15301382009-07-30 17:40:51 +00001284 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1285 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-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 Stump11289f42009-09-09 15:08:12 +00001290 // FIXME: the location information here isn't great.
1291 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001292 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001293 << TemplateId
Douglas Gregord8d297c2009-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 Gregor5c0405d2009-10-07 22:35:40 +00001300 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001301 }
1302 return 0;
1303 }
Mike Stump11289f42009-09-09 15:08:12 +00001304
Douglas Gregord8d297c2009-07-21 23:53:31 +00001305 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001306 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001307 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001308 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1309
Mike Stump11289f42009-09-09 15:08:12 +00001310 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-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 McCalle78aac42010-03-10 03:28:59 +00001315 ClassTemplate->getInjectedClassNameSpecialization(Context)))
Douglas Gregor15301382009-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 Stump11289f42009-09-09 15:08:12 +00001323 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001324 ExpectedTemplateParams,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001325 true, TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00001326 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001327
1328 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001329 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001330 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001331 diag::err_template_param_list_matches_nontemplate)
1332 << TemplateId
1333 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001334 else
1335 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001336 }
Mike Stump11289f42009-09-09 15:08:12 +00001337
Douglas Gregord8d297c2009-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 Stump11289f42009-09-09 15:08:12 +00001343
Douglas Gregord8d297c2009-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 Gregor65911492009-11-23 12:11:45 +00001347 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001348 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001349 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1350 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001351 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1352 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-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 Gregord8d297c2009-07-21 23:53:31 +00001361 ++Idx;
1362 }
1363 }
Mike Stump11289f42009-09-09 15:08:12 +00001364
Douglas Gregord8d297c2009-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 Gregordc572a32009-03-30 22:58:21 +00001370QualType Sema::CheckTemplateIdType(TemplateName Name,
1371 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001372 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001373 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-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 McCall6b51f282009-11-23 01:53:49 +00001377 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001378 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001379
Douglas Gregorc40290e2009-03-09 23:48:35 +00001380 // Check that the template argument list is well-formed for this
1381 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001382 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001383 TemplateArgs.size());
1384 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001385 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001386 return QualType();
1387
Mike Stump11289f42009-09-09 15:08:12 +00001388 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001389 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001390 "Converted template argument list is too short!");
1391
1392 QualType CanonType;
1393
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001394 if (Name.isDependent() ||
1395 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001396 TemplateArgs)) {
Douglas Gregorc40290e2009-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 Gregor6bc50582009-05-07 06:41:52 +00001404 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001405 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001406 Converted.getFlatArguments(),
1407 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001408
Douglas Gregora8e02e72009-07-28 23:00:59 +00001409 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001410 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-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 Stump11289f42009-09-09 15:08:12 +00001414 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001415 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001416 // Find the class template specialization declaration that
1417 // corresponds to these arguments.
1418 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001419 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001420 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001421 Converted.flatSize(),
1422 Context);
Douglas Gregorc40290e2009-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 Stump11289f42009-09-09 15:08:12 +00001430 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001431 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001432 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001433 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001434 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001435 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1436 Decl->setLexicalDeclContext(CurContext);
1437 }
1438
1439 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001440 assert(isa<RecordType>(CanonType) &&
1441 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001442 }
Mike Stump11289f42009-09-09 15:08:12 +00001443
Douglas Gregorc40290e2009-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 McCall6b51f282009-11-23 01:53:49 +00001447 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001448}
1449
Douglas Gregor67a65642009-02-17 23:15:12 +00001450Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001451Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001452 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001453 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001454 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001455 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001456
Douglas Gregorc40290e2009-03-09 23:48:35 +00001457 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001458 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001459 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001460
John McCall6b51f282009-11-23 01:53:49 +00001461 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001462 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001463
1464 if (Result.isNull())
1465 return true;
1466
John McCallbcd03502009-12-07 02:54:59 +00001467 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-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 McCalld8fe9af2009-09-08 17:47:29 +00001477}
John McCall06f6fe8d2009-09-04 01:14:41 +00001478
John McCalld8fe9af2009-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 McCall06f6fe8d2009-09-04 01:14:41 +00001485
John McCall0ad16662009-10-29 08:12:44 +00001486 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001487 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001488 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001489
John McCalld8fe9af2009-09-08 17:47:29 +00001490 // Verify the tag specifier.
1491 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001492
John McCalld8fe9af2009-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 McCall7f41d982009-09-11 04:59:25 +00001501 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001502 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1503 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001504 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001505 }
1506 }
1507
John McCalld8fe9af2009-09-08 17:47:29 +00001508 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1509
1510 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001511}
1512
John McCalle66edc12009-11-24 19:00:30 +00001513Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1514 LookupResult &R,
1515 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001516 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-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 Stump11289f42009-09-09 15:08:12 +00001519 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001520 // though.
John McCalle66edc12009-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 Gregor3c8a0cf2009-10-22 07:19:14 +00001531 }
John McCall58cc69d2010-01-27 01:50:18 +00001532
1533 // We don't want lookup warnings at this point.
1534 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001535
John McCalle66edc12009-11-24 19:00:30 +00001536 bool Dependent
1537 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1538 &TemplateArgs);
1539 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001540 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001541 Qualifier, QualifierRange,
1542 R.getLookupName(), R.getNameLoc(),
1543 RequiresADL, TemplateArgs);
John McCall58cc69d2010-01-27 01:50:18 +00001544 ULE->addDecls(R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001545
1546 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001547}
1548
John McCalle66edc12009-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 Stump11289f42009-09-09 15:08:12 +00001560
John McCalle66edc12009-11-24 19:00:30 +00001561 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1562 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00001563
John McCalle66edc12009-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 Gregora727cb92009-06-30 22:34:41 +00001581}
1582
Douglas Gregorb67535d2009-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 Stump11289f42009-09-09 15:08:12 +00001590Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001591Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001592 const CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001593 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001594 TypeTy *ObjectType,
1595 bool EnteringContext) {
Douglas Gregor9abe2372010-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 Gregorb67535d2009-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 Gregor3cf81312009-11-03 23:16:33 +00001619 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001620 EnteringContext, Template);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001621 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1622 isa<CXXRecordDecl>(LookupCtx) &&
1623 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00001624 // This is a dependent template.
1625 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-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 Gregorb67535d2009-03-31 00:43:58 +00001630 return TemplateTy();
Douglas Gregord2e6a452010-01-14 17:47:39 +00001631 } else {
1632 // We found something; return it.
1633 return Template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001634 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001635 }
1636
Mike Stump11289f42009-09-09 15:08:12 +00001637 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001638 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-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 Gregor71395fa2009-11-04 00:56:37 +00001645 case UnqualifiedId::IK_OperatorFunctionId:
1646 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1647 Name.OperatorFunctionId.Operator));
Alexis Hunted0530f2009-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 Gregor3cf81312009-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 Gregorb67535d2009-03-31 00:43:58 +00001661}
1662
Mike Stump11289f42009-09-09 15:08:12 +00001663bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001664 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001665 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001666 const TemplateArgument &Arg = AL.getArgument();
1667
Anders Carlssonc8cbb2d2009-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 McCall0d07eb32009-10-29 18:45:58 +00001676 SourceRange SR = AL.getSourceRange();
1677 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001678 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001679
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001680 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001681 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001682
John McCallbcd03502009-12-07 02:54:59 +00001683 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001684 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001685
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001686 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001687 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001688 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001689 return false;
1690}
1691
Douglas Gregor36d7c5f2009-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 McCallbcd03502009-12-07 02:54:59 +00001714static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001715SubstDefaultTemplateArgument(Sema &SemaRef,
1716 TemplateDecl *Template,
1717 SourceLocation TemplateLoc,
1718 SourceLocation RAngleLoc,
1719 TemplateTypeParmDecl *Param,
1720 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001721 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-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 Gregor9167f8b2009-11-11 01:00:40 +00001760/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-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 Gregor9167f8b2009-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 Gregor5c80a27b2009-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 McCallbcd03502009-12-07 02:54:59 +00001847 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-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 Gregorda0fb532009-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 Gregorda0fb532009-11-11 19:31:23 +00001897 TemplateDecl *Template,
1898 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001899 SourceLocation RAngleLoc,
1900 TemplateArgumentListBuilder &Converted) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001901 // Check template type parameters.
1902 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001903 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001904
Douglas Gregoreebed722009-11-11 19:41:09 +00001905 // Check non-type template parameters.
1906 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001907 // Do substitution on the type of the non-type template parameter
1908 // with the template arguments we've seen thus far.
1909 QualType NTTPType = NTTP->getType();
1910 if (NTTPType->isDependentType()) {
1911 // Do substitution on the type of the non-type template parameter.
1912 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1913 NTTP, Converted.getFlatArguments(),
1914 Converted.flatSize(),
1915 SourceRange(TemplateLoc, RAngleLoc));
1916
1917 TemplateArgumentList TemplateArgs(Context, Converted,
1918 /*TakeArgs=*/false);
1919 NTTPType = SubstType(NTTPType,
1920 MultiLevelTemplateArgumentList(TemplateArgs),
1921 NTTP->getLocation(),
1922 NTTP->getDeclName());
1923 // If that worked, check the non-type template parameter type
1924 // for validity.
1925 if (!NTTPType.isNull())
1926 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1927 NTTP->getLocation());
1928 if (NTTPType.isNull())
1929 return true;
1930 }
1931
1932 switch (Arg.getArgument().getKind()) {
1933 case TemplateArgument::Null:
1934 assert(false && "Should never see a NULL template argument here");
1935 return true;
1936
1937 case TemplateArgument::Expression: {
1938 Expr *E = Arg.getArgument().getAsExpr();
1939 TemplateArgument Result;
1940 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1941 return true;
1942
1943 Converted.Append(Result);
1944 break;
1945 }
1946
1947 case TemplateArgument::Declaration:
1948 case TemplateArgument::Integral:
1949 // We've already checked this template argument, so just copy
1950 // it to the list of converted arguments.
1951 Converted.Append(Arg.getArgument());
1952 break;
1953
1954 case TemplateArgument::Template:
1955 // We were given a template template argument. It may not be ill-formed;
1956 // see below.
1957 if (DependentTemplateName *DTN
1958 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1959 // We have a template argument such as \c T::template X, which we
1960 // parsed as a template template argument. However, since we now
1961 // know that we need a non-type template argument, convert this
1962 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00001963 Expr *E = DependentScopeDeclRefExpr::Create(Context,
1964 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00001965 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00001966 DTN->getIdentifier(),
1967 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00001968
1969 TemplateArgument Result;
1970 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1971 return true;
1972
1973 Converted.Append(Result);
1974 break;
1975 }
1976
1977 // We have a template argument that actually does refer to a class
1978 // template, template alias, or template template parameter, and
1979 // therefore cannot be a non-type template argument.
1980 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1981 << Arg.getSourceRange();
1982
1983 Diag(Param->getLocation(), diag::note_template_param_here);
1984 return true;
1985
1986 case TemplateArgument::Type: {
1987 // We have a non-type template parameter but the template
1988 // argument is a type.
1989
1990 // C++ [temp.arg]p2:
1991 // In a template-argument, an ambiguity between a type-id and
1992 // an expression is resolved to a type-id, regardless of the
1993 // form of the corresponding template-parameter.
1994 //
1995 // We warn specifically about this case, since it can be rather
1996 // confusing for users.
1997 QualType T = Arg.getArgument().getAsType();
1998 SourceRange SR = Arg.getSourceRange();
1999 if (T->isFunctionType())
2000 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2001 else
2002 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2003 Diag(Param->getLocation(), diag::note_template_param_here);
2004 return true;
2005 }
2006
2007 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002008 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002009 break;
2010 }
2011
2012 return false;
2013 }
2014
2015
2016 // Check template template parameters.
2017 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2018
2019 // Substitute into the template parameter list of the template
2020 // template parameter, since previously-supplied template arguments
2021 // may appear within the template template parameter.
2022 {
2023 // Set up a template instantiation context.
2024 LocalInstantiationScope Scope(*this);
2025 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2026 TempParm, Converted.getFlatArguments(),
2027 Converted.flatSize(),
2028 SourceRange(TemplateLoc, RAngleLoc));
2029
2030 TemplateArgumentList TemplateArgs(Context, Converted,
2031 /*TakeArgs=*/false);
2032 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2033 SubstDecl(TempParm, CurContext,
2034 MultiLevelTemplateArgumentList(TemplateArgs)));
2035 if (!TempParm)
2036 return true;
2037
2038 // FIXME: TempParam is leaked.
2039 }
2040
2041 switch (Arg.getArgument().getKind()) {
2042 case TemplateArgument::Null:
2043 assert(false && "Should never see a NULL template argument here");
2044 return true;
2045
2046 case TemplateArgument::Template:
2047 if (CheckTemplateArgument(TempParm, Arg))
2048 return true;
2049
2050 Converted.Append(Arg.getArgument());
2051 break;
2052
2053 case TemplateArgument::Expression:
2054 case TemplateArgument::Type:
2055 // We have a template template parameter but the template
2056 // argument does not refer to a template.
2057 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2058 return true;
2059
2060 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002061 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002062 "Declaration argument with template template parameter");
2063 break;
2064 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002065 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002066 "Integral argument with template template parameter");
2067 break;
2068
2069 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002070 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002071 break;
2072 }
2073
2074 return false;
2075}
2076
Douglas Gregord32e0282009-02-09 23:23:08 +00002077/// \brief Check that the given template argument list is well-formed
2078/// for specializing the given template.
2079bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2080 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002081 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002082 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002083 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002084 TemplateParameterList *Params = Template->getTemplateParameters();
2085 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002086 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002087 bool Invalid = false;
2088
John McCall6b51f282009-11-23 01:53:49 +00002089 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2090
Mike Stump11289f42009-09-09 15:08:12 +00002091 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002092 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002093
Anders Carlsson15201f12009-06-13 02:08:00 +00002094 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002095 (NumArgs < Params->getMinRequiredArguments() &&
2096 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002097 // FIXME: point at either the first arg beyond what we can handle,
2098 // or the '>', depending on whether we have too many or too few
2099 // arguments.
2100 SourceRange Range;
2101 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002102 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002103 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2104 << (NumArgs > NumParams)
2105 << (isa<ClassTemplateDecl>(Template)? 0 :
2106 isa<FunctionTemplateDecl>(Template)? 1 :
2107 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2108 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002109 Diag(Template->getLocation(), diag::note_template_decl_here)
2110 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002111 Invalid = true;
2112 }
Mike Stump11289f42009-09-09 15:08:12 +00002113
2114 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002115 // [...] The type and form of each template-argument specified in
2116 // a template-id shall match the type and form specified for the
2117 // corresponding parameter declared by the template in its
2118 // template-parameter-list.
2119 unsigned ArgIdx = 0;
2120 for (TemplateParameterList::iterator Param = Params->begin(),
2121 ParamEnd = Params->end();
2122 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002123 if (ArgIdx > NumArgs && PartialTemplateArgs)
2124 break;
Mike Stump11289f42009-09-09 15:08:12 +00002125
Douglas Gregoreebed722009-11-11 19:41:09 +00002126 // If we have a template parameter pack, check every remaining template
2127 // argument against that template parameter pack.
2128 if ((*Param)->isTemplateParameterPack()) {
2129 Converted.BeginPack();
2130 for (; ArgIdx < NumArgs; ++ArgIdx) {
2131 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2132 TemplateLoc, RAngleLoc, Converted)) {
2133 Invalid = true;
2134 break;
2135 }
2136 }
2137 Converted.EndPack();
2138 continue;
2139 }
2140
Douglas Gregor84d49a22009-11-11 21:54:23 +00002141 if (ArgIdx < NumArgs) {
2142 // Check the template argument we were given.
2143 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2144 TemplateLoc, RAngleLoc, Converted))
2145 return true;
2146
2147 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002148 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002149
Douglas Gregor84d49a22009-11-11 21:54:23 +00002150 // We have a default template argument that we will use.
2151 TemplateArgumentLoc Arg;
2152
2153 // Retrieve the default template argument from the template
2154 // parameter. For each kind of template parameter, we substitute the
2155 // template arguments provided thus far and any "outer" template arguments
2156 // (when the template parameter was part of a nested template) into
2157 // the default argument.
2158 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2159 if (!TTP->hasDefaultArgument()) {
2160 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2161 break;
2162 }
2163
John McCallbcd03502009-12-07 02:54:59 +00002164 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002165 Template,
2166 TemplateLoc,
2167 RAngleLoc,
2168 TTP,
2169 Converted);
2170 if (!ArgType)
2171 return true;
2172
2173 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2174 ArgType);
2175 } else if (NonTypeTemplateParmDecl *NTTP
2176 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2177 if (!NTTP->hasDefaultArgument()) {
2178 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2179 break;
2180 }
2181
2182 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2183 TemplateLoc,
2184 RAngleLoc,
2185 NTTP,
2186 Converted);
2187 if (E.isInvalid())
2188 return true;
2189
2190 Expr *Ex = E.takeAs<Expr>();
2191 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2192 } else {
2193 TemplateTemplateParmDecl *TempParm
2194 = cast<TemplateTemplateParmDecl>(*Param);
2195
2196 if (!TempParm->hasDefaultArgument()) {
2197 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2198 break;
2199 }
2200
2201 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2202 TemplateLoc,
2203 RAngleLoc,
2204 TempParm,
2205 Converted);
2206 if (Name.isNull())
2207 return true;
2208
2209 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2210 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2211 TempParm->getDefaultArgument().getTemplateNameLoc());
2212 }
2213
2214 // Introduce an instantiation record that describes where we are using
2215 // the default template argument.
2216 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2217 Converted.getFlatArguments(),
2218 Converted.flatSize(),
2219 SourceRange(TemplateLoc, RAngleLoc));
2220
2221 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002222 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002223 RAngleLoc, Converted))
2224 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002225 }
2226
2227 return Invalid;
2228}
2229
2230/// \brief Check a template argument against its corresponding
2231/// template type parameter.
2232///
2233/// This routine implements the semantics of C++ [temp.arg.type]. It
2234/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002235bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002236 TypeSourceInfo *ArgInfo) {
2237 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002238 QualType Arg = ArgInfo->getType();
2239
Douglas Gregord32e0282009-02-09 23:23:08 +00002240 // C++ [temp.arg.type]p2:
2241 // A local type, a type with no linkage, an unnamed type or a type
2242 // compounded from any of these types shall not be used as a
2243 // template-argument for a template type-parameter.
2244 //
2245 // FIXME: Perform the recursive and no-linkage type checks.
2246 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002247 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002248 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002249 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002250 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002251 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2252 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2253 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2254 << QualType(Tag, 0) << SR;
2255 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002256 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002257 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2258 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002259 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2260 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002261 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2262 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2263 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002264 }
2265
2266 return false;
2267}
2268
Douglas Gregorccb07762009-02-11 19:52:55 +00002269/// \brief Checks whether the given template argument is the address
2270/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002271bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2272 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002273 bool Invalid = false;
2274
2275 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002276 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002277 Arg = Cast->getSubExpr();
2278
Sebastian Redl576fd422009-05-10 18:38:11 +00002279 // C++0x allows nullptr, and there's no further checking to be done for that.
2280 if (Arg->getType()->isNullPtrType())
2281 return false;
2282
Douglas Gregorccb07762009-02-11 19:52:55 +00002283 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002284 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002285 // A template-argument for a non-type, non-template
2286 // template-parameter shall be one of: [...]
2287 //
2288 // -- the address of an object or function with external
2289 // linkage, including function templates and function
2290 // template-ids but excluding non-static class members,
2291 // expressed as & id-expression where the & is optional if
2292 // the name refers to a function or array, or if the
2293 // corresponding template-parameter is a reference; or
2294 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002295
Douglas Gregorccb07762009-02-11 19:52:55 +00002296 // Ignore (and complain about) any excess parentheses.
2297 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2298 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002299 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002300 diag::err_template_arg_extra_parens)
2301 << Arg->getSourceRange();
2302 Invalid = true;
2303 }
2304
2305 Arg = Parens->getSubExpr();
2306 }
2307
2308 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2309 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2310 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2311 } else
2312 DRE = dyn_cast<DeclRefExpr>(Arg);
2313
Chandler Carruth724a8a12010-01-31 10:01:20 +00002314 if (!DRE)
2315 return Diag(Arg->getSourceRange().getBegin(),
2316 diag::err_template_arg_not_decl_ref)
2317 << Arg->getSourceRange();
2318
2319 // Stop checking the precise nature of the argument if it is value dependent,
2320 // it should be checked when instantiated.
2321 if (Arg->isValueDependent())
2322 return false;
2323
2324 if (!isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00002325 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002326 diag::err_template_arg_not_object_or_func_form)
2327 << Arg->getSourceRange();
2328
2329 // Cannot refer to non-static data members
2330 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2331 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2332 << Field << Arg->getSourceRange();
2333
2334 // Cannot refer to non-static member functions
2335 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2336 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00002337 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002338 diag::err_template_arg_method)
2339 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002340
Douglas Gregorccb07762009-02-11 19:52:55 +00002341 // Functions must have external linkage.
2342 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002343 if (!isExternalLinkage(Func->getLinkage())) {
Mike Stump11289f42009-09-09 15:08:12 +00002344 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002345 diag::err_template_arg_function_not_extern)
2346 << Func << Arg->getSourceRange();
2347 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2348 << true;
2349 return true;
2350 }
2351
2352 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002353 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002354 return Invalid;
2355 }
2356
2357 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002358 if (!isExternalLinkage(Var->getLinkage())) {
Mike Stump11289f42009-09-09 15:08:12 +00002359 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002360 diag::err_template_arg_object_not_extern)
2361 << Var << Arg->getSourceRange();
2362 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2363 << true;
2364 return true;
2365 }
2366
2367 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002368 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00002369 return Invalid;
2370 }
Mike Stump11289f42009-09-09 15:08:12 +00002371
Douglas Gregorccb07762009-02-11 19:52:55 +00002372 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002373 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002374 diag::err_template_arg_not_object_or_func)
2375 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002376 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002377 diag::note_template_arg_refers_here);
2378 return true;
2379}
2380
2381/// \brief Checks whether the given template argument is a pointer to
2382/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002383bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2384 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002385 bool Invalid = false;
2386
2387 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002388 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002389 Arg = Cast->getSubExpr();
2390
Sebastian Redl576fd422009-05-10 18:38:11 +00002391 // C++0x allows nullptr, and there's no further checking to be done for that.
2392 if (Arg->getType()->isNullPtrType())
2393 return false;
2394
Douglas Gregorccb07762009-02-11 19:52:55 +00002395 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002396 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002397 // A template-argument for a non-type, non-template
2398 // template-parameter shall be one of: [...]
2399 //
2400 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002401 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002402
2403 // Ignore (and complain about) any excess parentheses.
2404 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2405 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002406 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002407 diag::err_template_arg_extra_parens)
2408 << Arg->getSourceRange();
2409 Invalid = true;
2410 }
2411
2412 Arg = Parens->getSubExpr();
2413 }
2414
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002415 // A pointer-to-member constant written &Class::member.
2416 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002417 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2418 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2419 if (DRE && !DRE->getQualifier())
2420 DRE = 0;
2421 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002422 }
2423 // A constant of pointer-to-member type.
2424 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2425 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2426 if (VD->getType()->isMemberPointerType()) {
2427 if (isa<NonTypeTemplateParmDecl>(VD) ||
2428 (isa<VarDecl>(VD) &&
2429 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2430 if (Arg->isTypeDependent() || Arg->isValueDependent())
2431 Converted = TemplateArgument(Arg->Retain());
2432 else
2433 Converted = TemplateArgument(VD->getCanonicalDecl());
2434 return Invalid;
2435 }
2436 }
2437 }
2438
2439 DRE = 0;
2440 }
2441
Douglas Gregorccb07762009-02-11 19:52:55 +00002442 if (!DRE)
2443 return Diag(Arg->getSourceRange().getBegin(),
2444 diag::err_template_arg_not_pointer_to_member_form)
2445 << Arg->getSourceRange();
2446
2447 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2448 assert((isa<FieldDecl>(DRE->getDecl()) ||
2449 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2450 "Only non-static member pointers can make it here");
2451
2452 // Okay: this is the address of a non-static member, and therefore
2453 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002454 if (Arg->isTypeDependent() || Arg->isValueDependent())
2455 Converted = TemplateArgument(Arg->Retain());
2456 else
2457 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002458 return Invalid;
2459 }
2460
2461 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002462 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002463 diag::err_template_arg_not_pointer_to_member_form)
2464 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002465 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002466 diag::note_template_arg_refers_here);
2467 return true;
2468}
2469
Douglas Gregord32e0282009-02-09 23:23:08 +00002470/// \brief Check a template argument against its corresponding
2471/// non-type template parameter.
2472///
Douglas Gregor463421d2009-03-03 04:44:36 +00002473/// This routine implements the semantics of C++ [temp.arg.nontype].
2474/// It returns true if an error occurred, and false otherwise. \p
2475/// InstantiatedParamType is the type of the non-type template
2476/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002477///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002478/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002479bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002480 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002481 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002482 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2483
Douglas Gregor86560402009-02-10 23:36:10 +00002484 // If either the parameter has a dependent type or the argument is
2485 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002486 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00002487 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2488 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002489 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002490 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002491 }
Douglas Gregor86560402009-02-10 23:36:10 +00002492
2493 // C++ [temp.arg.nontype]p5:
2494 // The following conversions are performed on each expression used
2495 // as a non-type template-argument. If a non-type
2496 // template-argument cannot be converted to the type of the
2497 // corresponding template-parameter then the program is
2498 // ill-formed.
2499 //
2500 // -- for a non-type template-parameter of integral or
2501 // enumeration type, integral promotions (4.5) and integral
2502 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002503 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002504 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002505 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002506 // C++ [temp.arg.nontype]p1:
2507 // A template-argument for a non-type, non-template
2508 // template-parameter shall be one of:
2509 //
2510 // -- an integral constant-expression of integral or enumeration
2511 // type; or
2512 // -- the name of a non-type template-parameter; or
2513 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002514 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002515 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002516 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002517 diag::err_template_arg_not_integral_or_enumeral)
2518 << ArgType << Arg->getSourceRange();
2519 Diag(Param->getLocation(), diag::note_template_param_here);
2520 return true;
2521 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002522 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002523 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2524 << ArgType << Arg->getSourceRange();
2525 return true;
2526 }
2527
2528 // FIXME: We need some way to more easily get the unqualified form
2529 // of the types without going all the way to the
2530 // canonical type.
2531 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2532 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2533 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2534 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2535
2536 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002537 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002538 // Okay: no conversion necessary
2539 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2540 !ParamType->isEnumeralType()) {
2541 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002542 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002543 } else {
2544 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002545 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002546 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002547 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002548 Diag(Param->getLocation(), diag::note_template_param_here);
2549 return true;
2550 }
2551
Douglas Gregor52aba872009-03-14 00:20:21 +00002552 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002553 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002554 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002555
2556 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002557 llvm::APSInt OldValue = Value;
2558
2559 // Coerce the template argument's value to the value it will have
2560 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002561 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002562 if (Value.getBitWidth() != AllowedBits)
2563 Value.extOrTrunc(AllowedBits);
2564 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002565
2566 // Complain if an unsigned parameter received a negative value.
2567 if (IntegerType->isUnsignedIntegerType()
2568 && (OldValue.isSigned() && OldValue.isNegative())) {
2569 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2570 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2571 << Arg->getSourceRange();
2572 Diag(Param->getLocation(), diag::note_template_param_here);
2573 }
2574
2575 // Complain if we overflowed the template parameter's type.
2576 unsigned RequiredBits;
2577 if (IntegerType->isUnsignedIntegerType())
2578 RequiredBits = OldValue.getActiveBits();
2579 else if (OldValue.isUnsigned())
2580 RequiredBits = OldValue.getActiveBits() + 1;
2581 else
2582 RequiredBits = OldValue.getMinSignedBits();
2583 if (RequiredBits > AllowedBits) {
2584 Diag(Arg->getSourceRange().getBegin(),
2585 diag::warn_template_arg_too_large)
2586 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2587 << Arg->getSourceRange();
2588 Diag(Param->getLocation(), diag::note_template_param_here);
2589 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002590 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002591
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002592 // Add the value of this argument to the list of converted
2593 // arguments. We use the bitwidth and signedness of the template
2594 // parameter.
2595 if (Arg->isValueDependent()) {
2596 // The argument is value-dependent. Create a new
2597 // TemplateArgument with the converted expression.
2598 Converted = TemplateArgument(Arg);
2599 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002600 }
2601
John McCall0ad16662009-10-29 08:12:44 +00002602 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002603 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002604 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002605 return false;
2606 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002607
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002608 // Handle pointer-to-function, reference-to-function, and
2609 // pointer-to-member-function all in (roughly) the same way.
2610 if (// -- For a non-type template-parameter of type pointer to
2611 // function, only the function-to-pointer conversion (4.3) is
2612 // applied. If the template-argument represents a set of
2613 // overloaded functions (or a pointer to such), the matching
2614 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002615 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002616 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002617 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002618 // -- For a non-type template-parameter of type reference to
2619 // function, no conversions apply. If the template-argument
2620 // represents a set of overloaded functions, the matching
2621 // function is selected from the set (13.4).
2622 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002623 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002624 // -- For a non-type template-parameter of type pointer to
2625 // member function, no conversions apply. If the
2626 // template-argument represents a set of overloaded member
2627 // functions, the matching member function is selected from
2628 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002629 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002630 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002631 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002632 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002633 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002634 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002635 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002636 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2637 ParamType->isMemberPointerType())) {
2638 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002639 if (ParamType->isMemberPointerType())
2640 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2641 else
2642 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002643 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002644 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002645 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002646 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002647 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002648 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2649 return true;
2650
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002651 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002652 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002653 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002654 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002655 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002656 }
2657 }
2658
Mike Stump11289f42009-09-09 15:08:12 +00002659 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002660 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002661 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002662 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002663 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002664 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002665 Diag(Param->getLocation(), diag::note_template_param_here);
2666 return true;
2667 }
Mike Stump11289f42009-09-09 15:08:12 +00002668
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002669 if (ParamType->isMemberPointerType())
2670 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump11289f42009-09-09 15:08:12 +00002671
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002672 NamedDecl *Entity = 0;
2673 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2674 return true;
2675
Chandler Carruth724a8a12010-01-31 10:01:20 +00002676 if (Arg->isValueDependent()) {
2677 Converted = TemplateArgument(Arg);
2678 } else {
2679 if (Entity)
2680 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2681 Converted = TemplateArgument(Entity);
2682 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002683 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002684 }
2685
Chris Lattner696197c2009-02-20 21:37:53 +00002686 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002687 // -- for a non-type template-parameter of type pointer to
2688 // object, qualification conversions (4.4) and the
2689 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002690 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002691 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002692 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002693
Sebastian Redl576fd422009-05-10 18:38:11 +00002694 if (ArgType->isNullPtrType()) {
2695 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002696 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002697 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002698 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002699 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002700 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002701
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002702 if (IsQualificationConversion(ArgType, ParamType)) {
2703 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002704 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002705 }
Mike Stump11289f42009-09-09 15:08:12 +00002706
Douglas Gregor1515f762009-02-11 18:22:40 +00002707 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002708 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002709 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002710 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002711 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002712 Diag(Param->getLocation(), diag::note_template_param_here);
2713 return true;
2714 }
Mike Stump11289f42009-09-09 15:08:12 +00002715
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002716 NamedDecl *Entity = 0;
2717 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2718 return true;
2719
Chandler Carruth724a8a12010-01-31 10:01:20 +00002720 if (Arg->isValueDependent()) {
2721 Converted = TemplateArgument(Arg);
2722 } else {
2723 if (Entity)
2724 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2725 Converted = TemplateArgument(Entity);
2726 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002727 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002728 }
Mike Stump11289f42009-09-09 15:08:12 +00002729
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002730 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002731 // -- For a non-type template-parameter of type reference to
2732 // object, no conversions apply. The type referred to by the
2733 // reference may be more cv-qualified than the (otherwise
2734 // identical) type of the template-argument. The
2735 // template-parameter is bound directly to the
2736 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002737 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002738 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002739
Chandler Carruth7ceffab2010-02-03 09:37:33 +00002740 QualType ReferredType = ParamRefType->getPointeeType();
2741 if (!Context.hasSameUnqualifiedType(ReferredType, ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002742 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002743 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002744 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002745 << Arg->getSourceRange();
2746 Diag(Param->getLocation(), diag::note_template_param_here);
2747 return true;
2748 }
2749
Mike Stump11289f42009-09-09 15:08:12 +00002750 unsigned ParamQuals
Chandler Carruth7ceffab2010-02-03 09:37:33 +00002751 = Context.getCanonicalType(ReferredType).getCVRQualifiers();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002752 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002753
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002754 if ((ParamQuals | ArgQuals) != ParamQuals) {
2755 Diag(Arg->getSourceRange().getBegin(),
2756 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002757 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002758 << Arg->getSourceRange();
2759 Diag(Param->getLocation(), diag::note_template_param_here);
2760 return true;
2761 }
Mike Stump11289f42009-09-09 15:08:12 +00002762
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002763 NamedDecl *Entity = 0;
2764 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2765 return true;
2766
Chandler Carruth724a8a12010-01-31 10:01:20 +00002767 if (Arg->isValueDependent()) {
2768 Converted = TemplateArgument(Arg);
2769 } else {
2770 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2771 Converted = TemplateArgument(Entity);
2772 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002773 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002774 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002775
2776 // -- For a non-type template-parameter of type pointer to data
2777 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002778 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002779 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2780
Douglas Gregor1515f762009-02-11 18:22:40 +00002781 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002782 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002783 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002784 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002785 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002786 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002787 } else {
2788 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002789 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002790 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002791 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002792 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002793 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002794 }
2795
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002796 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002797}
2798
2799/// \brief Check a template argument against its corresponding
2800/// template template parameter.
2801///
2802/// This routine implements the semantics of C++ [temp.arg.template].
2803/// It returns true if an error occurred, and false otherwise.
2804bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002805 const TemplateArgumentLoc &Arg) {
2806 TemplateName Name = Arg.getArgument().getAsTemplate();
2807 TemplateDecl *Template = Name.getAsTemplateDecl();
2808 if (!Template) {
2809 // Any dependent template name is fine.
2810 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2811 return false;
2812 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002813
2814 // C++ [temp.arg.template]p1:
2815 // A template-argument for a template template-parameter shall be
2816 // the name of a class template, expressed as id-expression. Only
2817 // primary class templates are considered when matching the
2818 // template template argument with the corresponding parameter;
2819 // partial specializations are not considered even if their
2820 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002821 //
2822 // Note that we also allow template template parameters here, which
2823 // will happen when we are dealing with, e.g., class template
2824 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002825 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002826 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002827 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002828 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002829 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002830 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002831 << Template;
2832 }
2833
2834 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2835 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002836 true,
2837 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002838 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002839}
2840
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002841/// \brief Determine whether the given template parameter lists are
2842/// equivalent.
2843///
Mike Stump11289f42009-09-09 15:08:12 +00002844/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002845/// source code as part of a new template declaration.
2846///
2847/// \param Old The old template parameter list, typically found via
2848/// name lookup of the template declared with this template parameter
2849/// list.
2850///
2851/// \param Complain If true, this routine will produce a diagnostic if
2852/// the template parameter lists are not equivalent.
2853///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002854/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00002855///
2856/// \param TemplateArgLoc If this source location is valid, then we
2857/// are actually checking the template parameter list of a template
2858/// argument (New) against the template parameter list of its
2859/// corresponding template template parameter (Old). We produce
2860/// slightly different diagnostics in this scenario.
2861///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002862/// \returns True if the template parameter lists are equal, false
2863/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002864bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002865Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2866 TemplateParameterList *Old,
2867 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002868 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002869 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002870 if (Old->size() != New->size()) {
2871 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002872 unsigned NextDiag = diag::err_template_param_list_different_arity;
2873 if (TemplateArgLoc.isValid()) {
2874 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2875 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002876 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002877 Diag(New->getTemplateLoc(), NextDiag)
2878 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002879 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002880 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002881 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002882 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002883 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2884 }
2885
2886 return false;
2887 }
2888
2889 for (TemplateParameterList::iterator OldParm = Old->begin(),
2890 OldParmEnd = Old->end(), NewParm = New->begin();
2891 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2892 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002893 if (Complain) {
2894 unsigned NextDiag = diag::err_template_param_different_kind;
2895 if (TemplateArgLoc.isValid()) {
2896 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2897 NextDiag = diag::note_template_param_different_kind;
2898 }
2899 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002900 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00002901 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002902 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00002903 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002904 return false;
2905 }
2906
2907 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2908 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002909 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00002910 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002911 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2912 // The types of non-type template parameters must agree.
2913 NonTypeTemplateParmDecl *NewNTTP
2914 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002915
2916 // If we are matching a template template argument to a template
2917 // template parameter and one of the non-type template parameter types
2918 // is dependent, then we must wait until template instantiation time
2919 // to actually compare the arguments.
2920 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2921 (OldNTTP->getType()->isDependentType() ||
2922 NewNTTP->getType()->isDependentType()))
2923 continue;
2924
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002925 if (Context.getCanonicalType(OldNTTP->getType()) !=
2926 Context.getCanonicalType(NewNTTP->getType())) {
2927 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002928 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2929 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002930 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002931 diag::err_template_arg_template_params_mismatch);
2932 NextDiag = diag::note_template_nontype_parm_different_type;
2933 }
2934 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002935 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002936 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00002937 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002938 diag::note_template_nontype_parm_prev_declaration)
2939 << OldNTTP->getType();
2940 }
2941 return false;
2942 }
2943 } else {
2944 // The template parameter lists of template template
2945 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00002946 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002947 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002948 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002949 = cast<TemplateTemplateParmDecl>(*OldParm);
2950 TemplateTemplateParmDecl *NewTTP
2951 = cast<TemplateTemplateParmDecl>(*NewParm);
2952 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2953 OldTTP->getTemplateParameters(),
2954 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002955 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00002956 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002957 return false;
2958 }
2959 }
2960
2961 return true;
2962}
2963
2964/// \brief Check whether a template can be declared within this scope.
2965///
2966/// If the template declaration is valid in this scope, returns
2967/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002968bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002969Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002970 // Find the nearest enclosing declaration scope.
2971 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2972 (S->getFlags() & Scope::TemplateParamScope) != 0)
2973 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002974
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002975 // C++ [temp]p2:
2976 // A template-declaration can appear only as a namespace scope or
2977 // class scope declaration.
2978 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002979 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2980 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002981 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002982 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002983
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002984 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002985 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002986
2987 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2988 return false;
2989
Mike Stump11289f42009-09-09 15:08:12 +00002990 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002991 diag::err_template_outside_namespace_or_class_scope)
2992 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002993}
Douglas Gregor67a65642009-02-17 23:15:12 +00002994
Douglas Gregor54888652009-10-07 00:13:32 +00002995/// \brief Determine what kind of template specialization the given declaration
2996/// is.
2997static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2998 if (!D)
2999 return TSK_Undeclared;
3000
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003001 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3002 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003003 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3004 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003005 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3006 return Var->getTemplateSpecializationKind();
3007
Douglas Gregor54888652009-10-07 00:13:32 +00003008 return TSK_Undeclared;
3009}
3010
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003011/// \brief Check whether a specialization is well-formed in the current
3012/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003013///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003014/// This routine determines whether a template specialization can be declared
3015/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003016///
3017/// \param S the semantic analysis object for which this check is being
3018/// performed.
3019///
3020/// \param Specialized the entity being specialized or instantiated, which
3021/// may be a kind of template (class template, function template, etc.) or
3022/// a member of a class template (member function, static data member,
3023/// member class).
3024///
3025/// \param PrevDecl the previous declaration of this entity, if any.
3026///
3027/// \param Loc the location of the explicit specialization or instantiation of
3028/// this entity.
3029///
3030/// \param IsPartialSpecialization whether this is a partial specialization of
3031/// a class template.
3032///
Douglas Gregor54888652009-10-07 00:13:32 +00003033/// \returns true if there was an error that we cannot recover from, false
3034/// otherwise.
3035static bool CheckTemplateSpecializationScope(Sema &S,
3036 NamedDecl *Specialized,
3037 NamedDecl *PrevDecl,
3038 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003039 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003040 // Keep these "kind" numbers in sync with the %select statements in the
3041 // various diagnostics emitted by this routine.
3042 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003043 bool isTemplateSpecialization = false;
3044 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003045 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003046 isTemplateSpecialization = true;
3047 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003048 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003049 isTemplateSpecialization = true;
3050 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003051 EntityKind = 3;
3052 else if (isa<VarDecl>(Specialized))
3053 EntityKind = 4;
3054 else if (isa<RecordDecl>(Specialized))
3055 EntityKind = 5;
3056 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003057 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3058 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003059 return true;
3060 }
3061
Douglas Gregorf47b9112009-02-25 22:02:03 +00003062 // C++ [temp.expl.spec]p2:
3063 // An explicit specialization shall be declared in the namespace
3064 // of which the template is a member, or, for member templates, in
3065 // the namespace of which the enclosing class or enclosing class
3066 // template is a member. An explicit specialization of a member
3067 // function, member class or static data member of a class
3068 // template shall be declared in the namespace of which the class
3069 // template is a member. Such a declaration may also be a
3070 // definition. If the declaration is not a definition, the
3071 // specialization may be defined later in the name- space in which
3072 // the explicit specialization was declared, or in a namespace
3073 // that encloses the one in which the explicit specialization was
3074 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003075 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3076 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003077 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003078 return true;
3079 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003080
Douglas Gregor40fb7442009-10-07 17:30:37 +00003081 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3082 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003083 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003084 return true;
3085 }
3086
Douglas Gregore4b05162009-10-07 17:21:34 +00003087 // C++ [temp.class.spec]p6:
3088 // A class template partial specialization may be declared or redeclared
3089 // in any namespace scope in which its definition may be defined (14.5.1
3090 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003091 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003092 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003093 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003094 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003095 if ((!PrevDecl ||
3096 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3097 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3098 // There is no prior declaration of this entity, so this
3099 // specialization must be in the same context as the template
3100 // itself.
3101 if (!DC->Equals(SpecializedContext)) {
3102 if (isa<TranslationUnitDecl>(SpecializedContext))
3103 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3104 << EntityKind << Specialized;
3105 else if (isa<NamespaceDecl>(SpecializedContext))
3106 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3107 << EntityKind << Specialized
3108 << cast<NamedDecl>(SpecializedContext);
3109
3110 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3111 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003112 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003113 }
Douglas Gregor54888652009-10-07 00:13:32 +00003114
3115 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003116 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003117 // Note that HandleDeclarator() performs this check for explicit
3118 // specializations of function templates, static data members, and member
3119 // functions, so we skip the check here for those kinds of entities.
3120 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003121 // Should we refactor that check, so that it occurs later?
3122 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003123 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3124 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003125 if (isa<TranslationUnitDecl>(SpecializedContext))
3126 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3127 << EntityKind << Specialized;
3128 else if (isa<NamespaceDecl>(SpecializedContext))
3129 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3130 << EntityKind << Specialized
3131 << cast<NamedDecl>(SpecializedContext);
3132
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003133 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003134 }
Douglas Gregor54888652009-10-07 00:13:32 +00003135
3136 // FIXME: check for specialization-after-instantiation errors and such.
3137
Douglas Gregorf47b9112009-02-25 22:02:03 +00003138 return false;
3139}
Douglas Gregor54888652009-10-07 00:13:32 +00003140
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003141/// \brief Check the non-type template arguments of a class template
3142/// partial specialization according to C++ [temp.class.spec]p9.
3143///
Douglas Gregor09a30232009-06-12 22:08:06 +00003144/// \param TemplateParams the template parameters of the primary class
3145/// template.
3146///
3147/// \param TemplateArg the template arguments of the class template
3148/// partial specialization.
3149///
3150/// \param MirrorsPrimaryTemplate will be set true if the class
3151/// template partial specialization arguments are identical to the
3152/// implicit template arguments of the primary template. This is not
3153/// necessarily an error (C++0x), and it is left to the caller to diagnose
3154/// this condition when it is an error.
3155///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003156/// \returns true if there was an error, false otherwise.
3157bool Sema::CheckClassTemplatePartialSpecializationArgs(
3158 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003159 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003160 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003161 // FIXME: the interface to this function will have to change to
3162 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003163 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003164
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003165 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003166
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003167 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003168 // Determine whether the template argument list of the partial
3169 // specialization is identical to the implicit argument list of
3170 // the primary template. The caller may need to diagnostic this as
3171 // an error per C++ [temp.class.spec]p9b3.
3172 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003173 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003174 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3175 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003176 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003177 MirrorsPrimaryTemplate = false;
3178 } else if (TemplateTemplateParmDecl *TTP
3179 = dyn_cast<TemplateTemplateParmDecl>(
3180 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003181 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003182 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003183 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003184 if (!ArgDecl ||
3185 ArgDecl->getIndex() != TTP->getIndex() ||
3186 ArgDecl->getDepth() != TTP->getDepth())
3187 MirrorsPrimaryTemplate = false;
3188 }
3189 }
3190
Mike Stump11289f42009-09-09 15:08:12 +00003191 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003192 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003193 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003194 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003195 }
3196
Anders Carlsson40c1d492009-06-13 18:20:51 +00003197 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003198 if (!ArgExpr) {
3199 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003200 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003201 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003202
3203 // C++ [temp.class.spec]p8:
3204 // A non-type argument is non-specialized if it is the name of a
3205 // non-type parameter. All other non-type arguments are
3206 // specialized.
3207 //
3208 // Below, we check the two conditions that only apply to
3209 // specialized non-type arguments, so skip any non-specialized
3210 // arguments.
3211 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003212 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003213 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003214 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003215 (Param->getIndex() != NTTP->getIndex() ||
3216 Param->getDepth() != NTTP->getDepth()))
3217 MirrorsPrimaryTemplate = false;
3218
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003219 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003220 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003221
3222 // C++ [temp.class.spec]p9:
3223 // Within the argument list of a class template partial
3224 // specialization, the following restrictions apply:
3225 // -- A partially specialized non-type argument expression
3226 // shall not involve a template parameter of the partial
3227 // specialization except when the argument expression is a
3228 // simple identifier.
3229 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003230 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003231 diag::err_dependent_non_type_arg_in_partial_spec)
3232 << ArgExpr->getSourceRange();
3233 return true;
3234 }
3235
3236 // -- The type of a template parameter corresponding to a
3237 // specialized non-type argument shall not be dependent on a
3238 // parameter of the specialization.
3239 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003240 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003241 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3242 << Param->getType()
3243 << ArgExpr->getSourceRange();
3244 Diag(Param->getLocation(), diag::note_template_param_here);
3245 return true;
3246 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003247
3248 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003249 }
3250
3251 return false;
3252}
3253
Douglas Gregorc854c662010-02-26 06:03:23 +00003254/// \brief Retrieve the previous declaration of the given declaration.
3255static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3256 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3257 return VD->getPreviousDeclaration();
3258 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3259 return FD->getPreviousDeclaration();
3260 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3261 return TD->getPreviousDeclaration();
3262 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3263 return TD->getPreviousDeclaration();
3264 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3265 return FTD->getPreviousDeclaration();
3266 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3267 return CTD->getPreviousDeclaration();
3268 return 0;
3269}
3270
Douglas Gregorc08f4892009-03-25 00:13:59 +00003271Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003272Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3273 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003274 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00003275 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003276 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003277 SourceLocation TemplateNameLoc,
3278 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003279 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003280 SourceLocation RAngleLoc,
3281 AttributeList *Attr,
3282 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003283 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003284
Douglas Gregor67a65642009-02-17 23:15:12 +00003285 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003286 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003287 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003288 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3289
3290 if (!ClassTemplate) {
3291 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3292 << (Name.getAsTemplateDecl() &&
3293 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3294 return true;
3295 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003296
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003297 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003298 bool isPartialSpecialization = false;
3299
Douglas Gregorf47b9112009-02-25 22:02:03 +00003300 // Check the validity of the template headers that introduce this
3301 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003302 // FIXME: We probably shouldn't complain about these headers for
3303 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003304 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003305 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3306 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003307 TemplateParameterLists.size(),
3308 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003309 if (TemplateParams && TemplateParams->size() > 0) {
3310 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003311
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003312 // C++ [temp.class.spec]p10:
3313 // The template parameter list of a specialization shall not
3314 // contain default template argument values.
3315 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3316 Decl *Param = TemplateParams->getParam(I);
3317 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3318 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003319 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003320 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003321 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003322 }
3323 } else if (NonTypeTemplateParmDecl *NTTP
3324 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3325 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003326 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003327 diag::err_default_arg_in_partial_spec)
3328 << DefArg->getSourceRange();
3329 NTTP->setDefaultArgument(0);
3330 DefArg->Destroy(Context);
3331 }
3332 } else {
3333 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003334 if (TTP->hasDefaultArgument()) {
3335 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003336 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003337 << TTP->getDefaultArgument().getSourceRange();
3338 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003339 }
3340 }
3341 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003342 } else if (TemplateParams) {
3343 if (TUK == TUK_Friend)
3344 Diag(KWLoc, diag::err_template_spec_friend)
3345 << CodeModificationHint::CreateRemoval(
3346 SourceRange(TemplateParams->getTemplateLoc(),
3347 TemplateParams->getRAngleLoc()))
3348 << SourceRange(LAngleLoc, RAngleLoc);
3349 else
3350 isExplicitSpecialization = true;
3351 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003352 Diag(KWLoc, diag::err_template_spec_needs_header)
3353 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003354 isExplicitSpecialization = true;
3355 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003356
Douglas Gregor67a65642009-02-17 23:15:12 +00003357 // Check that the specialization uses the same tag kind as the
3358 // original template.
3359 TagDecl::TagKind Kind;
3360 switch (TagSpec) {
3361 default: assert(0 && "Unknown tag type!");
3362 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3363 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3364 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3365 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003366 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003367 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003368 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003369 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003370 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003371 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003372 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003373 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003374 diag::note_previous_use);
3375 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3376 }
3377
Douglas Gregorc40290e2009-03-09 23:48:35 +00003378 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003379 TemplateArgumentListInfo TemplateArgs;
3380 TemplateArgs.setLAngleLoc(LAngleLoc);
3381 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003382 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003383
Douglas Gregor67a65642009-02-17 23:15:12 +00003384 // Check that the template argument list is well-formed for this
3385 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003386 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3387 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003388 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3389 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003390 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003391
Mike Stump11289f42009-09-09 15:08:12 +00003392 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003393 ClassTemplate->getTemplateParameters()->size()) &&
3394 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003395
Douglas Gregor2373c592009-05-31 09:31:02 +00003396 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003397 // corresponds to these arguments.
3398 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003399 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003400 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003401 if (CheckClassTemplatePartialSpecializationArgs(
3402 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003403 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003404 return true;
3405
Douglas Gregor09a30232009-06-12 22:08:06 +00003406 if (MirrorsPrimaryTemplate) {
3407 // C++ [temp.class.spec]p9b3:
3408 //
Mike Stump11289f42009-09-09 15:08:12 +00003409 // -- The argument list of the specialization shall not be identical
3410 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003411 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003412 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00003413 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00003414 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003415 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003416 ClassTemplate->getIdentifier(),
3417 TemplateNameLoc,
3418 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003419 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003420 AS_none);
3421 }
3422
Douglas Gregor2208a292009-09-26 20:57:03 +00003423 // FIXME: Diagnose friend partial specializations
3424
Douglas Gregor92354b62010-02-09 00:37:32 +00003425 if (!Name.isDependent() &&
3426 !TemplateSpecializationType::anyDependentTemplateArguments(
3427 TemplateArgs.getArgumentArray(),
3428 TemplateArgs.size())) {
3429 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3430 << ClassTemplate->getDeclName();
3431 isPartialSpecialization = false;
3432 } else {
3433 // FIXME: Template parameter list matters, too
3434 ClassTemplatePartialSpecializationDecl::Profile(ID,
3435 Converted.getFlatArguments(),
3436 Converted.flatSize(),
3437 Context);
3438 }
3439 }
3440
3441 if (!isPartialSpecialization)
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003442 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003443 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003444 Converted.flatSize(),
3445 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003446 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003447 ClassTemplateSpecializationDecl *PrevDecl = 0;
3448
3449 if (isPartialSpecialization)
3450 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003451 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003452 InsertPos);
3453 else
3454 PrevDecl
3455 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003456
3457 ClassTemplateSpecializationDecl *Specialization = 0;
3458
Douglas Gregorf47b9112009-02-25 22:02:03 +00003459 // Check whether we can declare a class template specialization in
3460 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003461 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003462 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003463 TemplateNameLoc,
3464 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003465 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003466
Douglas Gregor15301382009-07-30 17:40:51 +00003467 // The canonical type
3468 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003469 if (PrevDecl &&
3470 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003471 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003472 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003473 // arguments was referenced but not declared, or we're only
3474 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003475 // declaration node as our own, updating its source location to
3476 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003477 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003478 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003479 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003480 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003481 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003482 // Build the canonical type that describes the converted template
3483 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003484 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3485 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003486 Converted.getFlatArguments(),
3487 Converted.flatSize());
3488
Douglas Gregor2373c592009-05-31 09:31:02 +00003489 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003490 ClassTemplatePartialSpecializationDecl *PrevPartial
3491 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003492 ClassTemplatePartialSpecializationDecl *Partial
3493 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003494 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003495 TemplateNameLoc,
3496 TemplateParams,
3497 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003498 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003499 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003500 CanonType,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003501 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00003502 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor2373c592009-05-31 09:31:02 +00003503
3504 if (PrevPartial) {
3505 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3506 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3507 } else {
3508 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3509 }
3510 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003511
Douglas Gregor21610382009-10-29 00:04:11 +00003512 // If we are providing an explicit specialization of a member class
3513 // template specialization, make a note of that.
3514 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3515 PrevPartial->setMemberSpecialization();
3516
Douglas Gregor91772d12009-06-13 00:26:55 +00003517 // Check that all of the template parameters of the class template
3518 // partial specialization are deducible from the template
3519 // arguments. If not, this class template partial specialization
3520 // will never be used.
3521 llvm::SmallVector<bool, 8> DeducibleParams;
3522 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003523 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003524 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003525 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003526 unsigned NumNonDeducible = 0;
3527 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3528 if (!DeducibleParams[I])
3529 ++NumNonDeducible;
3530
3531 if (NumNonDeducible) {
3532 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3533 << (NumNonDeducible > 1)
3534 << SourceRange(TemplateNameLoc, RAngleLoc);
3535 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3536 if (!DeducibleParams[I]) {
3537 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3538 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003539 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003540 diag::note_partial_spec_unused_parameter)
3541 << Param->getDeclName();
3542 else
Mike Stump11289f42009-09-09 15:08:12 +00003543 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003544 diag::note_partial_spec_unused_parameter)
3545 << std::string("<anonymous>");
3546 }
3547 }
3548 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003549 } else {
3550 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003551 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003552 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003553 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003554 ClassTemplate->getDeclContext(),
3555 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003556 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003557 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003558 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00003559 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor67a65642009-02-17 23:15:12 +00003560
3561 if (PrevDecl) {
3562 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3563 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3564 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003565 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003566 InsertPos);
3567 }
Douglas Gregor15301382009-07-30 17:40:51 +00003568
3569 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003570 }
3571
Douglas Gregor06db9f52009-10-12 20:18:28 +00003572 // C++ [temp.expl.spec]p6:
3573 // If a template, a member template or the member of a class template is
3574 // explicitly specialized then that specialization shall be declared
3575 // before the first use of that specialization that would cause an implicit
3576 // instantiation to take place, in every translation unit in which such a
3577 // use occurs; no diagnostic is required.
3578 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003579 bool Okay = false;
3580 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3581 // Is there any previous explicit specialization declaration?
3582 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3583 Okay = true;
3584 break;
3585 }
3586 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003587
Douglas Gregorc854c662010-02-26 06:03:23 +00003588 if (!Okay) {
3589 SourceRange Range(TemplateNameLoc, RAngleLoc);
3590 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3591 << Context.getTypeDeclType(Specialization) << Range;
3592
3593 Diag(PrevDecl->getPointOfInstantiation(),
3594 diag::note_instantiation_required_here)
3595 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003596 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003597 return true;
3598 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003599 }
3600
Douglas Gregor2208a292009-09-26 20:57:03 +00003601 // If this is not a friend, note that this is an explicit specialization.
3602 if (TUK != TUK_Friend)
3603 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003604
3605 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003606 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003607 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003608 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003609 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003610 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003611 Diag(Def->getLocation(), diag::note_previous_definition);
3612 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003613 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003614 }
3615 }
3616
Douglas Gregord56a91e2009-02-26 22:19:44 +00003617 // Build the fully-sugared type for this class template
3618 // specialization as the user wrote in the specialization
3619 // itself. This means that we'll pretty-print the type retrieved
3620 // from the specialization's declaration the way that the user
3621 // actually wrote the specialization, rather than formatting the
3622 // name based on the "canonical" representation used to store the
3623 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003624 TypeSourceInfo *WrittenTy
3625 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3626 TemplateArgs, CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003627 if (TUK != TUK_Friend)
3628 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003629 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003630
Douglas Gregor1e249f82009-02-25 22:18:32 +00003631 // C++ [temp.expl.spec]p9:
3632 // A template explicit specialization is in the scope of the
3633 // namespace in which the template was defined.
3634 //
3635 // We actually implement this paragraph where we set the semantic
3636 // context (in the creation of the ClassTemplateSpecializationDecl),
3637 // but we also maintain the lexical context where the actual
3638 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003639 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003640
Douglas Gregor67a65642009-02-17 23:15:12 +00003641 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003642 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003643 Specialization->startDefinition();
3644
Douglas Gregor2208a292009-09-26 20:57:03 +00003645 if (TUK == TUK_Friend) {
3646 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3647 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00003648 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00003649 /*FIXME:*/KWLoc);
3650 Friend->setAccess(AS_public);
3651 CurContext->addDecl(Friend);
3652 } else {
3653 // Add the specialization into its lexical context, so that it can
3654 // be seen when iterating through the list of declarations in that
3655 // context. However, specializations are not found by name lookup.
3656 CurContext->addDecl(Specialization);
3657 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003658 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003659}
Douglas Gregor333489b2009-03-27 23:10:48 +00003660
Mike Stump11289f42009-09-09 15:08:12 +00003661Sema::DeclPtrTy
3662Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003663 MultiTemplateParamsArg TemplateParameterLists,
3664 Declarator &D) {
3665 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3666}
3667
Mike Stump11289f42009-09-09 15:08:12 +00003668Sema::DeclPtrTy
3669Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003670 MultiTemplateParamsArg TemplateParameterLists,
3671 Declarator &D) {
3672 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3673 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3674 "Not a function declarator!");
3675 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003676
Douglas Gregor17a7c122009-06-24 00:54:41 +00003677 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003678 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003679 }
Mike Stump11289f42009-09-09 15:08:12 +00003680
Douglas Gregor17a7c122009-06-24 00:54:41 +00003681 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003682
3683 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003684 move(TemplateParameterLists),
3685 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003686 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003687 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003688 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003689 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003690 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3691 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003692 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003693}
3694
John McCall4f7ced62010-02-11 01:33:53 +00003695/// \brief Strips various properties off an implicit instantiation
3696/// that has just been explicitly specialized.
3697static void StripImplicitInstantiation(NamedDecl *D) {
3698 D->invalidateAttrs();
3699
3700 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3701 FD->setInlineSpecified(false);
3702 }
3703}
3704
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003705/// \brief Diagnose cases where we have an explicit template specialization
3706/// before/after an explicit template instantiation, producing diagnostics
3707/// for those cases where they are required and determining whether the
3708/// new specialization/instantiation will have any effect.
3709///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003710/// \param NewLoc the location of the new explicit specialization or
3711/// instantiation.
3712///
3713/// \param NewTSK the kind of the new explicit specialization or instantiation.
3714///
3715/// \param PrevDecl the previous declaration of the entity.
3716///
3717/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3718///
3719/// \param PrevPointOfInstantiation if valid, indicates where the previus
3720/// declaration was instantiated (either implicitly or explicitly).
3721///
3722/// \param SuppressNew will be set to true to indicate that the new
3723/// specialization or instantiation has no effect and should be ignored.
3724///
3725/// \returns true if there was an error that should prevent the introduction of
3726/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003727bool
3728Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3729 TemplateSpecializationKind NewTSK,
3730 NamedDecl *PrevDecl,
3731 TemplateSpecializationKind PrevTSK,
3732 SourceLocation PrevPointOfInstantiation,
3733 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003734 SuppressNew = false;
3735
3736 switch (NewTSK) {
3737 case TSK_Undeclared:
3738 case TSK_ImplicitInstantiation:
3739 assert(false && "Don't check implicit instantiations here");
3740 return false;
3741
3742 case TSK_ExplicitSpecialization:
3743 switch (PrevTSK) {
3744 case TSK_Undeclared:
3745 case TSK_ExplicitSpecialization:
3746 // Okay, we're just specializing something that is either already
3747 // explicitly specialized or has merely been mentioned without any
3748 // instantiation.
3749 return false;
3750
3751 case TSK_ImplicitInstantiation:
3752 if (PrevPointOfInstantiation.isInvalid()) {
3753 // The declaration itself has not actually been instantiated, so it is
3754 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00003755 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003756 return false;
3757 }
3758 // Fall through
3759
3760 case TSK_ExplicitInstantiationDeclaration:
3761 case TSK_ExplicitInstantiationDefinition:
3762 assert((PrevTSK == TSK_ImplicitInstantiation ||
3763 PrevPointOfInstantiation.isValid()) &&
3764 "Explicit instantiation without point of instantiation?");
3765
3766 // C++ [temp.expl.spec]p6:
3767 // If a template, a member template or the member of a class template
3768 // is explicitly specialized then that specialization shall be declared
3769 // before the first use of that specialization that would cause an
3770 // implicit instantiation to take place, in every translation unit in
3771 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00003772 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3773 // Is there any previous explicit specialization declaration?
3774 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
3775 return false;
3776 }
3777
Douglas Gregor1d957a32009-10-27 18:42:08 +00003778 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003779 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003780 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003781 << (PrevTSK != TSK_ImplicitInstantiation);
3782
3783 return true;
3784 }
3785 break;
3786
3787 case TSK_ExplicitInstantiationDeclaration:
3788 switch (PrevTSK) {
3789 case TSK_ExplicitInstantiationDeclaration:
3790 // This explicit instantiation declaration is redundant (that's okay).
3791 SuppressNew = true;
3792 return false;
3793
3794 case TSK_Undeclared:
3795 case TSK_ImplicitInstantiation:
3796 // We're explicitly instantiating something that may have already been
3797 // implicitly instantiated; that's fine.
3798 return false;
3799
3800 case TSK_ExplicitSpecialization:
3801 // C++0x [temp.explicit]p4:
3802 // For a given set of template parameters, if an explicit instantiation
3803 // of a template appears after a declaration of an explicit
3804 // specialization for that template, the explicit instantiation has no
3805 // effect.
John McCall6b21eb52010-03-02 23:09:38 +00003806 SuppressNew = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003807 return false;
3808
3809 case TSK_ExplicitInstantiationDefinition:
3810 // C++0x [temp.explicit]p10:
3811 // If an entity is the subject of both an explicit instantiation
3812 // declaration and an explicit instantiation definition in the same
3813 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003814 Diag(NewLoc,
3815 diag::err_explicit_instantiation_declaration_after_definition);
3816 Diag(PrevPointOfInstantiation,
3817 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003818 assert(PrevPointOfInstantiation.isValid() &&
3819 "Explicit instantiation without point of instantiation?");
3820 SuppressNew = true;
3821 return false;
3822 }
3823 break;
3824
3825 case TSK_ExplicitInstantiationDefinition:
3826 switch (PrevTSK) {
3827 case TSK_Undeclared:
3828 case TSK_ImplicitInstantiation:
3829 // We're explicitly instantiating something that may have already been
3830 // implicitly instantiated; that's fine.
3831 return false;
3832
3833 case TSK_ExplicitSpecialization:
3834 // C++ DR 259, C++0x [temp.explicit]p4:
3835 // For a given set of template parameters, if an explicit
3836 // instantiation of a template appears after a declaration of
3837 // an explicit specialization for that template, the explicit
3838 // instantiation has no effect.
3839 //
3840 // In C++98/03 mode, we only give an extension warning here, because it
3841 // is not not harmful to try to explicitly instantiate something that
3842 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003843 if (!getLangOptions().CPlusPlus0x) {
3844 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003845 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003846 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003847 diag::note_previous_template_specialization);
3848 }
3849 SuppressNew = true;
3850 return false;
3851
3852 case TSK_ExplicitInstantiationDeclaration:
3853 // We're explicity instantiating a definition for something for which we
3854 // were previously asked to suppress instantiations. That's fine.
3855 return false;
3856
3857 case TSK_ExplicitInstantiationDefinition:
3858 // C++0x [temp.spec]p5:
3859 // For a given template and a given set of template-arguments,
3860 // - an explicit instantiation definition shall appear at most once
3861 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003862 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003863 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003864 Diag(PrevPointOfInstantiation,
3865 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003866 SuppressNew = true;
3867 return false;
3868 }
3869 break;
3870 }
3871
3872 assert(false && "Missing specialization/instantiation case?");
3873
3874 return false;
3875}
3876
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003877/// \brief Perform semantic analysis for the given function template
3878/// specialization.
3879///
3880/// This routine performs all of the semantic analysis required for an
3881/// explicit function template specialization. On successful completion,
3882/// the function declaration \p FD will become a function template
3883/// specialization.
3884///
3885/// \param FD the function declaration, which will be updated to become a
3886/// function template specialization.
3887///
3888/// \param HasExplicitTemplateArgs whether any template arguments were
3889/// explicitly provided.
3890///
3891/// \param LAngleLoc the location of the left angle bracket ('<'), if
3892/// template arguments were explicitly provided.
3893///
3894/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3895/// if any.
3896///
3897/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3898/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3899/// true as in, e.g., \c void sort<>(char*, char*);
3900///
3901/// \param RAngleLoc the location of the right angle bracket ('>'), if
3902/// template arguments were explicitly provided.
3903///
3904/// \param PrevDecl the set of declarations that
3905bool
3906Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00003907 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00003908 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003909 // The set of function template specializations that could match this
3910 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00003911 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003912
3913 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00003914 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3915 I != E; ++I) {
3916 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3917 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003918 // Only consider templates found within the same semantic lookup scope as
3919 // FD.
3920 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3921 continue;
3922
3923 // C++ [temp.expl.spec]p11:
3924 // A trailing template-argument can be left unspecified in the
3925 // template-id naming an explicit function template specialization
3926 // provided it can be deduced from the function argument type.
3927 // Perform template argument deduction to determine whether we may be
3928 // specializing this template.
3929 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00003930 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003931 FunctionDecl *Specialization = 0;
3932 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00003933 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003934 FD->getType(),
3935 Specialization,
3936 Info)) {
3937 // FIXME: Template argument deduction failed; record why it failed, so
3938 // that we can provide nifty diagnostics.
3939 (void)TDK;
3940 continue;
3941 }
3942
3943 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00003944 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003945 }
3946 }
3947
Douglas Gregor5de279c2009-09-26 03:41:46 +00003948 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00003949 UnresolvedSetIterator Result
3950 = getMostSpecialized(Candidates.begin(), Candidates.end(),
3951 TPOC_Other, FD->getLocation(),
Douglas Gregor5de279c2009-09-26 03:41:46 +00003952 PartialDiagnostic(diag::err_function_template_spec_no_match)
3953 << FD->getDeclName(),
3954 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00003955 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor5de279c2009-09-26 03:41:46 +00003956 PartialDiagnostic(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00003957 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003958 return true;
John McCall58cc69d2010-01-27 01:50:18 +00003959
3960 // Ignore access information; it doesn't figure into redeclaration checking.
3961 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003962
3963 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003964 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00003965
3966 // If this is a friend declaration, then we're not really declaring
3967 // an explicit specialization.
3968 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003969
Douglas Gregor54888652009-10-07 00:13:32 +00003970 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00003971 if (!isFriend &&
3972 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00003973 Specialization->getPrimaryTemplate(),
3974 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003975 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003976 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003977
3978 // C++ [temp.expl.spec]p6:
3979 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003980 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003981 // before the first use of that specialization that would cause an implicit
3982 // instantiation to take place, in every translation unit in which such a
3983 // use occurs; no diagnostic is required.
3984 FunctionTemplateSpecializationInfo *SpecInfo
3985 = Specialization->getTemplateSpecializationInfo();
3986 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00003987
3988 bool SuppressNew = false;
John McCall816d75b2010-03-24 07:46:06 +00003989 if (!isFriend &&
3990 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00003991 TSK_ExplicitSpecialization,
3992 Specialization,
3993 SpecInfo->getTemplateSpecializationKind(),
3994 SpecInfo->getPointOfInstantiation(),
3995 SuppressNew))
Douglas Gregor06db9f52009-10-12 20:18:28 +00003996 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00003997
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003998 // Mark the prior declaration as an explicit specialization, so that later
3999 // clients know that this is an explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004000 if (!isFriend)
4001 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004002
4003 // Turn the given function declaration into a function template
4004 // specialization, with the template arguments from the previous
4005 // specialization.
Douglas Gregord5058122010-02-11 01:19:42 +00004006 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004007 new (Context) TemplateArgumentList(
4008 *Specialization->getTemplateSpecializationArgs()),
4009 /*InsertPos=*/0,
John McCall816d75b2010-03-24 07:46:06 +00004010 SpecInfo->getTemplateSpecializationKind());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004011
4012 // The "previous declaration" for this function template specialization is
4013 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004014 Previous.clear();
4015 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004016 return false;
4017}
4018
Douglas Gregor86d142a2009-10-08 07:24:58 +00004019/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004020/// specialization.
4021///
4022/// This routine performs all of the semantic analysis required for an
4023/// explicit member function specialization. On successful completion,
4024/// the function declaration \p FD will become a member function
4025/// specialization.
4026///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004027/// \param Member the member declaration, which will be updated to become a
4028/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004029///
John McCall1f82f242009-11-18 22:49:29 +00004030/// \param Previous the set of declarations, one of which may be specialized
4031/// by this function specialization; the set will be modified to contain the
4032/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004033bool
John McCall1f82f242009-11-18 22:49:29 +00004034Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004035 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
4036
4037 // Try to find the member we are instantiating.
4038 NamedDecl *Instantiation = 0;
4039 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004040 MemberSpecializationInfo *MSInfo = 0;
4041
John McCall1f82f242009-11-18 22:49:29 +00004042 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004043 // Nowhere to look anyway.
4044 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004045 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4046 I != E; ++I) {
4047 NamedDecl *D = (*I)->getUnderlyingDecl();
4048 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004049 if (Context.hasSameType(Function->getType(), Method->getType())) {
4050 Instantiation = Method;
4051 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004052 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004053 break;
4054 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004055 }
4056 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004057 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004058 VarDecl *PrevVar;
4059 if (Previous.isSingleResult() &&
4060 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004061 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004062 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004063 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004064 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004065 }
4066 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004067 CXXRecordDecl *PrevRecord;
4068 if (Previous.isSingleResult() &&
4069 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4070 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004071 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004072 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004073 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004074 }
4075
4076 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004077 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004078 // specializations are always out-of-line, the caller will complain about
4079 // this mismatch later.
4080 return false;
4081 }
4082
Douglas Gregor86d142a2009-10-08 07:24:58 +00004083 // Make sure that this is a specialization of a member.
4084 if (!InstantiatedFrom) {
4085 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4086 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004087 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4088 return true;
4089 }
4090
Douglas Gregor06db9f52009-10-12 20:18:28 +00004091 // C++ [temp.expl.spec]p6:
4092 // If a template, a member template or the member of a class template is
4093 // explicitly specialized then that spe- cialization shall be declared
4094 // before the first use of that specialization that would cause an implicit
4095 // instantiation to take place, in every translation unit in which such a
4096 // use occurs; no diagnostic is required.
4097 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004098
4099 bool SuppressNew = false;
4100 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4101 TSK_ExplicitSpecialization,
4102 Instantiation,
4103 MSInfo->getTemplateSpecializationKind(),
4104 MSInfo->getPointOfInstantiation(),
4105 SuppressNew))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004106 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004107
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004108 // Check the scope of this explicit specialization.
4109 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004110 InstantiatedFrom,
4111 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004112 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004113 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004114
Douglas Gregor86d142a2009-10-08 07:24:58 +00004115 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004116 // the original declaration to note that it is an explicit specialization
4117 // (if it was previously an implicit instantiation). This latter step
4118 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004119 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004120 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4121 if (InstantiationFunction->getTemplateSpecializationKind() ==
4122 TSK_ImplicitInstantiation) {
4123 InstantiationFunction->setTemplateSpecializationKind(
4124 TSK_ExplicitSpecialization);
4125 InstantiationFunction->setLocation(Member->getLocation());
4126 }
4127
Douglas Gregor86d142a2009-10-08 07:24:58 +00004128 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4129 cast<CXXMethodDecl>(InstantiatedFrom),
4130 TSK_ExplicitSpecialization);
4131 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004132 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4133 if (InstantiationVar->getTemplateSpecializationKind() ==
4134 TSK_ImplicitInstantiation) {
4135 InstantiationVar->setTemplateSpecializationKind(
4136 TSK_ExplicitSpecialization);
4137 InstantiationVar->setLocation(Member->getLocation());
4138 }
4139
Douglas Gregor86d142a2009-10-08 07:24:58 +00004140 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4141 cast<VarDecl>(InstantiatedFrom),
4142 TSK_ExplicitSpecialization);
4143 } else {
4144 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004145 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4146 if (InstantiationClass->getTemplateSpecializationKind() ==
4147 TSK_ImplicitInstantiation) {
4148 InstantiationClass->setTemplateSpecializationKind(
4149 TSK_ExplicitSpecialization);
4150 InstantiationClass->setLocation(Member->getLocation());
4151 }
4152
Douglas Gregor86d142a2009-10-08 07:24:58 +00004153 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004154 cast<CXXRecordDecl>(InstantiatedFrom),
4155 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004156 }
4157
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004158 // Save the caller the trouble of having to figure out which declaration
4159 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004160 Previous.clear();
4161 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004162 return false;
4163}
4164
Douglas Gregore47f5a72009-10-14 23:41:34 +00004165/// \brief Check the scope of an explicit instantiation.
4166static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4167 SourceLocation InstLoc,
4168 bool WasQualifiedName) {
4169 DeclContext *ExpectedContext
4170 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4171 DeclContext *CurContext = S.CurContext->getLookupContext();
4172
4173 // C++0x [temp.explicit]p2:
4174 // An explicit instantiation shall appear in an enclosing namespace of its
4175 // template.
4176 //
4177 // This is DR275, which we do not retroactively apply to C++98/03.
4178 if (S.getLangOptions().CPlusPlus0x &&
4179 !CurContext->Encloses(ExpectedContext)) {
4180 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4181 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4182 << D << NS;
4183 else
4184 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4185 << D;
4186 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4187 return;
4188 }
4189
4190 // C++0x [temp.explicit]p2:
4191 // If the name declared in the explicit instantiation is an unqualified
4192 // name, the explicit instantiation shall appear in the namespace where
4193 // its template is declared or, if that namespace is inline (7.3.1), any
4194 // namespace from its enclosing namespace set.
4195 if (WasQualifiedName)
4196 return;
4197
4198 if (CurContext->Equals(ExpectedContext))
4199 return;
4200
4201 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4202 << D << ExpectedContext;
4203 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4204}
4205
4206/// \brief Determine whether the given scope specifier has a template-id in it.
4207static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4208 if (!SS.isSet())
4209 return false;
4210
4211 // C++0x [temp.explicit]p2:
4212 // If the explicit instantiation is for a member function, a member class
4213 // or a static data member of a class template specialization, the name of
4214 // the class template specialization in the qualified-id for the member
4215 // name shall be a simple-template-id.
4216 //
4217 // C++98 has the same restriction, just worded differently.
4218 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4219 NNS; NNS = NNS->getPrefix())
4220 if (Type *T = NNS->getAsType())
4221 if (isa<TemplateSpecializationType>(T))
4222 return true;
4223
4224 return false;
4225}
4226
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004227// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00004228// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00004229Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004230Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004231 SourceLocation ExternLoc,
4232 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004233 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004234 SourceLocation KWLoc,
4235 const CXXScopeSpec &SS,
4236 TemplateTy TemplateD,
4237 SourceLocation TemplateNameLoc,
4238 SourceLocation LAngleLoc,
4239 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004240 SourceLocation RAngleLoc,
4241 AttributeList *Attr) {
4242 // Find the class template we're specializing
4243 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004244 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004245 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4246
4247 // Check that the specialization uses the same tag kind as the
4248 // original template.
4249 TagDecl::TagKind Kind;
4250 switch (TagSpec) {
4251 default: assert(0 && "Unknown tag type!");
4252 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4253 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4254 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4255 }
Douglas Gregord9034f02009-05-14 16:41:31 +00004256 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004257 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004258 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004259 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004260 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00004261 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004262 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004263 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004264 diag::note_previous_use);
4265 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4266 }
4267
Douglas Gregore47f5a72009-10-14 23:41:34 +00004268 // C++0x [temp.explicit]p2:
4269 // There are two forms of explicit instantiation: an explicit instantiation
4270 // definition and an explicit instantiation declaration. An explicit
4271 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004272 TemplateSpecializationKind TSK
4273 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4274 : TSK_ExplicitInstantiationDeclaration;
4275
Douglas Gregora1f49972009-05-13 00:25:59 +00004276 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004277 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004278 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004279
4280 // Check that the template argument list is well-formed for this
4281 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004282 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4283 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004284 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4285 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004286 return true;
4287
Mike Stump11289f42009-09-09 15:08:12 +00004288 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004289 ClassTemplate->getTemplateParameters()->size()) &&
4290 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004291
Douglas Gregora1f49972009-05-13 00:25:59 +00004292 // Find the class template specialization declaration that
4293 // corresponds to these arguments.
4294 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004295 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004296 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004297 Converted.flatSize(),
4298 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004299 void *InsertPos = 0;
4300 ClassTemplateSpecializationDecl *PrevDecl
4301 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4302
Douglas Gregor54888652009-10-07 00:13:32 +00004303 // C++0x [temp.explicit]p2:
4304 // [...] An explicit instantiation shall appear in an enclosing
4305 // namespace of its template. [...]
4306 //
4307 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004308 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4309 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004310
Douglas Gregora1f49972009-05-13 00:25:59 +00004311 ClassTemplateSpecializationDecl *Specialization = 0;
4312
Douglas Gregor0681a352009-11-25 06:01:46 +00004313 bool ReusedDecl = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004314 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00004315 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004316 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004317 PrevDecl,
4318 PrevDecl->getSpecializationKind(),
4319 PrevDecl->getPointOfInstantiation(),
4320 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00004321 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004322
Douglas Gregor12e49d32009-10-15 22:53:21 +00004323 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004324 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00004325
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004326 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4327 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4328 // Since the only prior class template specialization with these
4329 // arguments was referenced but not declared, reuse that
4330 // declaration node as our own, updating its source location to
4331 // reflect our new declaration.
4332 Specialization = PrevDecl;
4333 Specialization->setLocation(TemplateNameLoc);
4334 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004335 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004336 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004337 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004338
4339 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004340 // Create a new class template specialization declaration node for
4341 // this explicit specialization.
4342 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00004343 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00004344 ClassTemplate->getDeclContext(),
4345 TemplateNameLoc,
4346 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004347 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004348 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004349
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004350 if (PrevDecl) {
4351 // Remove the previous declaration from the folding set, since we want
4352 // to introduce a new declaration.
4353 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4354 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4355 }
4356
4357 // Insert the new specialization.
4358 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004359 }
4360
4361 // Build the fully-sugared type for this explicit instantiation as
4362 // the user wrote in the explicit instantiation itself. This means
4363 // that we'll pretty-print the type retrieved from the
4364 // specialization's declaration the way that the user actually wrote
4365 // the explicit instantiation, rather than formatting the name based
4366 // on the "canonical" representation used to store the template
4367 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004368 TypeSourceInfo *WrittenTy
4369 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4370 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004371 Context.getTypeDeclType(Specialization));
4372 Specialization->setTypeAsWritten(WrittenTy);
4373 TemplateArgsIn.release();
4374
Douglas Gregor0681a352009-11-25 06:01:46 +00004375 if (!ReusedDecl) {
4376 // Add the explicit instantiation into its lexical context. However,
4377 // since explicit instantiations are never found by name lookup, we
4378 // just put it into the declaration context directly.
4379 Specialization->setLexicalDeclContext(CurContext);
4380 CurContext->addDecl(Specialization);
4381 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004382
4383 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004384 // A definition of a class template or class member template
4385 // shall be in scope at the point of the explicit instantiation of
4386 // the class template or class member template.
4387 //
4388 // This check comes when we actually try to perform the
4389 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004390 ClassTemplateSpecializationDecl *Def
4391 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004392 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004393 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004394 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00004395
4396 // Instantiate the members of this class template specialization.
4397 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004398 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004399 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004400 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4401
4402 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4403 // TSK_ExplicitInstantiationDefinition
4404 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4405 TSK == TSK_ExplicitInstantiationDefinition)
4406 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004407
Douglas Gregor12e49d32009-10-15 22:53:21 +00004408 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004409 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004410
4411 return DeclPtrTy::make(Specialization);
4412}
4413
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004414// Explicit instantiation of a member class of a class template.
4415Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004416Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004417 SourceLocation ExternLoc,
4418 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004419 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004420 SourceLocation KWLoc,
4421 const CXXScopeSpec &SS,
4422 IdentifierInfo *Name,
4423 SourceLocation NameLoc,
4424 AttributeList *Attr) {
4425
Douglas Gregord6ab8742009-05-28 23:31:59 +00004426 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004427 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004428 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004429 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004430 MultiTemplateParamsArg(*this, 0, 0),
4431 Owned, IsDependent);
4432 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4433
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004434 if (!TagD)
4435 return true;
4436
4437 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4438 if (Tag->isEnum()) {
4439 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4440 << Context.getTypeDeclType(Tag);
4441 return true;
4442 }
4443
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004444 if (Tag->isInvalidDecl())
4445 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004446
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004447 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4448 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4449 if (!Pattern) {
4450 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4451 << Context.getTypeDeclType(Record);
4452 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4453 return true;
4454 }
4455
Douglas Gregore47f5a72009-10-14 23:41:34 +00004456 // C++0x [temp.explicit]p2:
4457 // If the explicit instantiation is for a class or member class, the
4458 // elaborated-type-specifier in the declaration shall include a
4459 // simple-template-id.
4460 //
4461 // C++98 has the same restriction, just worded differently.
4462 if (!ScopeSpecifierHasTemplateId(SS))
4463 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4464 << Record << SS.getRange();
4465
4466 // C++0x [temp.explicit]p2:
4467 // There are two forms of explicit instantiation: an explicit instantiation
4468 // definition and an explicit instantiation declaration. An explicit
4469 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004470 TemplateSpecializationKind TSK
4471 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4472 : TSK_ExplicitInstantiationDeclaration;
4473
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004474 // C++0x [temp.explicit]p2:
4475 // [...] An explicit instantiation shall appear in an enclosing
4476 // namespace of its template. [...]
4477 //
4478 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004479 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004480
4481 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004482 CXXRecordDecl *PrevDecl
4483 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004484 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004485 PrevDecl = Record;
4486 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004487 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4488 bool SuppressNew = false;
4489 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004490 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004491 PrevDecl,
4492 MSInfo->getTemplateSpecializationKind(),
4493 MSInfo->getPointOfInstantiation(),
4494 SuppressNew))
4495 return true;
4496 if (SuppressNew)
4497 return TagD;
4498 }
4499
Douglas Gregor12e49d32009-10-15 22:53:21 +00004500 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004501 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004502 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004503 // C++ [temp.explicit]p3:
4504 // A definition of a member class of a class template shall be in scope
4505 // at the point of an explicit instantiation of the member class.
4506 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004507 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004508 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004509 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4510 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004511 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4512 << Pattern;
4513 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004514 } else {
4515 if (InstantiateClass(NameLoc, Record, Def,
4516 getTemplateInstantiationArgs(Record),
4517 TSK))
4518 return true;
4519
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004520 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004521 if (!RecordDef)
4522 return true;
4523 }
4524 }
4525
4526 // Instantiate all of the members of the class.
4527 InstantiateClassMembers(NameLoc, RecordDef,
4528 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004529
Mike Stump87c57ac2009-05-16 07:39:55 +00004530 // FIXME: We don't have any representation for explicit instantiations of
4531 // member classes. Such a representation is not needed for compilation, but it
4532 // should be available for clients that want to see all of the declarations in
4533 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004534 return TagD;
4535}
4536
Douglas Gregor450f00842009-09-25 18:43:00 +00004537Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4538 SourceLocation ExternLoc,
4539 SourceLocation TemplateLoc,
4540 Declarator &D) {
4541 // Explicit instantiations always require a name.
4542 DeclarationName Name = GetNameForDeclarator(D);
4543 if (!Name) {
4544 if (!D.isInvalidType())
4545 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4546 diag::err_explicit_instantiation_requires_name)
4547 << D.getDeclSpec().getSourceRange()
4548 << D.getSourceRange();
4549
4550 return true;
4551 }
4552
4553 // The scope passed in may not be a decl scope. Zip up the scope tree until
4554 // we find one that is.
4555 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4556 (S->getFlags() & Scope::TemplateParamScope) != 0)
4557 S = S->getParent();
4558
4559 // Determine the type of the declaration.
4560 QualType R = GetTypeForDeclarator(D, S, 0);
4561 if (R.isNull())
4562 return true;
4563
4564 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4565 // Cannot explicitly instantiate a typedef.
4566 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4567 << Name;
4568 return true;
4569 }
4570
Douglas Gregor3c74d412009-10-14 20:14:33 +00004571 // C++0x [temp.explicit]p1:
4572 // [...] An explicit instantiation of a function template shall not use the
4573 // inline or constexpr specifiers.
4574 // Presumably, this also applies to member functions of class templates as
4575 // well.
4576 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4577 Diag(D.getDeclSpec().getInlineSpecLoc(),
4578 diag::err_explicit_instantiation_inline)
Chris Lattner3c7b86f2009-12-06 17:36:05 +00004579 <<CodeModificationHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004580
4581 // FIXME: check for constexpr specifier.
4582
Douglas Gregore47f5a72009-10-14 23:41:34 +00004583 // C++0x [temp.explicit]p2:
4584 // There are two forms of explicit instantiation: an explicit instantiation
4585 // definition and an explicit instantiation declaration. An explicit
4586 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004587 TemplateSpecializationKind TSK
4588 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4589 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004590
John McCall27b18f82009-11-17 02:14:36 +00004591 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4592 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004593
4594 if (!R->isFunctionType()) {
4595 // C++ [temp.explicit]p1:
4596 // A [...] static data member of a class template can be explicitly
4597 // instantiated from the member definition associated with its class
4598 // template.
John McCall27b18f82009-11-17 02:14:36 +00004599 if (Previous.isAmbiguous())
4600 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00004601
John McCall67c00872009-12-02 08:25:40 +00004602 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00004603 if (!Prev || !Prev->isStaticDataMember()) {
4604 // We expect to see a data data member here.
4605 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4606 << Name;
4607 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4608 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004609 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004610 return true;
4611 }
4612
4613 if (!Prev->getInstantiatedFromStaticDataMember()) {
4614 // FIXME: Check for explicit specialization?
4615 Diag(D.getIdentifierLoc(),
4616 diag::err_explicit_instantiation_data_member_not_instantiated)
4617 << Prev;
4618 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4619 // FIXME: Can we provide a note showing where this was declared?
4620 return true;
4621 }
4622
Douglas Gregore47f5a72009-10-14 23:41:34 +00004623 // C++0x [temp.explicit]p2:
4624 // If the explicit instantiation is for a member function, a member class
4625 // or a static data member of a class template specialization, the name of
4626 // the class template specialization in the qualified-id for the member
4627 // name shall be a simple-template-id.
4628 //
4629 // C++98 has the same restriction, just worded differently.
4630 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4631 Diag(D.getIdentifierLoc(),
4632 diag::err_explicit_instantiation_without_qualified_id)
4633 << Prev << D.getCXXScopeSpec().getRange();
4634
4635 // Check the scope of this explicit instantiation.
4636 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4637
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004638 // Verify that it is okay to explicitly instantiate here.
4639 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4640 assert(MSInfo && "Missing static data member specialization info?");
4641 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004642 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004643 MSInfo->getTemplateSpecializationKind(),
4644 MSInfo->getPointOfInstantiation(),
4645 SuppressNew))
4646 return true;
4647 if (SuppressNew)
4648 return DeclPtrTy();
4649
Douglas Gregor450f00842009-09-25 18:43:00 +00004650 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004651 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004652 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004653 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4654 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004655
4656 // FIXME: Create an ExplicitInstantiation node?
4657 return DeclPtrTy();
4658 }
4659
Douglas Gregor0e876e02009-09-25 23:53:26 +00004660 // If the declarator is a template-id, translate the parser's template
4661 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004662 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004663 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004664 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4665 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00004666 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4667 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00004668 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4669 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004670 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00004671 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00004672 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004673 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004674 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004675
Douglas Gregor450f00842009-09-25 18:43:00 +00004676 // C++ [temp.explicit]p1:
4677 // A [...] function [...] can be explicitly instantiated from its template.
4678 // A member function [...] of a class template can be explicitly
4679 // instantiated from the member definition associated with its class
4680 // template.
John McCall58cc69d2010-01-27 01:50:18 +00004681 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00004682 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4683 P != PEnd; ++P) {
4684 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004685 if (!HasExplicitTemplateArgs) {
4686 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4687 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4688 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004689
John McCall58cc69d2010-01-27 01:50:18 +00004690 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004691 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
4692 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00004693 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004694 }
4695 }
4696
4697 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4698 if (!FunTmpl)
4699 continue;
4700
John McCallbc077cf2010-02-08 23:07:23 +00004701 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004702 FunctionDecl *Specialization = 0;
4703 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004704 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00004705 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004706 R, Specialization, Info)) {
4707 // FIXME: Keep track of almost-matches?
4708 (void)TDK;
4709 continue;
4710 }
4711
John McCall58cc69d2010-01-27 01:50:18 +00004712 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00004713 }
4714
4715 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004716 UnresolvedSetIterator Result
4717 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00004718 D.getIdentifierLoc(),
4719 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4720 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4721 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4722
John McCall58cc69d2010-01-27 01:50:18 +00004723 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00004724 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004725
4726 // Ignore access control bits, we don't need them for redeclaration checking.
4727 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00004728
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004729 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004730 Diag(D.getIdentifierLoc(),
4731 diag::err_explicit_instantiation_member_function_not_instantiated)
4732 << Specialization
4733 << (Specialization->getTemplateSpecializationKind() ==
4734 TSK_ExplicitSpecialization);
4735 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4736 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004737 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004738
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004739 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004740 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4741 PrevDecl = Specialization;
4742
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004743 if (PrevDecl) {
4744 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004745 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004746 PrevDecl,
4747 PrevDecl->getTemplateSpecializationKind(),
4748 PrevDecl->getPointOfInstantiation(),
4749 SuppressNew))
4750 return true;
4751
4752 // FIXME: We may still want to build some representation of this
4753 // explicit specialization.
4754 if (SuppressNew)
4755 return DeclPtrTy();
4756 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00004757
4758 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004759
4760 if (TSK == TSK_ExplicitInstantiationDefinition)
4761 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4762 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004763
Douglas Gregore47f5a72009-10-14 23:41:34 +00004764 // C++0x [temp.explicit]p2:
4765 // If the explicit instantiation is for a member function, a member class
4766 // or a static data member of a class template specialization, the name of
4767 // the class template specialization in the qualified-id for the member
4768 // name shall be a simple-template-id.
4769 //
4770 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004771 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00004772 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00004773 D.getCXXScopeSpec().isSet() &&
4774 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4775 Diag(D.getIdentifierLoc(),
4776 diag::err_explicit_instantiation_without_qualified_id)
4777 << Specialization << D.getCXXScopeSpec().getRange();
4778
4779 CheckExplicitInstantiationScope(*this,
4780 FunTmpl? (NamedDecl *)FunTmpl
4781 : Specialization->getInstantiatedFromMemberFunction(),
4782 D.getIdentifierLoc(),
4783 D.getCXXScopeSpec().isSet());
4784
Douglas Gregor450f00842009-09-25 18:43:00 +00004785 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4786 return DeclPtrTy();
4787}
4788
Douglas Gregor333489b2009-03-27 23:10:48 +00004789Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004790Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4791 const CXXScopeSpec &SS, IdentifierInfo *Name,
4792 SourceLocation TagLoc, SourceLocation NameLoc) {
4793 // This has to hold, because SS is expected to be defined.
4794 assert(Name && "Expected a name in a dependent tag");
4795
4796 NestedNameSpecifier *NNS
4797 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4798 if (!NNS)
4799 return true;
4800
4801 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4802 if (T.isNull())
4803 return true;
4804
4805 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4806 QualType ElabType = Context.getElaboratedType(T, TagKind);
4807
4808 return ElabType.getAsOpaquePtr();
4809}
4810
4811Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004812Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4813 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004814 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004815 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4816 if (!NNS)
4817 return true;
4818
4819 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004820 if (T.isNull())
4821 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004822 return T.getAsOpaquePtr();
4823}
4824
Douglas Gregordce2b622009-04-01 00:28:59 +00004825Sema::TypeResult
4826Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4827 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004828 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004829 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004830 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004831 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004832 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004833 assert(TemplateId && "Expected a template specialization type");
4834
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004835 if (computeDeclContext(SS, false)) {
4836 // If we can compute a declaration context, then the "typename"
4837 // keyword was superfluous. Just build a QualifiedNameType to keep
4838 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004839
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004840 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4841 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4842 }
Mike Stump11289f42009-09-09 15:08:12 +00004843
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004844 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004845}
4846
Douglas Gregor333489b2009-03-27 23:10:48 +00004847/// \brief Build the type that describes a C++ typename specifier,
4848/// e.g., "typename T::type".
4849QualType
4850Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4851 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004852 CXXRecordDecl *CurrentInstantiation = 0;
4853 if (NNS->isDependent()) {
4854 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004855
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004856 // If the nested-name-specifier does not refer to the current
4857 // instantiation, then build a typename type.
4858 if (!CurrentInstantiation)
4859 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004860
Douglas Gregorc707da62009-09-02 13:12:51 +00004861 // The nested-name-specifier refers to the current instantiation, so the
4862 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004863 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004864 // extraneous "typename" keywords, and we retroactively apply this DR to
4865 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004866 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004867
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004868 DeclContext *Ctx = 0;
4869
4870 if (CurrentInstantiation)
4871 Ctx = CurrentInstantiation;
4872 else {
4873 CXXScopeSpec SS;
4874 SS.setScopeRep(NNS);
4875 SS.setRange(Range);
4876 if (RequireCompleteDeclContext(SS))
4877 return QualType();
4878
4879 Ctx = computeDeclContext(SS);
4880 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004881 assert(Ctx && "No declaration context?");
4882
4883 DeclarationName Name(&II);
John McCall27b18f82009-11-17 02:14:36 +00004884 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4885 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00004886 unsigned DiagID = 0;
4887 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00004888 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004889 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004890 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004891 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00004892
4893 case LookupResult::NotFoundInCurrentInstantiation:
4894 // Okay, it's a member of an unknown instantiation.
4895 return Context.getTypenameType(NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00004896
4897 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004898 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004899 // We found a type. Build a QualifiedNameType, since the
4900 // typename-specifier was just sugar. FIXME: Tell
4901 // QualifiedNameType that it has a "typename" prefix.
4902 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4903 }
4904
4905 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004906 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004907 break;
4908
John McCalle61f2ba2009-11-18 02:36:19 +00004909 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004910 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00004911 return QualType();
4912
Douglas Gregor333489b2009-03-27 23:10:48 +00004913 case LookupResult::FoundOverloaded:
4914 DiagID = diag::err_typename_nested_not_type;
4915 Referenced = *Result.begin();
4916 break;
4917
John McCall6538c932009-10-10 05:48:19 +00004918 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004919 return QualType();
4920 }
4921
4922 // If we get here, it's because name lookup did not find a
4923 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004924 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004925 if (Referenced)
4926 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4927 << Name;
4928 return QualType();
4929}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004930
4931namespace {
4932 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00004933 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00004934 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004935 SourceLocation Loc;
4936 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004937
Douglas Gregor15acfb92009-08-06 16:20:37 +00004938 public:
Mike Stump11289f42009-09-09 15:08:12 +00004939 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004940 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004941 DeclarationName Entity)
4942 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004943 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004944
4945 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004946 /// transformed.
4947 ///
4948 /// For the purposes of type reconstruction, a type has already been
4949 /// transformed if it is NULL or if it is not dependent.
4950 bool AlreadyTransformed(QualType T) {
4951 return T.isNull() || !T->isDependentType();
4952 }
Mike Stump11289f42009-09-09 15:08:12 +00004953
4954 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004955 /// rebuilt.
4956 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004957
Douglas Gregor15acfb92009-08-06 16:20:37 +00004958 /// \brief Returns the name of the entity whose type is being rebuilt.
4959 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004960
Douglas Gregoref6ab412009-10-27 06:26:26 +00004961 /// \brief Sets the "base" location and entity when that
4962 /// information is known based on another transformation.
4963 void setBase(SourceLocation Loc, DeclarationName Entity) {
4964 this->Loc = Loc;
4965 this->Entity = Entity;
4966 }
4967
Douglas Gregor15acfb92009-08-06 16:20:37 +00004968 /// \brief Transforms an expression by returning the expression itself
4969 /// (an identity function).
4970 ///
4971 /// FIXME: This is completely unsafe; we will need to actually clone the
4972 /// expressions.
4973 Sema::OwningExprResult TransformExpr(Expr *E) {
4974 return getSema().Owned(E);
4975 }
Mike Stump11289f42009-09-09 15:08:12 +00004976
Douglas Gregor15acfb92009-08-06 16:20:37 +00004977 /// \brief Transforms a typename type by determining whether the type now
4978 /// refers to a member of the current instantiation, and then
4979 /// type-checking and building a QualifiedNameType (when possible).
Douglas Gregorfe17d252010-02-16 19:09:40 +00004980 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL,
4981 QualType ObjectType);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004982 };
4983}
4984
Mike Stump11289f42009-09-09 15:08:12 +00004985QualType
John McCall550e0c22009-10-21 00:40:46 +00004986CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
Douglas Gregorfe17d252010-02-16 19:09:40 +00004987 TypenameTypeLoc TL,
4988 QualType ObjectType) {
John McCall0ad16662009-10-29 08:12:44 +00004989 TypenameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00004990
Douglas Gregor15acfb92009-08-06 16:20:37 +00004991 NestedNameSpecifier *NNS
4992 = TransformNestedNameSpecifier(T->getQualifier(),
Douglas Gregorfe17d252010-02-16 19:09:40 +00004993 /*FIXME:*/SourceRange(getBaseLocation()),
4994 ObjectType);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004995 if (!NNS)
4996 return QualType();
4997
4998 // If the nested-name-specifier did not change, and we cannot compute the
4999 // context corresponding to the nested-name-specifier, then this
5000 // typename type will not change; exit early.
5001 CXXScopeSpec SS;
5002 SS.setRange(SourceRange(getBaseLocation()));
5003 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00005004
5005 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00005006 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00005007 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00005008
5009 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00005010 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00005011 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00005012 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00005013 = TransformType(QualType(TemplateId, 0));
5014 if (NewTemplateId.isNull())
5015 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005016
Douglas Gregor15acfb92009-08-06 16:20:37 +00005017 if (NNS == T->getQualifier() &&
5018 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00005019 Result = QualType(T, 0);
5020 else
5021 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
5022 } else
5023 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
5024 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00005025
Douglas Gregor281c4862010-03-07 23:26:22 +00005026 if (Result.isNull())
5027 return QualType();
5028
John McCall0ad16662009-10-29 08:12:44 +00005029 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
5030 NewTL.setNameLoc(TL.getNameLoc());
5031 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00005032}
5033
5034/// \brief Rebuilds a type within the context of the current instantiation.
5035///
Mike Stump11289f42009-09-09 15:08:12 +00005036/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005037/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005038/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005039/// partial specialization thereof). This routine will rebuild that type now
5040/// that we have entered the declarator's scope, which may produce different
5041/// canonical types, e.g.,
5042///
5043/// \code
5044/// template<typename T>
5045/// struct X {
5046/// typedef T* pointer;
5047/// pointer data();
5048/// };
5049///
5050/// template<typename T>
5051/// typename X<T>::pointer X<T>::data() { ... }
5052/// \endcode
5053///
5054/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
5055/// since we do not know that we can look into X<T> when we parsed the type.
5056/// This function will rebuild the type, performing the lookup of "pointer"
5057/// in X<T> and returning a QualifiedNameType whose canonical type is the same
5058/// as the canonical type of T*, allowing the return types of the out-of-line
5059/// definition and the declaration to match.
5060QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
5061 DeclarationName Name) {
5062 if (T.isNull() || !T->isDependentType())
5063 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005064
Douglas Gregor15acfb92009-08-06 16:20:37 +00005065 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5066 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005067}
Douglas Gregorbe999392009-09-15 16:23:51 +00005068
5069/// \brief Produces a formatted string that describes the binding of
5070/// template parameters to template arguments.
5071std::string
5072Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5073 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005074 // FIXME: For variadic templates, we'll need to get the structured list.
5075 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5076 Args.flat_size());
5077}
5078
5079std::string
5080Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5081 const TemplateArgument *Args,
5082 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005083 std::string Result;
5084
Douglas Gregore62e6a02009-11-11 19:13:48 +00005085 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005086 return Result;
5087
5088 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005089 if (I >= NumArgs)
5090 break;
5091
Douglas Gregorbe999392009-09-15 16:23:51 +00005092 if (I == 0)
5093 Result += "[with ";
5094 else
5095 Result += ", ";
5096
5097 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5098 Result += Id->getName();
5099 } else {
5100 Result += '$';
5101 Result += llvm::utostr(I);
5102 }
5103
5104 Result += " = ";
5105
5106 switch (Args[I].getKind()) {
5107 case TemplateArgument::Null:
5108 Result += "<no value>";
5109 break;
5110
5111 case TemplateArgument::Type: {
5112 std::string TypeStr;
5113 Args[I].getAsType().getAsStringInternal(TypeStr,
5114 Context.PrintingPolicy);
5115 Result += TypeStr;
5116 break;
5117 }
5118
5119 case TemplateArgument::Declaration: {
5120 bool Unnamed = true;
5121 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5122 if (ND->getDeclName()) {
5123 Unnamed = false;
5124 Result += ND->getNameAsString();
5125 }
5126 }
5127
5128 if (Unnamed) {
5129 Result += "<anonymous>";
5130 }
5131 break;
5132 }
5133
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005134 case TemplateArgument::Template: {
5135 std::string Str;
5136 llvm::raw_string_ostream OS(Str);
5137 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5138 Result += OS.str();
5139 break;
5140 }
5141
Douglas Gregorbe999392009-09-15 16:23:51 +00005142 case TemplateArgument::Integral: {
5143 Result += Args[I].getAsIntegral()->toString(10);
5144 break;
5145 }
5146
5147 case TemplateArgument::Expression: {
5148 assert(false && "No expressions in deduced template arguments!");
5149 Result += "<expression>";
5150 break;
5151 }
5152
5153 case TemplateArgument::Pack:
5154 // FIXME: Format template argument packs
5155 Result += "<template argument pack>";
5156 break;
5157 }
5158 }
5159
5160 Result += ']';
5161 return Result;
5162}