blob: 7c4cab11836600a48b60f6af32e267cf2db9a907 [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"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000020#include "clang/Parse/Template.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000023#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000024using namespace clang;
25
Douglas Gregorb7bfe792009-09-02 22:59:36 +000026/// \brief Determine whether the declaration found is acceptable as the name
27/// of a template and, if so, return that template declaration. Otherwise,
28/// returns NULL.
29static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
30 if (!D)
31 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000032
Douglas Gregorb7bfe792009-09-02 22:59:36 +000033 if (isa<TemplateDecl>(D))
34 return D;
Mike Stump11289f42009-09-09 15:08:12 +000035
Douglas Gregorb7bfe792009-09-02 22:59:36 +000036 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
37 // C++ [temp.local]p1:
38 // Like normal (non-template) classes, class templates have an
39 // injected-class-name (Clause 9). The injected-class-name
40 // can be used with or without a template-argument-list. When
41 // it is used without a template-argument-list, it is
42 // equivalent to the injected-class-name followed by the
43 // template-parameters of the class template enclosed in
44 // <>. When it is used with a template-argument-list, it
45 // refers to the specified class template specialization,
46 // which could be the current specialization or another
47 // specialization.
48 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000049 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000050 if (Record->getDescribedClassTemplate())
51 return Record->getDescribedClassTemplate();
52
53 if (ClassTemplateSpecializationDecl *Spec
54 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
55 return Spec->getSpecializedTemplate();
56 }
Mike Stump11289f42009-09-09 15:08:12 +000057
Douglas Gregorb7bfe792009-09-02 22:59:36 +000058 return 0;
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Douglas Gregorb7bfe792009-09-02 22:59:36 +000061 return 0;
62}
63
John McCalle66edc12009-11-24 19:00:30 +000064static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
65 LookupResult::Filter filter = R.makeFilter();
66 while (filter.hasNext()) {
67 NamedDecl *Orig = filter.next();
68 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
69 if (!Repl)
70 filter.erase();
71 else if (Repl != Orig)
72 filter.replace(Repl);
73 }
74 filter.done();
75}
76
Douglas Gregorb7bfe792009-09-02 22:59:36 +000077TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor3cf81312009-11-03 23:16:33 +000078 const CXXScopeSpec &SS,
79 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +000080 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +000081 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +000082 TemplateTy &TemplateResult) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +000083 assert(getLangOptions().CPlusPlus && "No template names in C!");
84
Douglas Gregor3cf81312009-11-03 23:16:33 +000085 DeclarationName TName;
86
87 switch (Name.getKind()) {
88 case UnqualifiedId::IK_Identifier:
89 TName = DeclarationName(Name.Identifier);
90 break;
91
92 case UnqualifiedId::IK_OperatorFunctionId:
93 TName = Context.DeclarationNames.getCXXOperatorName(
94 Name.OperatorFunctionId.Operator);
95 break;
96
Alexis Hunted0530f2009-11-28 08:58:14 +000097 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +000098 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
99 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000100
Douglas Gregor3cf81312009-11-03 23:16:33 +0000101 default:
102 return TNK_Non_template;
103 }
Mike Stump11289f42009-09-09 15:08:12 +0000104
John McCalle66edc12009-11-24 19:00:30 +0000105 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump11289f42009-09-09 15:08:12 +0000106
Douglas Gregorff18cc12009-12-31 08:11:17 +0000107 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
108 LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +0000109 R.suppressDiagnostics();
110 LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
111 if (R.empty())
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000112 return TNK_Non_template;
113
John McCalld28ae272009-12-02 08:04:21 +0000114 TemplateName Template;
115 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000116
John McCalld28ae272009-12-02 08:04:21 +0000117 unsigned ResultCount = R.end() - R.begin();
118 if (ResultCount > 1) {
119 // We assume that we'll preserve the qualifier from a function
120 // template name in other ways.
121 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
122 TemplateKind = TNK_Function_template;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000123 } else {
John McCalld28ae272009-12-02 08:04:21 +0000124 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
125
126 if (SS.isSet() && !SS.isInvalid()) {
127 NestedNameSpecifier *Qualifier
128 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
129 Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
130 } else {
131 Template = TemplateName(TD);
132 }
133
134 if (isa<FunctionTemplateDecl>(TD))
135 TemplateKind = TNK_Function_template;
136 else {
137 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
138 TemplateKind = TNK_Type_template;
139 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000140 }
Mike Stump11289f42009-09-09 15:08:12 +0000141
John McCalld28ae272009-12-02 08:04:21 +0000142 TemplateResult = TemplateTy::make(Template);
143 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000144}
145
Douglas Gregor18473f32010-01-12 21:28:44 +0000146bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
147 SourceLocation IILoc,
148 Scope *S,
149 const CXXScopeSpec *SS,
150 TemplateTy &SuggestedTemplate,
151 TemplateNameKind &SuggestedKind) {
152 // We can't recover unless there's a dependent scope specifier preceding the
153 // template name.
154 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
155 computeDeclContext(*SS))
156 return false;
157
158 // The code is missing a 'template' keyword prior to the dependent template
159 // name.
160 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
161 Diag(IILoc, diag::err_template_kw_missing)
162 << Qualifier << II.getName()
163 << CodeModificationHint::CreateInsertion(IILoc, "template ");
164 SuggestedTemplate
165 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
166 SuggestedKind = TNK_Dependent_template_name;
167 return true;
168}
169
John McCalle66edc12009-11-24 19:00:30 +0000170void Sema::LookupTemplateName(LookupResult &Found,
171 Scope *S, const CXXScopeSpec &SS,
172 QualType ObjectType,
173 bool EnteringContext) {
174 // Determine where to perform name lookup
175 DeclContext *LookupCtx = 0;
176 bool isDependent = false;
177 if (!ObjectType.isNull()) {
178 // This nested-name-specifier occurs in a member access expression, e.g.,
179 // x->B::f, and we are looking into the type of the object.
180 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
181 LookupCtx = computeDeclContext(ObjectType);
182 isDependent = ObjectType->isDependentType();
183 assert((isDependent || !ObjectType->isIncompleteType()) &&
184 "Caller should have completed object type");
185 } else if (SS.isSet()) {
186 // This nested-name-specifier occurs after another nested-name-specifier,
187 // so long into the context associated with the prior nested-name-specifier.
188 LookupCtx = computeDeclContext(SS, EnteringContext);
189 isDependent = isDependentScopeSpecifier(SS);
190
191 // The declaration context must be complete.
192 if (LookupCtx && RequireCompleteDeclContext(SS))
193 return;
194 }
195
196 bool ObjectTypeSearchedInScope = false;
197 if (LookupCtx) {
198 // Perform "qualified" name lookup into the declaration context we
199 // computed, which is either the type of the base of a member access
200 // expression or the declaration context associated with a prior
201 // nested-name-specifier.
202 LookupQualifiedName(Found, LookupCtx);
203
204 if (!ObjectType.isNull() && Found.empty()) {
205 // C++ [basic.lookup.classref]p1:
206 // In a class member access expression (5.2.5), if the . or -> token is
207 // immediately followed by an identifier followed by a <, the
208 // identifier must be looked up to determine whether the < is the
209 // beginning of a template argument list (14.2) or a less-than operator.
210 // The identifier is first looked up in the class of the object
211 // expression. If the identifier is not found, it is then looked up in
212 // the context of the entire postfix-expression and shall name a class
213 // or function template.
214 //
215 // FIXME: When we're instantiating a template, do we actually have to
216 // look in the scope of the template? Seems fishy...
217 if (S) LookupName(Found, S);
218 ObjectTypeSearchedInScope = true;
219 }
220 } else if (isDependent) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000221 // We cannot look into a dependent object type or nested nme
222 // specifier.
John McCalle66edc12009-11-24 19:00:30 +0000223 return;
224 } else {
225 // Perform unqualified name lookup in the current scope.
226 LookupName(Found, S);
227 }
228
229 // FIXME: Cope with ambiguous name-lookup results.
230 assert(!Found.isAmbiguous() &&
231 "Cannot handle template name-lookup ambiguities");
232
Douglas Gregorc119dd52010-01-12 17:06:20 +0000233 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000234 // If we did not find any names, attempt to correct any typos.
235 DeclarationName Name = Found.getLookupName();
236 if (CorrectTypo(Found, S, &SS, LookupCtx)) {
237 FilterAcceptableTemplateNames(Context, Found);
238 if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
239 if (LookupCtx)
240 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
241 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
242 << CodeModificationHint::CreateReplacement(Found.getNameLoc(),
243 Found.getLookupName().getAsString());
244 else
245 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
246 << Name << Found.getLookupName()
247 << CodeModificationHint::CreateReplacement(Found.getNameLoc(),
248 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000249 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
250 Diag(Template->getLocation(), diag::note_previous_decl)
251 << Template->getDeclName();
Douglas Gregorff18cc12009-12-31 08:11:17 +0000252 } else
253 Found.clear();
254 } else {
255 Found.clear();
256 }
257 }
258
John McCalle66edc12009-11-24 19:00:30 +0000259 FilterAcceptableTemplateNames(Context, Found);
260 if (Found.empty())
261 return;
262
263 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
264 // C++ [basic.lookup.classref]p1:
265 // [...] If the lookup in the class of the object expression finds a
266 // template, the name is also looked up in the context of the entire
267 // postfix-expression and [...]
268 //
269 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
270 LookupOrdinaryName);
271 LookupName(FoundOuter, S);
272 FilterAcceptableTemplateNames(Context, FoundOuter);
273 // FIXME: Handle ambiguities in this lookup better
274
275 if (FoundOuter.empty()) {
276 // - if the name is not found, the name found in the class of the
277 // object expression is used, otherwise
278 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
279 // - if the name is found in the context of the entire
280 // postfix-expression and does not name a class template, the name
281 // found in the class of the object expression is used, otherwise
282 } else {
283 // - if the name found is a class template, it must refer to the same
284 // entity as the one found in the class of the object expression,
285 // otherwise the program is ill-formed.
286 if (!Found.isSingleResult() ||
287 Found.getFoundDecl()->getCanonicalDecl()
288 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
289 Diag(Found.getNameLoc(),
290 diag::err_nested_name_member_ref_lookup_ambiguous)
291 << Found.getLookupName();
292 Diag(Found.getRepresentativeDecl()->getLocation(),
293 diag::note_ambig_member_ref_object_type)
294 << ObjectType;
295 Diag(FoundOuter.getFoundDecl()->getLocation(),
296 diag::note_ambig_member_ref_scope);
297
298 // Recover by taking the template that we found in the object
299 // expression's type.
300 }
301 }
302 }
303}
304
John McCallcd4b4772009-12-02 03:53:29 +0000305/// ActOnDependentIdExpression - Handle a dependent id-expression that
306/// was just parsed. This is only possible with an explicit scope
307/// specifier naming a dependent type.
John McCalle66edc12009-11-24 19:00:30 +0000308Sema::OwningExprResult
309Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
310 DeclarationName Name,
311 SourceLocation NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +0000312 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000313 const TemplateArgumentListInfo *TemplateArgs) {
314 NestedNameSpecifier *Qualifier
315 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
316
John McCallcd4b4772009-12-02 03:53:29 +0000317 if (!isAddressOfOperand &&
318 isa<CXXMethodDecl>(CurContext) &&
319 cast<CXXMethodDecl>(CurContext)->isInstance()) {
320 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
321
John McCalle66edc12009-11-24 19:00:30 +0000322 // Since the 'this' expression is synthesized, we don't need to
323 // perform the double-lookup check.
324 NamedDecl *FirstQualifierInScope = 0;
325
John McCall2d74de92009-12-01 22:10:20 +0000326 return Owned(CXXDependentScopeMemberExpr::Create(Context,
327 /*This*/ 0, ThisType,
328 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000329 /*Op*/ SourceLocation(),
330 Qualifier, SS.getRange(),
331 FirstQualifierInScope,
332 Name, NameLoc,
333 TemplateArgs));
334 }
335
336 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
337}
338
339Sema::OwningExprResult
340Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
341 DeclarationName Name,
342 SourceLocation NameLoc,
343 const TemplateArgumentListInfo *TemplateArgs) {
344 return Owned(DependentScopeDeclRefExpr::Create(Context,
345 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
346 SS.getRange(),
347 Name, NameLoc,
348 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000349}
350
Douglas Gregor5101c242008-12-05 18:15:24 +0000351/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
352/// that the template parameter 'PrevDecl' is being shadowed by a new
353/// declaration at location Loc. Returns true to indicate that this is
354/// an error, and false otherwise.
355bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000356 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000357
358 // Microsoft Visual C++ permits template parameters to be shadowed.
359 if (getLangOptions().Microsoft)
360 return false;
361
362 // C++ [temp.local]p4:
363 // A template-parameter shall not be redeclared within its
364 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000365 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000366 << cast<NamedDecl>(PrevDecl)->getDeclName();
367 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
368 return true;
369}
370
Douglas Gregor463421d2009-03-03 04:44:36 +0000371/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000372/// the parameter D to reference the templated declaration and return a pointer
373/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000374TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000375 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000376 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000377 return Temp;
378 }
379 return 0;
380}
381
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000382static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
383 const ParsedTemplateArgument &Arg) {
384
385 switch (Arg.getKind()) {
386 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000387 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000388 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
389 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000390 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000391 return TemplateArgumentLoc(TemplateArgument(T), DI);
392 }
393
394 case ParsedTemplateArgument::NonType: {
395 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
396 return TemplateArgumentLoc(TemplateArgument(E), E);
397 }
398
399 case ParsedTemplateArgument::Template: {
400 TemplateName Template
401 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
402 return TemplateArgumentLoc(TemplateArgument(Template),
403 Arg.getScopeSpec().getRange(),
404 Arg.getLocation());
405 }
406 }
407
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000408 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000409 return TemplateArgumentLoc();
410}
411
412/// \brief Translates template arguments as provided by the parser
413/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000414void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
415 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000416 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000417 TemplateArgs.addArgument(translateTemplateArgument(*this,
418 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000419}
420
Douglas Gregor5101c242008-12-05 18:15:24 +0000421/// ActOnTypeParameter - Called when a C++ template type parameter
422/// (e.g., "typename T") has been parsed. Typename specifies whether
423/// the keyword "typename" was used to declare the type parameter
424/// (otherwise, "class" was used), and KeyLoc is the location of the
425/// "class" or "typename" keyword. ParamName is the name of the
426/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000427/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000428/// If the type parameter has a default argument, it will be added
429/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000430Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000431 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000432 SourceLocation KeyLoc,
433 IdentifierInfo *ParamName,
434 SourceLocation ParamNameLoc,
435 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000436 assert(S->isTemplateParamScope() &&
437 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000438 bool Invalid = false;
439
440 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000441 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000442 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000443 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000444 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000445 }
446
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000447 SourceLocation Loc = ParamNameLoc;
448 if (!ParamName)
449 Loc = KeyLoc;
450
Douglas Gregor5101c242008-12-05 18:15:24 +0000451 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000452 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
453 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000454 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000455 if (Invalid)
456 Param->setInvalidDecl();
457
458 if (ParamName) {
459 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000460 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000461 IdResolver.AddDecl(Param);
462 }
463
Chris Lattner83f095c2009-03-28 19:18:32 +0000464 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000465}
466
Douglas Gregordba32632009-02-10 19:49:53 +0000467/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000468/// Default) to the given template type parameter (TypeParam).
469void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000470 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000471 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000472 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000473 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000474 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000475
John McCallbcd03502009-12-07 02:54:59 +0000476 TypeSourceInfo *DefaultTInfo;
477 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall0ad16662009-10-29 08:12:44 +0000478
John McCallbcd03502009-12-07 02:54:59 +0000479 assert(DefaultTInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000480
Anders Carlssond3824352009-06-12 22:30:13 +0000481 // C++0x [temp.param]p9:
482 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000483 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000484 if (Parm->isParameterPack()) {
485 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000486 return;
487 }
Mike Stump11289f42009-09-09 15:08:12 +0000488
Douglas Gregordba32632009-02-10 19:49:53 +0000489 // C++ [temp.param]p14:
490 // A template-parameter shall not be used in its own default argument.
491 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000492
Douglas Gregordba32632009-02-10 19:49:53 +0000493 // Check the template argument itself.
John McCallbcd03502009-12-07 02:54:59 +0000494 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000495 Parm->setInvalidDecl();
496 return;
497 }
498
John McCallbcd03502009-12-07 02:54:59 +0000499 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000500}
501
Douglas Gregor463421d2009-03-03 04:44:36 +0000502/// \brief Check that the type of a non-type template parameter is
503/// well-formed.
504///
505/// \returns the (possibly-promoted) parameter type if valid;
506/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000507QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000508Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
509 // C++ [temp.param]p4:
510 //
511 // A non-type template-parameter shall have one of the following
512 // (optionally cv-qualified) types:
513 //
514 // -- integral or enumeration type,
515 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000516 // -- pointer to object or pointer to function,
517 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000518 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
519 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000520 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000521 T->isReferenceType() ||
522 // -- pointer to member.
523 T->isMemberPointerType() ||
524 // If T is a dependent type, we can't do the check now, so we
525 // assume that it is well-formed.
526 T->isDependentType())
527 return T;
528 // C++ [temp.param]p8:
529 //
530 // A non-type template-parameter of type "array of T" or
531 // "function returning T" is adjusted to be of type "pointer to
532 // T" or "pointer to function returning T", respectively.
533 else if (T->isArrayType())
534 // FIXME: Keep the type prior to promotion?
535 return Context.getArrayDecayedType(T);
536 else if (T->isFunctionType())
537 // FIXME: Keep the type prior to promotion?
538 return Context.getPointerType(T);
539
540 Diag(Loc, diag::err_template_nontype_parm_bad_type)
541 << T;
542
543 return QualType();
544}
545
Douglas Gregor5101c242008-12-05 18:15:24 +0000546/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
547/// template parameter (e.g., "int Size" in "template<int Size>
548/// class Array") has been parsed. S is the current scope and D is
549/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000550Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000551 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000552 unsigned Position) {
John McCallbcd03502009-12-07 02:54:59 +0000553 TypeSourceInfo *TInfo = 0;
554 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000555
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000556 assert(S->isTemplateParamScope() &&
557 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000558 bool Invalid = false;
559
560 IdentifierInfo *ParamName = D.getIdentifier();
561 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000562 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000563 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000564 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000565 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000566 }
567
Douglas Gregor463421d2009-03-03 04:44:36 +0000568 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000569 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000570 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000571 Invalid = true;
572 }
Douglas Gregor81338792009-02-10 17:43:50 +0000573
Douglas Gregor5101c242008-12-05 18:15:24 +0000574 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000575 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
576 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000577 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000578 if (Invalid)
579 Param->setInvalidDecl();
580
581 if (D.getIdentifier()) {
582 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000583 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000584 IdResolver.AddDecl(Param);
585 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000586 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000587}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000588
Douglas Gregordba32632009-02-10 19:49:53 +0000589/// \brief Adds a default argument to the given non-type template
590/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000591void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000592 SourceLocation EqualLoc,
593 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000594 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000595 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000596 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000597
Douglas Gregordba32632009-02-10 19:49:53 +0000598 // C++ [temp.param]p14:
599 // A template-parameter shall not be used in its own default argument.
600 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000601
Douglas Gregordba32632009-02-10 19:49:53 +0000602 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000603 TemplateArgument Converted;
604 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
605 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000606 TemplateParm->setInvalidDecl();
607 return;
608 }
609
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000610 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000611}
612
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000613
614/// ActOnTemplateTemplateParameter - Called when a C++ template template
615/// parameter (e.g. T in template <template <typename> class T> class array)
616/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000617Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
618 SourceLocation TmpLoc,
619 TemplateParamsTy *Params,
620 IdentifierInfo *Name,
621 SourceLocation NameLoc,
622 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000623 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000624 assert(S->isTemplateParamScope() &&
625 "Template template parameter not in template parameter scope!");
626
627 // Construct the parameter object.
628 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000629 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
630 TmpLoc, Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000631 (TemplateParameterList*)Params);
632
633 // Make sure the parameter is valid.
634 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
635 // do anything yet. However, if the template parameter list or (eventual)
636 // default value is ever invalidated, that will propagate here.
637 bool Invalid = false;
638 if (Invalid) {
639 Param->setInvalidDecl();
640 }
641
642 // If the tt-param has a name, then link the identifier into the scope
643 // and lookup mechanisms.
644 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000645 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000646 IdResolver.AddDecl(Param);
647 }
648
Chris Lattner83f095c2009-03-28 19:18:32 +0000649 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000650}
651
Douglas Gregordba32632009-02-10 19:49:53 +0000652/// \brief Adds a default argument to the given template template
653/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000654void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000655 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000656 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000657 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000658 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000659
Douglas Gregordba32632009-02-10 19:49:53 +0000660 // C++ [temp.param]p14:
661 // A template-parameter shall not be used in its own default argument.
662 // FIXME: Implement this check! Needs a recursive walk over the types.
663
Douglas Gregore62e6a02009-11-11 19:13:48 +0000664 // Check only that we have a template template argument. We don't want to
665 // try to check well-formedness now, because our template template parameter
666 // might have dependent types in its template parameters, which we wouldn't
667 // be able to match now.
668 //
669 // If none of the template template parameter's template arguments mention
670 // other template parameters, we could actually perform more checking here.
671 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000672 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000673 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
674 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
675 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000676 return;
677 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000678
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000679 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000680}
681
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000682/// ActOnTemplateParameterList - Builds a TemplateParameterList that
683/// contains the template parameters in Params/NumParams.
684Sema::TemplateParamsTy *
685Sema::ActOnTemplateParameterList(unsigned Depth,
686 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000687 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000688 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000689 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000690 SourceLocation RAngleLoc) {
691 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000692 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000693
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000694 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000695 (NamedDecl**)Params, NumParams,
696 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000697}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000698
Douglas Gregorc08f4892009-03-25 00:13:59 +0000699Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000700Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000701 SourceLocation KWLoc, const CXXScopeSpec &SS,
702 IdentifierInfo *Name, SourceLocation NameLoc,
703 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000704 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000705 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000706 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000707 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000708 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000709 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000710
711 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000712 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000713 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000714
John McCall27b5c252009-09-14 21:59:20 +0000715 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
716 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000717
718 // There is no such thing as an unnamed class template.
719 if (!Name) {
720 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000721 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000722 }
723
724 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000725 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000726 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000727 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000728 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000729 if (RequireCompleteDeclContext(SS))
730 return true;
731
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000732 SemanticContext = computeDeclContext(SS, true);
733 if (!SemanticContext) {
734 // FIXME: Produce a reasonable diagnostic here
735 return true;
736 }
Mike Stump11289f42009-09-09 15:08:12 +0000737
John McCall27b18f82009-11-17 02:14:36 +0000738 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000739 } else {
740 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000741 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000742 }
Mike Stump11289f42009-09-09 15:08:12 +0000743
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000744 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
745 NamedDecl *PrevDecl = 0;
746 if (Previous.begin() != Previous.end())
747 PrevDecl = *Previous.begin();
748
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000749 // If there is a previous declaration with the same name, check
750 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000751 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000752 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000753
754 // We may have found the injected-class-name of a class template,
755 // class template partial specialization, or class template specialization.
756 // In these cases, grab the template that is being defined or specialized.
757 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
758 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
759 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
760 PrevClassTemplate
761 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
762 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
763 PrevClassTemplate
764 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
765 ->getSpecializedTemplate();
766 }
767 }
768
John McCalld43784f2009-12-18 11:25:59 +0000769 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000770 // C++ [namespace.memdef]p3:
771 // [...] When looking for a prior declaration of a class or a function
772 // declared as a friend, and when the name of the friend class or
773 // function is neither a qualified name nor a template-id, scopes outside
774 // the innermost enclosing namespace scope are not considered.
775 DeclContext *OutermostContext = CurContext;
776 while (!OutermostContext->isFileContext())
777 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000778
779 if (PrevDecl &&
780 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
781 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
John McCall90d3bb92009-12-17 23:21:11 +0000782 SemanticContext = PrevDecl->getDeclContext();
783 } else {
784 // Declarations in outer scopes don't matter. However, the outermost
785 // context we computed is the semantic context for our new
786 // declaration.
787 PrevDecl = PrevClassTemplate = 0;
788 SemanticContext = OutermostContext;
789 }
790
791 if (CurContext->isDependentContext()) {
792 // If this is a dependent context, we don't want to link the friend
793 // class template to the template in scope, because that would perform
794 // checking of the template parameter lists that can't be performed
795 // until the outer context is instantiated.
796 PrevDecl = PrevClassTemplate = 0;
797 }
798 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
799 PrevDecl = PrevClassTemplate = 0;
800
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000801 if (PrevClassTemplate) {
802 // Ensure that the template parameter lists are compatible.
803 if (!TemplateParameterListsAreEqual(TemplateParams,
804 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000805 /*Complain=*/true,
806 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000807 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000808
809 // C++ [temp.class]p4:
810 // In a redeclaration, partial specialization, explicit
811 // specialization or explicit instantiation of a class template,
812 // the class-key shall agree in kind with the original class
813 // template declaration (7.1.5.3).
814 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000815 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000816 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000817 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000818 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000819 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000820 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000821 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000822 }
823
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000824 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000825 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000826 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000827 Diag(NameLoc, diag::err_redefinition) << Name;
828 Diag(Def->getLocation(), diag::note_previous_definition);
829 // FIXME: Would it make sense to try to "forget" the previous
830 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000831 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000832 }
833 }
834 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
835 // Maybe we will complain about the shadowed template parameter.
836 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
837 // Just pretend that we didn't see the previous declaration.
838 PrevDecl = 0;
839 } else if (PrevDecl) {
840 // C++ [temp]p5:
841 // A class template shall not have the same name as any other
842 // template, class, function, object, enumeration, enumerator,
843 // namespace, or type in the same scope (3.3), except as specified
844 // in (14.5.4).
845 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
846 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000847 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000848 }
849
Douglas Gregordba32632009-02-10 19:49:53 +0000850 // Check the template parameter list of this declaration, possibly
851 // merging in the template parameter list from the previous class
852 // template declaration.
853 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000854 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
855 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000856 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000857
Douglas Gregore362cea2009-05-10 22:57:19 +0000858 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000859 // declaration!
860
Mike Stump11289f42009-09-09 15:08:12 +0000861 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000862 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000863 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000864 PrevClassTemplate->getTemplatedDecl() : 0,
865 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000866
867 ClassTemplateDecl *NewTemplate
868 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
869 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000870 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000871 NewClass->setDescribedClassTemplate(NewTemplate);
872
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000873 // Build the type for the class template declaration now.
John McCalle78aac42010-03-10 03:28:59 +0000874 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
875 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000876 assert(T->isDependentType() && "Class template type is not dependent?");
877 (void)T;
878
Douglas Gregorcf915552009-10-13 16:30:37 +0000879 // If we are providing an explicit specialization of a member that is a
880 // class template, make a note of that.
881 if (PrevClassTemplate &&
882 PrevClassTemplate->getInstantiatedFromMemberTemplate())
883 PrevClassTemplate->setMemberSpecialization();
884
Anders Carlsson137108d2009-03-26 01:24:28 +0000885 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000886 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000887 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000888
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000889 // Set the lexical context of these templates
890 NewClass->setLexicalDeclContext(CurContext);
891 NewTemplate->setLexicalDeclContext(CurContext);
892
John McCall9bb74a52009-07-31 02:45:11 +0000893 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000894 NewClass->startDefinition();
895
896 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000897 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000898
John McCall27b5c252009-09-14 21:59:20 +0000899 if (TUK != TUK_Friend)
900 PushOnScopeChains(NewTemplate, S);
901 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000902 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000903 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000904 NewClass->setAccess(PrevClassTemplate->getAccess());
905 }
John McCall27b5c252009-09-14 21:59:20 +0000906
Douglas Gregor3dad8422009-09-26 06:47:28 +0000907 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
908 PrevClassTemplate != NULL);
909
John McCall27b5c252009-09-14 21:59:20 +0000910 // Friend templates are visible in fairly strange ways.
911 if (!CurContext->isDependentContext()) {
912 DeclContext *DC = SemanticContext->getLookupContext();
913 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
914 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
915 PushOnScopeChains(NewTemplate, EnclosingScope,
916 /* AddToContext = */ false);
917 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000918
919 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
920 NewClass->getLocation(),
921 NewTemplate,
922 /*FIXME:*/NewClass->getLocation());
923 Friend->setAccess(AS_public);
924 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000925 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000926
Douglas Gregordba32632009-02-10 19:49:53 +0000927 if (Invalid) {
928 NewTemplate->setInvalidDecl();
929 NewClass->setInvalidDecl();
930 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000931 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000932}
933
Douglas Gregored5731f2009-11-25 17:50:39 +0000934/// \brief Diagnose the presence of a default template argument on a
935/// template parameter, which is ill-formed in certain contexts.
936///
937/// \returns true if the default template argument should be dropped.
938static bool DiagnoseDefaultTemplateArgument(Sema &S,
939 Sema::TemplateParamListContext TPC,
940 SourceLocation ParamLoc,
941 SourceRange DefArgRange) {
942 switch (TPC) {
943 case Sema::TPC_ClassTemplate:
944 return false;
945
946 case Sema::TPC_FunctionTemplate:
947 // C++ [temp.param]p9:
948 // A default template-argument shall not be specified in a
949 // function template declaration or a function template
950 // definition [...]
951 // (This sentence is not in C++0x, per DR226).
952 if (!S.getLangOptions().CPlusPlus0x)
953 S.Diag(ParamLoc,
954 diag::err_template_parameter_default_in_function_template)
955 << DefArgRange;
956 return false;
957
958 case Sema::TPC_ClassTemplateMember:
959 // C++0x [temp.param]p9:
960 // A default template-argument shall not be specified in the
961 // template-parameter-lists of the definition of a member of a
962 // class template that appears outside of the member's class.
963 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
964 << DefArgRange;
965 return true;
966
967 case Sema::TPC_FriendFunctionTemplate:
968 // C++ [temp.param]p9:
969 // A default template-argument shall not be specified in a
970 // friend template declaration.
971 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
972 << DefArgRange;
973 return true;
974
975 // FIXME: C++0x [temp.param]p9 allows default template-arguments
976 // for friend function templates if there is only a single
977 // declaration (and it is a definition). Strange!
978 }
979
980 return false;
981}
982
Douglas Gregordba32632009-02-10 19:49:53 +0000983/// \brief Checks the validity of a template parameter list, possibly
984/// considering the template parameter list from a previous
985/// declaration.
986///
987/// If an "old" template parameter list is provided, it must be
988/// equivalent (per TemplateParameterListsAreEqual) to the "new"
989/// template parameter list.
990///
991/// \param NewParams Template parameter list for a new template
992/// declaration. This template parameter list will be updated with any
993/// default arguments that are carried through from the previous
994/// template parameter list.
995///
996/// \param OldParams If provided, template parameter list from a
997/// previous declaration of the same template. Default template
998/// arguments will be merged from the old template parameter list to
999/// the new template parameter list.
1000///
Douglas Gregored5731f2009-11-25 17:50:39 +00001001/// \param TPC Describes the context in which we are checking the given
1002/// template parameter list.
1003///
Douglas Gregordba32632009-02-10 19:49:53 +00001004/// \returns true if an error occurred, false otherwise.
1005bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001006 TemplateParameterList *OldParams,
1007 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001008 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001009
Douglas Gregordba32632009-02-10 19:49:53 +00001010 // C++ [temp.param]p10:
1011 // The set of default template-arguments available for use with a
1012 // template declaration or definition is obtained by merging the
1013 // default arguments from the definition (if in scope) and all
1014 // declarations in scope in the same way default function
1015 // arguments are (8.3.6).
1016 bool SawDefaultArgument = false;
1017 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001018
Anders Carlsson327865d2009-06-12 23:20:15 +00001019 bool SawParameterPack = false;
1020 SourceLocation ParameterPackLoc;
1021
Mike Stumpc89c8e32009-02-11 23:03:27 +00001022 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001023 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001024 if (OldParams)
1025 OldParam = OldParams->begin();
1026
1027 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1028 NewParamEnd = NewParams->end();
1029 NewParam != NewParamEnd; ++NewParam) {
1030 // Variables used to diagnose redundant default arguments
1031 bool RedundantDefaultArg = false;
1032 SourceLocation OldDefaultLoc;
1033 SourceLocation NewDefaultLoc;
1034
1035 // Variables used to diagnose missing default arguments
1036 bool MissingDefaultArg = false;
1037
Anders Carlsson327865d2009-06-12 23:20:15 +00001038 // C++0x [temp.param]p11:
1039 // If a template parameter of a class template is a template parameter pack,
1040 // it must be the last template parameter.
1041 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001042 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001043 diag::err_template_param_pack_must_be_last_template_parameter);
1044 Invalid = true;
1045 }
1046
Douglas Gregordba32632009-02-10 19:49:53 +00001047 if (TemplateTypeParmDecl *NewTypeParm
1048 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001049 // Check the presence of a default argument here.
1050 if (NewTypeParm->hasDefaultArgument() &&
1051 DiagnoseDefaultTemplateArgument(*this, TPC,
1052 NewTypeParm->getLocation(),
1053 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1054 .getFullSourceRange()))
1055 NewTypeParm->removeDefaultArgument();
1056
1057 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001058 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001059 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001060
Anders Carlsson327865d2009-06-12 23:20:15 +00001061 if (NewTypeParm->isParameterPack()) {
1062 assert(!NewTypeParm->hasDefaultArgument() &&
1063 "Parameter packs can't have a default argument!");
1064 SawParameterPack = true;
1065 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001066 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001067 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001068 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1069 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1070 SawDefaultArgument = true;
1071 RedundantDefaultArg = true;
1072 PreviousDefaultArgLoc = NewDefaultLoc;
1073 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1074 // Merge the default argument from the old declaration to the
1075 // new declaration.
1076 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001077 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001078 true);
1079 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1080 } else if (NewTypeParm->hasDefaultArgument()) {
1081 SawDefaultArgument = true;
1082 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1083 } else if (SawDefaultArgument)
1084 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001085 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001086 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001087 // Check the presence of a default argument here.
1088 if (NewNonTypeParm->hasDefaultArgument() &&
1089 DiagnoseDefaultTemplateArgument(*this, TPC,
1090 NewNonTypeParm->getLocation(),
1091 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1092 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1093 NewNonTypeParm->setDefaultArgument(0);
1094 }
1095
Mike Stump12b8ce12009-08-04 21:02:39 +00001096 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001097 NonTypeTemplateParmDecl *OldNonTypeParm
1098 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001099 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001100 NewNonTypeParm->hasDefaultArgument()) {
1101 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1102 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1103 SawDefaultArgument = true;
1104 RedundantDefaultArg = true;
1105 PreviousDefaultArgLoc = NewDefaultLoc;
1106 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1107 // Merge the default argument from the old declaration to the
1108 // new declaration.
1109 SawDefaultArgument = true;
1110 // FIXME: We need to create a new kind of "default argument"
1111 // expression that points to a previous template template
1112 // parameter.
1113 NewNonTypeParm->setDefaultArgument(
1114 OldNonTypeParm->getDefaultArgument());
1115 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1116 } else if (NewNonTypeParm->hasDefaultArgument()) {
1117 SawDefaultArgument = true;
1118 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1119 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001120 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001121 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001122 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001123 TemplateTemplateParmDecl *NewTemplateParm
1124 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001125 if (NewTemplateParm->hasDefaultArgument() &&
1126 DiagnoseDefaultTemplateArgument(*this, TPC,
1127 NewTemplateParm->getLocation(),
1128 NewTemplateParm->getDefaultArgument().getSourceRange()))
1129 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1130
1131 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001132 TemplateTemplateParmDecl *OldTemplateParm
1133 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001134 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001135 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001136 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1137 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001138 SawDefaultArgument = true;
1139 RedundantDefaultArg = true;
1140 PreviousDefaultArgLoc = NewDefaultLoc;
1141 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1142 // Merge the default argument from the old declaration to the
1143 // new declaration.
1144 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001145 // FIXME: We need to create a new kind of "default argument" expression
1146 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001147 NewTemplateParm->setDefaultArgument(
1148 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001149 PreviousDefaultArgLoc
1150 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001151 } else if (NewTemplateParm->hasDefaultArgument()) {
1152 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001153 PreviousDefaultArgLoc
1154 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001155 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001156 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001157 }
1158
1159 if (RedundantDefaultArg) {
1160 // C++ [temp.param]p12:
1161 // A template-parameter shall not be given default arguments
1162 // by two different declarations in the same scope.
1163 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1164 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1165 Invalid = true;
1166 } else if (MissingDefaultArg) {
1167 // C++ [temp.param]p11:
1168 // If a template-parameter has a default template-argument,
1169 // all subsequent template-parameters shall have a default
1170 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001171 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001172 diag::err_template_param_default_arg_missing);
1173 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1174 Invalid = true;
1175 }
1176
1177 // If we have an old template parameter list that we're merging
1178 // in, move on to the next parameter.
1179 if (OldParams)
1180 ++OldParam;
1181 }
1182
1183 return Invalid;
1184}
Douglas Gregord32e0282009-02-09 23:23:08 +00001185
Mike Stump11289f42009-09-09 15:08:12 +00001186/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001187/// specifier, returning the template parameter list that applies to the
1188/// name.
1189///
1190/// \param DeclStartLoc the start of the declaration that has a scope
1191/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001192///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001193/// \param SS the scope specifier that will be matched to the given template
1194/// parameter lists. This scope specifier precedes a qualified name that is
1195/// being declared.
1196///
1197/// \param ParamLists the template parameter lists, from the outermost to the
1198/// innermost template parameter lists.
1199///
1200/// \param NumParamLists the number of template parameter lists in ParamLists.
1201///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001202/// \param IsExplicitSpecialization will be set true if the entity being
1203/// declared is an explicit specialization, false otherwise.
1204///
Mike Stump11289f42009-09-09 15:08:12 +00001205/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001206/// name that is preceded by the scope specifier @p SS. This template
1207/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001208/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001209/// template specialization), or may be NULL (if we were's declaring isn't
1210/// itself a template).
1211TemplateParameterList *
1212Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1213 const CXXScopeSpec &SS,
1214 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001215 unsigned NumParamLists,
1216 bool &IsExplicitSpecialization) {
1217 IsExplicitSpecialization = false;
1218
Douglas Gregord8d297c2009-07-21 23:53:31 +00001219 // Find the template-ids that occur within the nested-name-specifier. These
1220 // template-ids will match up with the template parameter lists.
1221 llvm::SmallVector<const TemplateSpecializationType *, 4>
1222 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001223 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1224 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001225 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1226 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001227 const Type *T = NNS->getAsType();
1228 if (!T) break;
1229
1230 // C++0x [temp.expl.spec]p17:
1231 // A member or a member template may be nested within many
1232 // enclosing class templates. In an explicit specialization for
1233 // such a member, the member declaration shall be preceded by a
1234 // template<> for each enclosing class template that is
1235 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001236 //
1237 // Following the existing practice of GNU and EDG, we allow a typedef of a
1238 // template specialization type.
1239 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1240 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001241
Mike Stump11289f42009-09-09 15:08:12 +00001242 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001243 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001244 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1245 if (!Template)
1246 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001247
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001248 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001249 ClassTemplateSpecializationDecl *SpecDecl
1250 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1251 // If the nested name specifier refers to an explicit specialization,
1252 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001253 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1254 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001255 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001256 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001257 }
Mike Stump11289f42009-09-09 15:08:12 +00001258
Douglas Gregord8d297c2009-07-21 23:53:31 +00001259 TemplateIdsInSpecifier.push_back(SpecType);
1260 }
1261 }
Mike Stump11289f42009-09-09 15:08:12 +00001262
Douglas Gregord8d297c2009-07-21 23:53:31 +00001263 // Reverse the list of template-ids in the scope specifier, so that we can
1264 // more easily match up the template-ids and the template parameter lists.
1265 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001266
Douglas Gregord8d297c2009-07-21 23:53:31 +00001267 SourceLocation FirstTemplateLoc = DeclStartLoc;
1268 if (NumParamLists)
1269 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001270
Douglas Gregord8d297c2009-07-21 23:53:31 +00001271 // Match the template-ids found in the specifier to the template parameter
1272 // lists.
1273 unsigned Idx = 0;
1274 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1275 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001276 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1277 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001278 if (Idx >= NumParamLists) {
1279 // We have a template-id without a corresponding template parameter
1280 // list.
1281 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001282 // FIXME: the location information here isn't great.
1283 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001284 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001285 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001286 << SS.getRange();
1287 } else {
1288 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1289 << SS.getRange()
1290 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1291 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001292 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001293 }
1294 return 0;
1295 }
Mike Stump11289f42009-09-09 15:08:12 +00001296
Douglas Gregord8d297c2009-07-21 23:53:31 +00001297 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001298 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001299 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001300 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1301
Mike Stump11289f42009-09-09 15:08:12 +00001302 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001303 = dyn_cast<ClassTemplateDecl>(Template)) {
1304 TemplateParameterList *ExpectedTemplateParams = 0;
1305 // Is this template-id naming the primary template?
1306 if (Context.hasSameType(TemplateId,
John McCalle78aac42010-03-10 03:28:59 +00001307 ClassTemplate->getInjectedClassNameSpecialization(Context)))
Douglas Gregor15301382009-07-30 17:40:51 +00001308 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1309 // ... or a partial specialization?
1310 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1311 = ClassTemplate->findPartialSpecialization(TemplateId))
1312 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1313
1314 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001315 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001316 ExpectedTemplateParams,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001317 true, TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00001318 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001319
1320 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001321 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001322 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001323 diag::err_template_param_list_matches_nontemplate)
1324 << TemplateId
1325 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001326 else
1327 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001328 }
Mike Stump11289f42009-09-09 15:08:12 +00001329
Douglas Gregord8d297c2009-07-21 23:53:31 +00001330 // If there were at least as many template-ids as there were template
1331 // parameter lists, then there are no template parameter lists remaining for
1332 // the declaration itself.
1333 if (Idx >= NumParamLists)
1334 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001335
Douglas Gregord8d297c2009-07-21 23:53:31 +00001336 // If there were too many template parameter lists, complain about that now.
1337 if (Idx != NumParamLists - 1) {
1338 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001339 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001340 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001341 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1342 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001343 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1344 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001345
1346 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1347 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1348 diag::note_explicit_template_spec_does_not_need_header)
1349 << ExplicitSpecializationsInSpecifier.back();
1350 ExplicitSpecializationsInSpecifier.pop_back();
1351 }
1352
Douglas Gregord8d297c2009-07-21 23:53:31 +00001353 ++Idx;
1354 }
1355 }
Mike Stump11289f42009-09-09 15:08:12 +00001356
Douglas Gregord8d297c2009-07-21 23:53:31 +00001357 // Return the last template parameter list, which corresponds to the
1358 // entity being declared.
1359 return ParamLists[NumParamLists - 1];
1360}
1361
Douglas Gregordc572a32009-03-30 22:58:21 +00001362QualType Sema::CheckTemplateIdType(TemplateName Name,
1363 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001364 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001365 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001366 if (!Template) {
1367 // The template name does not resolve to a template, so we just
1368 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001369 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001370 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001371
Douglas Gregorc40290e2009-03-09 23:48:35 +00001372 // Check that the template argument list is well-formed for this
1373 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001374 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001375 TemplateArgs.size());
1376 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001377 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001378 return QualType();
1379
Mike Stump11289f42009-09-09 15:08:12 +00001380 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001381 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001382 "Converted template argument list is too short!");
1383
1384 QualType CanonType;
1385
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001386 if (Name.isDependent() ||
1387 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001388 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001389 // This class template specialization is a dependent
1390 // type. Therefore, its canonical type is another class template
1391 // specialization type that contains all of the converted
1392 // arguments in canonical form. This ensures that, e.g., A<T> and
1393 // A<T, T> have identical types when A is declared as:
1394 //
1395 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001396 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001397 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001398 Converted.getFlatArguments(),
1399 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001400
Douglas Gregora8e02e72009-07-28 23:00:59 +00001401 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001402 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001403 // In the future, we need to teach getTemplateSpecializationType to only
1404 // build the canonical type and return that to us.
1405 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001406 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001407 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001408 // Find the class template specialization declaration that
1409 // corresponds to these arguments.
1410 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001411 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001412 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001413 Converted.flatSize(),
1414 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001415 void *InsertPos = 0;
1416 ClassTemplateSpecializationDecl *Decl
1417 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1418 if (!Decl) {
1419 // This is the first time we have referenced this class template
1420 // specialization. Create the canonical declaration and add it to
1421 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001422 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001423 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001424 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001425 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001426 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001427 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1428 Decl->setLexicalDeclContext(CurContext);
1429 }
1430
1431 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001432 assert(isa<RecordType>(CanonType) &&
1433 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001434 }
Mike Stump11289f42009-09-09 15:08:12 +00001435
Douglas Gregorc40290e2009-03-09 23:48:35 +00001436 // Build the fully-sugared type for this class template
1437 // specialization, which refers back to the class template
1438 // specialization we created or found.
John McCall6b51f282009-11-23 01:53:49 +00001439 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001440}
1441
Douglas Gregor67a65642009-02-17 23:15:12 +00001442Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001443Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001444 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001445 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001446 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001447 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001448
Douglas Gregorc40290e2009-03-09 23:48:35 +00001449 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001450 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001451 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001452
John McCall6b51f282009-11-23 01:53:49 +00001453 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001454 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001455
1456 if (Result.isNull())
1457 return true;
1458
John McCallbcd03502009-12-07 02:54:59 +00001459 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001460 TemplateSpecializationTypeLoc TL
1461 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1462 TL.setTemplateNameLoc(TemplateLoc);
1463 TL.setLAngleLoc(LAngleLoc);
1464 TL.setRAngleLoc(RAngleLoc);
1465 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1466 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1467
1468 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001469}
John McCall06f6fe8d2009-09-04 01:14:41 +00001470
John McCalld8fe9af2009-09-08 17:47:29 +00001471Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1472 TagUseKind TUK,
1473 DeclSpec::TST TagSpec,
1474 SourceLocation TagLoc) {
1475 if (TypeResult.isInvalid())
1476 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001477
John McCall0ad16662009-10-29 08:12:44 +00001478 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001479 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001480 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001481
John McCalld8fe9af2009-09-08 17:47:29 +00001482 // Verify the tag specifier.
1483 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001484
John McCalld8fe9af2009-09-08 17:47:29 +00001485 if (const RecordType *RT = Type->getAs<RecordType>()) {
1486 RecordDecl *D = RT->getDecl();
1487
1488 IdentifierInfo *Id = D->getIdentifier();
1489 assert(Id && "templated class must have an identifier");
1490
1491 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1492 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001493 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001494 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1495 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001496 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001497 }
1498 }
1499
John McCalld8fe9af2009-09-08 17:47:29 +00001500 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1501
1502 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001503}
1504
John McCalle66edc12009-11-24 19:00:30 +00001505Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1506 LookupResult &R,
1507 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001508 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001509 // FIXME: Can we do any checking at this point? I guess we could check the
1510 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001511 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001512 // though.
John McCalle66edc12009-11-24 19:00:30 +00001513
1514 // These should be filtered out by our callers.
1515 assert(!R.empty() && "empty lookup results when building templateid");
1516 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1517
1518 NestedNameSpecifier *Qualifier = 0;
1519 SourceRange QualifierRange;
1520 if (SS.isSet()) {
1521 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1522 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001523 }
John McCall58cc69d2010-01-27 01:50:18 +00001524
1525 // We don't want lookup warnings at this point.
1526 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001527
John McCalle66edc12009-11-24 19:00:30 +00001528 bool Dependent
1529 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1530 &TemplateArgs);
1531 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001532 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001533 Qualifier, QualifierRange,
1534 R.getLookupName(), R.getNameLoc(),
1535 RequiresADL, TemplateArgs);
John McCall58cc69d2010-01-27 01:50:18 +00001536 ULE->addDecls(R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001537
1538 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001539}
1540
John McCalle66edc12009-11-24 19:00:30 +00001541// We actually only call this from template instantiation.
1542Sema::OwningExprResult
1543Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1544 DeclarationName Name,
1545 SourceLocation NameLoc,
1546 const TemplateArgumentListInfo &TemplateArgs) {
1547 DeclContext *DC;
1548 if (!(DC = computeDeclContext(SS, false)) ||
1549 DC->isDependentContext() ||
1550 RequireCompleteDeclContext(SS))
1551 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001552
John McCalle66edc12009-11-24 19:00:30 +00001553 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1554 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00001555
John McCalle66edc12009-11-24 19:00:30 +00001556 if (R.isAmbiguous())
1557 return ExprError();
1558
1559 if (R.empty()) {
1560 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1561 << Name << SS.getRange();
1562 return ExprError();
1563 }
1564
1565 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1566 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1567 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1568 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1569 return ExprError();
1570 }
1571
1572 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001573}
1574
Douglas Gregorb67535d2009-03-31 00:43:58 +00001575/// \brief Form a dependent template name.
1576///
1577/// This action forms a dependent template name given the template
1578/// name and its (presumably dependent) scope specifier. For
1579/// example, given "MetaFun::template apply", the scope specifier \p
1580/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1581/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001582Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001583Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001584 const CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001585 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001586 TypeTy *ObjectType,
1587 bool EnteringContext) {
Douglas Gregor9abe2372010-01-19 16:01:07 +00001588 DeclContext *LookupCtx = 0;
1589 if (SS.isSet())
1590 LookupCtx = computeDeclContext(SS, EnteringContext);
1591 if (!LookupCtx && ObjectType)
1592 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1593 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001594 // C++0x [temp.names]p5:
1595 // If a name prefixed by the keyword template is not the name of
1596 // a template, the program is ill-formed. [Note: the keyword
1597 // template may not be applied to non-template members of class
1598 // templates. -end note ] [ Note: as is the case with the
1599 // typename prefix, the template prefix is allowed in cases
1600 // where it is not strictly necessary; i.e., when the
1601 // nested-name-specifier or the expression on the left of the ->
1602 // or . is not dependent on a template-parameter, or the use
1603 // does not appear in the scope of a template. -end note]
1604 //
1605 // Note: C++03 was more strict here, because it banned the use of
1606 // the "template" keyword prior to a template-name that was not a
1607 // dependent name. C++ DR468 relaxed this requirement (the
1608 // "template" keyword is now permitted). We follow the C++0x
1609 // rules, even in C++03 mode, retroactively applying the DR.
1610 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001611 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001612 EnteringContext, Template);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001613 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1614 isa<CXXRecordDecl>(LookupCtx) &&
1615 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00001616 // This is a dependent template.
1617 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001618 Diag(Name.getSourceRange().getBegin(),
1619 diag::err_template_kw_refers_to_non_template)
1620 << GetNameFromUnqualifiedId(Name)
1621 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001622 return TemplateTy();
Douglas Gregord2e6a452010-01-14 17:47:39 +00001623 } else {
1624 // We found something; return it.
1625 return Template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001626 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001627 }
1628
Mike Stump11289f42009-09-09 15:08:12 +00001629 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001630 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001631
1632 switch (Name.getKind()) {
1633 case UnqualifiedId::IK_Identifier:
1634 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1635 Name.Identifier));
1636
Douglas Gregor71395fa2009-11-04 00:56:37 +00001637 case UnqualifiedId::IK_OperatorFunctionId:
1638 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1639 Name.OperatorFunctionId.Operator));
Alexis Hunted0530f2009-11-28 08:58:14 +00001640
1641 case UnqualifiedId::IK_LiteralOperatorId:
1642 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1643
Douglas Gregor3cf81312009-11-03 23:16:33 +00001644 default:
1645 break;
1646 }
1647
1648 Diag(Name.getSourceRange().getBegin(),
1649 diag::err_template_kw_refers_to_non_template)
1650 << GetNameFromUnqualifiedId(Name)
1651 << Name.getSourceRange();
1652 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001653}
1654
Mike Stump11289f42009-09-09 15:08:12 +00001655bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001656 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001657 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001658 const TemplateArgument &Arg = AL.getArgument();
1659
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001660 // Check template type parameter.
1661 if (Arg.getKind() != TemplateArgument::Type) {
1662 // C++ [temp.arg.type]p1:
1663 // A template-argument for a template-parameter which is a
1664 // type shall be a type-id.
1665
1666 // We have a template type parameter but the template argument
1667 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001668 SourceRange SR = AL.getSourceRange();
1669 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001670 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001671
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001672 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001673 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001674
John McCallbcd03502009-12-07 02:54:59 +00001675 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001676 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001677
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001678 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001679 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001680 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001681 return false;
1682}
1683
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001684/// \brief Substitute template arguments into the default template argument for
1685/// the given template type parameter.
1686///
1687/// \param SemaRef the semantic analysis object for which we are performing
1688/// the substitution.
1689///
1690/// \param Template the template that we are synthesizing template arguments
1691/// for.
1692///
1693/// \param TemplateLoc the location of the template name that started the
1694/// template-id we are checking.
1695///
1696/// \param RAngleLoc the location of the right angle bracket ('>') that
1697/// terminates the template-id.
1698///
1699/// \param Param the template template parameter whose default we are
1700/// substituting into.
1701///
1702/// \param Converted the list of template arguments provided for template
1703/// parameters that precede \p Param in the template parameter list.
1704///
1705/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001706static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001707SubstDefaultTemplateArgument(Sema &SemaRef,
1708 TemplateDecl *Template,
1709 SourceLocation TemplateLoc,
1710 SourceLocation RAngleLoc,
1711 TemplateTypeParmDecl *Param,
1712 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001713 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001714
1715 // If the argument type is dependent, instantiate it now based
1716 // on the previously-computed template arguments.
1717 if (ArgType->getType()->isDependentType()) {
1718 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1719 /*TakeArgs=*/false);
1720
1721 MultiLevelTemplateArgumentList AllTemplateArgs
1722 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1723
1724 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1725 Template, Converted.getFlatArguments(),
1726 Converted.flatSize(),
1727 SourceRange(TemplateLoc, RAngleLoc));
1728
1729 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1730 Param->getDefaultArgumentLoc(),
1731 Param->getDeclName());
1732 }
1733
1734 return ArgType;
1735}
1736
1737/// \brief Substitute template arguments into the default template argument for
1738/// the given non-type template parameter.
1739///
1740/// \param SemaRef the semantic analysis object for which we are performing
1741/// the substitution.
1742///
1743/// \param Template the template that we are synthesizing template arguments
1744/// for.
1745///
1746/// \param TemplateLoc the location of the template name that started the
1747/// template-id we are checking.
1748///
1749/// \param RAngleLoc the location of the right angle bracket ('>') that
1750/// terminates the template-id.
1751///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001752/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001753/// substituting into.
1754///
1755/// \param Converted the list of template arguments provided for template
1756/// parameters that precede \p Param in the template parameter list.
1757///
1758/// \returns the substituted template argument, or NULL if an error occurred.
1759static Sema::OwningExprResult
1760SubstDefaultTemplateArgument(Sema &SemaRef,
1761 TemplateDecl *Template,
1762 SourceLocation TemplateLoc,
1763 SourceLocation RAngleLoc,
1764 NonTypeTemplateParmDecl *Param,
1765 TemplateArgumentListBuilder &Converted) {
1766 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1767 /*TakeArgs=*/false);
1768
1769 MultiLevelTemplateArgumentList AllTemplateArgs
1770 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1771
1772 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1773 Template, Converted.getFlatArguments(),
1774 Converted.flatSize(),
1775 SourceRange(TemplateLoc, RAngleLoc));
1776
1777 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1778}
1779
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001780/// \brief Substitute template arguments into the default template argument for
1781/// the given template template parameter.
1782///
1783/// \param SemaRef the semantic analysis object for which we are performing
1784/// the substitution.
1785///
1786/// \param Template the template that we are synthesizing template arguments
1787/// for.
1788///
1789/// \param TemplateLoc the location of the template name that started the
1790/// template-id we are checking.
1791///
1792/// \param RAngleLoc the location of the right angle bracket ('>') that
1793/// terminates the template-id.
1794///
1795/// \param Param the template template parameter whose default we are
1796/// substituting into.
1797///
1798/// \param Converted the list of template arguments provided for template
1799/// parameters that precede \p Param in the template parameter list.
1800///
1801/// \returns the substituted template argument, or NULL if an error occurred.
1802static TemplateName
1803SubstDefaultTemplateArgument(Sema &SemaRef,
1804 TemplateDecl *Template,
1805 SourceLocation TemplateLoc,
1806 SourceLocation RAngleLoc,
1807 TemplateTemplateParmDecl *Param,
1808 TemplateArgumentListBuilder &Converted) {
1809 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1810 /*TakeArgs=*/false);
1811
1812 MultiLevelTemplateArgumentList AllTemplateArgs
1813 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1814
1815 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1816 Template, Converted.getFlatArguments(),
1817 Converted.flatSize(),
1818 SourceRange(TemplateLoc, RAngleLoc));
1819
1820 return SemaRef.SubstTemplateName(
1821 Param->getDefaultArgument().getArgument().getAsTemplate(),
1822 Param->getDefaultArgument().getTemplateNameLoc(),
1823 AllTemplateArgs);
1824}
1825
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001826/// \brief If the given template parameter has a default template
1827/// argument, substitute into that default template argument and
1828/// return the corresponding template argument.
1829TemplateArgumentLoc
1830Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1831 SourceLocation TemplateLoc,
1832 SourceLocation RAngleLoc,
1833 Decl *Param,
1834 TemplateArgumentListBuilder &Converted) {
1835 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1836 if (!TypeParm->hasDefaultArgument())
1837 return TemplateArgumentLoc();
1838
John McCallbcd03502009-12-07 02:54:59 +00001839 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001840 TemplateLoc,
1841 RAngleLoc,
1842 TypeParm,
1843 Converted);
1844 if (DI)
1845 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1846
1847 return TemplateArgumentLoc();
1848 }
1849
1850 if (NonTypeTemplateParmDecl *NonTypeParm
1851 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1852 if (!NonTypeParm->hasDefaultArgument())
1853 return TemplateArgumentLoc();
1854
1855 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1856 TemplateLoc,
1857 RAngleLoc,
1858 NonTypeParm,
1859 Converted);
1860 if (Arg.isInvalid())
1861 return TemplateArgumentLoc();
1862
1863 Expr *ArgE = Arg.takeAs<Expr>();
1864 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1865 }
1866
1867 TemplateTemplateParmDecl *TempTempParm
1868 = cast<TemplateTemplateParmDecl>(Param);
1869 if (!TempTempParm->hasDefaultArgument())
1870 return TemplateArgumentLoc();
1871
1872 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1873 TemplateLoc,
1874 RAngleLoc,
1875 TempTempParm,
1876 Converted);
1877 if (TName.isNull())
1878 return TemplateArgumentLoc();
1879
1880 return TemplateArgumentLoc(TemplateArgument(TName),
1881 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1882 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1883}
1884
Douglas Gregorda0fb532009-11-11 19:31:23 +00001885/// \brief Check that the given template argument corresponds to the given
1886/// template parameter.
1887bool Sema::CheckTemplateArgument(NamedDecl *Param,
1888 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001889 TemplateDecl *Template,
1890 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001891 SourceLocation RAngleLoc,
1892 TemplateArgumentListBuilder &Converted) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001893 // Check template type parameters.
1894 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001895 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001896
Douglas Gregoreebed722009-11-11 19:41:09 +00001897 // Check non-type template parameters.
1898 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001899 // Do substitution on the type of the non-type template parameter
1900 // with the template arguments we've seen thus far.
1901 QualType NTTPType = NTTP->getType();
1902 if (NTTPType->isDependentType()) {
1903 // Do substitution on the type of the non-type template parameter.
1904 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1905 NTTP, Converted.getFlatArguments(),
1906 Converted.flatSize(),
1907 SourceRange(TemplateLoc, RAngleLoc));
1908
1909 TemplateArgumentList TemplateArgs(Context, Converted,
1910 /*TakeArgs=*/false);
1911 NTTPType = SubstType(NTTPType,
1912 MultiLevelTemplateArgumentList(TemplateArgs),
1913 NTTP->getLocation(),
1914 NTTP->getDeclName());
1915 // If that worked, check the non-type template parameter type
1916 // for validity.
1917 if (!NTTPType.isNull())
1918 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1919 NTTP->getLocation());
1920 if (NTTPType.isNull())
1921 return true;
1922 }
1923
1924 switch (Arg.getArgument().getKind()) {
1925 case TemplateArgument::Null:
1926 assert(false && "Should never see a NULL template argument here");
1927 return true;
1928
1929 case TemplateArgument::Expression: {
1930 Expr *E = Arg.getArgument().getAsExpr();
1931 TemplateArgument Result;
1932 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1933 return true;
1934
1935 Converted.Append(Result);
1936 break;
1937 }
1938
1939 case TemplateArgument::Declaration:
1940 case TemplateArgument::Integral:
1941 // We've already checked this template argument, so just copy
1942 // it to the list of converted arguments.
1943 Converted.Append(Arg.getArgument());
1944 break;
1945
1946 case TemplateArgument::Template:
1947 // We were given a template template argument. It may not be ill-formed;
1948 // see below.
1949 if (DependentTemplateName *DTN
1950 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1951 // We have a template argument such as \c T::template X, which we
1952 // parsed as a template template argument. However, since we now
1953 // know that we need a non-type template argument, convert this
1954 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00001955 Expr *E = DependentScopeDeclRefExpr::Create(Context,
1956 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00001957 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00001958 DTN->getIdentifier(),
1959 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00001960
1961 TemplateArgument Result;
1962 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1963 return true;
1964
1965 Converted.Append(Result);
1966 break;
1967 }
1968
1969 // We have a template argument that actually does refer to a class
1970 // template, template alias, or template template parameter, and
1971 // therefore cannot be a non-type template argument.
1972 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1973 << Arg.getSourceRange();
1974
1975 Diag(Param->getLocation(), diag::note_template_param_here);
1976 return true;
1977
1978 case TemplateArgument::Type: {
1979 // We have a non-type template parameter but the template
1980 // argument is a type.
1981
1982 // C++ [temp.arg]p2:
1983 // In a template-argument, an ambiguity between a type-id and
1984 // an expression is resolved to a type-id, regardless of the
1985 // form of the corresponding template-parameter.
1986 //
1987 // We warn specifically about this case, since it can be rather
1988 // confusing for users.
1989 QualType T = Arg.getArgument().getAsType();
1990 SourceRange SR = Arg.getSourceRange();
1991 if (T->isFunctionType())
1992 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1993 else
1994 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1995 Diag(Param->getLocation(), diag::note_template_param_here);
1996 return true;
1997 }
1998
1999 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002000 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002001 break;
2002 }
2003
2004 return false;
2005 }
2006
2007
2008 // Check template template parameters.
2009 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2010
2011 // Substitute into the template parameter list of the template
2012 // template parameter, since previously-supplied template arguments
2013 // may appear within the template template parameter.
2014 {
2015 // Set up a template instantiation context.
2016 LocalInstantiationScope Scope(*this);
2017 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2018 TempParm, Converted.getFlatArguments(),
2019 Converted.flatSize(),
2020 SourceRange(TemplateLoc, RAngleLoc));
2021
2022 TemplateArgumentList TemplateArgs(Context, Converted,
2023 /*TakeArgs=*/false);
2024 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2025 SubstDecl(TempParm, CurContext,
2026 MultiLevelTemplateArgumentList(TemplateArgs)));
2027 if (!TempParm)
2028 return true;
2029
2030 // FIXME: TempParam is leaked.
2031 }
2032
2033 switch (Arg.getArgument().getKind()) {
2034 case TemplateArgument::Null:
2035 assert(false && "Should never see a NULL template argument here");
2036 return true;
2037
2038 case TemplateArgument::Template:
2039 if (CheckTemplateArgument(TempParm, Arg))
2040 return true;
2041
2042 Converted.Append(Arg.getArgument());
2043 break;
2044
2045 case TemplateArgument::Expression:
2046 case TemplateArgument::Type:
2047 // We have a template template parameter but the template
2048 // argument does not refer to a template.
2049 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2050 return true;
2051
2052 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002053 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002054 "Declaration argument with template template parameter");
2055 break;
2056 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002057 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002058 "Integral argument with template template parameter");
2059 break;
2060
2061 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002062 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002063 break;
2064 }
2065
2066 return false;
2067}
2068
Douglas Gregord32e0282009-02-09 23:23:08 +00002069/// \brief Check that the given template argument list is well-formed
2070/// for specializing the given template.
2071bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2072 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002073 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002074 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002075 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002076 TemplateParameterList *Params = Template->getTemplateParameters();
2077 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002078 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002079 bool Invalid = false;
2080
John McCall6b51f282009-11-23 01:53:49 +00002081 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2082
Mike Stump11289f42009-09-09 15:08:12 +00002083 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002084 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002085
Anders Carlsson15201f12009-06-13 02:08:00 +00002086 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002087 (NumArgs < Params->getMinRequiredArguments() &&
2088 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002089 // FIXME: point at either the first arg beyond what we can handle,
2090 // or the '>', depending on whether we have too many or too few
2091 // arguments.
2092 SourceRange Range;
2093 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002094 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002095 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2096 << (NumArgs > NumParams)
2097 << (isa<ClassTemplateDecl>(Template)? 0 :
2098 isa<FunctionTemplateDecl>(Template)? 1 :
2099 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2100 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002101 Diag(Template->getLocation(), diag::note_template_decl_here)
2102 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002103 Invalid = true;
2104 }
Mike Stump11289f42009-09-09 15:08:12 +00002105
2106 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002107 // [...] The type and form of each template-argument specified in
2108 // a template-id shall match the type and form specified for the
2109 // corresponding parameter declared by the template in its
2110 // template-parameter-list.
2111 unsigned ArgIdx = 0;
2112 for (TemplateParameterList::iterator Param = Params->begin(),
2113 ParamEnd = Params->end();
2114 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002115 if (ArgIdx > NumArgs && PartialTemplateArgs)
2116 break;
Mike Stump11289f42009-09-09 15:08:12 +00002117
Douglas Gregoreebed722009-11-11 19:41:09 +00002118 // If we have a template parameter pack, check every remaining template
2119 // argument against that template parameter pack.
2120 if ((*Param)->isTemplateParameterPack()) {
2121 Converted.BeginPack();
2122 for (; ArgIdx < NumArgs; ++ArgIdx) {
2123 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2124 TemplateLoc, RAngleLoc, Converted)) {
2125 Invalid = true;
2126 break;
2127 }
2128 }
2129 Converted.EndPack();
2130 continue;
2131 }
2132
Douglas Gregor84d49a22009-11-11 21:54:23 +00002133 if (ArgIdx < NumArgs) {
2134 // Check the template argument we were given.
2135 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2136 TemplateLoc, RAngleLoc, Converted))
2137 return true;
2138
2139 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002140 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002141
Douglas Gregor84d49a22009-11-11 21:54:23 +00002142 // We have a default template argument that we will use.
2143 TemplateArgumentLoc Arg;
2144
2145 // Retrieve the default template argument from the template
2146 // parameter. For each kind of template parameter, we substitute the
2147 // template arguments provided thus far and any "outer" template arguments
2148 // (when the template parameter was part of a nested template) into
2149 // the default argument.
2150 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2151 if (!TTP->hasDefaultArgument()) {
2152 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2153 break;
2154 }
2155
John McCallbcd03502009-12-07 02:54:59 +00002156 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002157 Template,
2158 TemplateLoc,
2159 RAngleLoc,
2160 TTP,
2161 Converted);
2162 if (!ArgType)
2163 return true;
2164
2165 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2166 ArgType);
2167 } else if (NonTypeTemplateParmDecl *NTTP
2168 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2169 if (!NTTP->hasDefaultArgument()) {
2170 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2171 break;
2172 }
2173
2174 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2175 TemplateLoc,
2176 RAngleLoc,
2177 NTTP,
2178 Converted);
2179 if (E.isInvalid())
2180 return true;
2181
2182 Expr *Ex = E.takeAs<Expr>();
2183 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2184 } else {
2185 TemplateTemplateParmDecl *TempParm
2186 = cast<TemplateTemplateParmDecl>(*Param);
2187
2188 if (!TempParm->hasDefaultArgument()) {
2189 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2190 break;
2191 }
2192
2193 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2194 TemplateLoc,
2195 RAngleLoc,
2196 TempParm,
2197 Converted);
2198 if (Name.isNull())
2199 return true;
2200
2201 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2202 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2203 TempParm->getDefaultArgument().getTemplateNameLoc());
2204 }
2205
2206 // Introduce an instantiation record that describes where we are using
2207 // the default template argument.
2208 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2209 Converted.getFlatArguments(),
2210 Converted.flatSize(),
2211 SourceRange(TemplateLoc, RAngleLoc));
2212
2213 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002214 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002215 RAngleLoc, Converted))
2216 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002217 }
2218
2219 return Invalid;
2220}
2221
2222/// \brief Check a template argument against its corresponding
2223/// template type parameter.
2224///
2225/// This routine implements the semantics of C++ [temp.arg.type]. It
2226/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002227bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002228 TypeSourceInfo *ArgInfo) {
2229 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002230 QualType Arg = ArgInfo->getType();
2231
Douglas Gregord32e0282009-02-09 23:23:08 +00002232 // C++ [temp.arg.type]p2:
2233 // A local type, a type with no linkage, an unnamed type or a type
2234 // compounded from any of these types shall not be used as a
2235 // template-argument for a template type-parameter.
2236 //
2237 // FIXME: Perform the recursive and no-linkage type checks.
2238 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002239 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002240 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002241 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002242 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002243 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2244 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2245 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2246 << QualType(Tag, 0) << SR;
2247 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002248 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002249 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2250 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002251 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2252 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002253 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2254 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2255 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002256 }
2257
2258 return false;
2259}
2260
Douglas Gregorccb07762009-02-11 19:52:55 +00002261/// \brief Checks whether the given template argument is the address
2262/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002263bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2264 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002265 bool Invalid = false;
2266
2267 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002268 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002269 Arg = Cast->getSubExpr();
2270
Sebastian Redl576fd422009-05-10 18:38:11 +00002271 // C++0x allows nullptr, and there's no further checking to be done for that.
2272 if (Arg->getType()->isNullPtrType())
2273 return false;
2274
Douglas Gregorccb07762009-02-11 19:52:55 +00002275 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002276 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002277 // A template-argument for a non-type, non-template
2278 // template-parameter shall be one of: [...]
2279 //
2280 // -- the address of an object or function with external
2281 // linkage, including function templates and function
2282 // template-ids but excluding non-static class members,
2283 // expressed as & id-expression where the & is optional if
2284 // the name refers to a function or array, or if the
2285 // corresponding template-parameter is a reference; or
2286 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002287
Douglas Gregorccb07762009-02-11 19:52:55 +00002288 // Ignore (and complain about) any excess parentheses.
2289 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2290 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002291 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002292 diag::err_template_arg_extra_parens)
2293 << Arg->getSourceRange();
2294 Invalid = true;
2295 }
2296
2297 Arg = Parens->getSubExpr();
2298 }
2299
2300 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2301 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2302 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2303 } else
2304 DRE = dyn_cast<DeclRefExpr>(Arg);
2305
Chandler Carruth724a8a12010-01-31 10:01:20 +00002306 if (!DRE)
2307 return Diag(Arg->getSourceRange().getBegin(),
2308 diag::err_template_arg_not_decl_ref)
2309 << Arg->getSourceRange();
2310
2311 // Stop checking the precise nature of the argument if it is value dependent,
2312 // it should be checked when instantiated.
2313 if (Arg->isValueDependent())
2314 return false;
2315
2316 if (!isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00002317 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002318 diag::err_template_arg_not_object_or_func_form)
2319 << Arg->getSourceRange();
2320
2321 // Cannot refer to non-static data members
2322 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2323 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2324 << Field << Arg->getSourceRange();
2325
2326 // Cannot refer to non-static member functions
2327 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2328 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00002329 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002330 diag::err_template_arg_method)
2331 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002332
Douglas Gregorccb07762009-02-11 19:52:55 +00002333 // Functions must have external linkage.
2334 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002335 if (!isExternalLinkage(Func->getLinkage())) {
Mike Stump11289f42009-09-09 15:08:12 +00002336 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002337 diag::err_template_arg_function_not_extern)
2338 << Func << Arg->getSourceRange();
2339 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2340 << true;
2341 return true;
2342 }
2343
2344 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002345 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002346 return Invalid;
2347 }
2348
2349 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002350 if (!isExternalLinkage(Var->getLinkage())) {
Mike Stump11289f42009-09-09 15:08:12 +00002351 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002352 diag::err_template_arg_object_not_extern)
2353 << Var << Arg->getSourceRange();
2354 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2355 << true;
2356 return true;
2357 }
2358
2359 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002360 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00002361 return Invalid;
2362 }
Mike Stump11289f42009-09-09 15:08:12 +00002363
Douglas Gregorccb07762009-02-11 19:52:55 +00002364 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002365 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002366 diag::err_template_arg_not_object_or_func)
2367 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002368 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002369 diag::note_template_arg_refers_here);
2370 return true;
2371}
2372
2373/// \brief Checks whether the given template argument is a pointer to
2374/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002375bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2376 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002377 bool Invalid = false;
2378
2379 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002380 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002381 Arg = Cast->getSubExpr();
2382
Sebastian Redl576fd422009-05-10 18:38:11 +00002383 // C++0x allows nullptr, and there's no further checking to be done for that.
2384 if (Arg->getType()->isNullPtrType())
2385 return false;
2386
Douglas Gregorccb07762009-02-11 19:52:55 +00002387 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002388 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002389 // A template-argument for a non-type, non-template
2390 // template-parameter shall be one of: [...]
2391 //
2392 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002393 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002394
2395 // Ignore (and complain about) any excess parentheses.
2396 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2397 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002398 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002399 diag::err_template_arg_extra_parens)
2400 << Arg->getSourceRange();
2401 Invalid = true;
2402 }
2403
2404 Arg = Parens->getSubExpr();
2405 }
2406
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002407 // A pointer-to-member constant written &Class::member.
2408 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002409 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2410 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2411 if (DRE && !DRE->getQualifier())
2412 DRE = 0;
2413 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002414 }
2415 // A constant of pointer-to-member type.
2416 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2417 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2418 if (VD->getType()->isMemberPointerType()) {
2419 if (isa<NonTypeTemplateParmDecl>(VD) ||
2420 (isa<VarDecl>(VD) &&
2421 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2422 if (Arg->isTypeDependent() || Arg->isValueDependent())
2423 Converted = TemplateArgument(Arg->Retain());
2424 else
2425 Converted = TemplateArgument(VD->getCanonicalDecl());
2426 return Invalid;
2427 }
2428 }
2429 }
2430
2431 DRE = 0;
2432 }
2433
Douglas Gregorccb07762009-02-11 19:52:55 +00002434 if (!DRE)
2435 return Diag(Arg->getSourceRange().getBegin(),
2436 diag::err_template_arg_not_pointer_to_member_form)
2437 << Arg->getSourceRange();
2438
2439 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2440 assert((isa<FieldDecl>(DRE->getDecl()) ||
2441 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2442 "Only non-static member pointers can make it here");
2443
2444 // Okay: this is the address of a non-static member, and therefore
2445 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002446 if (Arg->isTypeDependent() || Arg->isValueDependent())
2447 Converted = TemplateArgument(Arg->Retain());
2448 else
2449 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002450 return Invalid;
2451 }
2452
2453 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002454 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002455 diag::err_template_arg_not_pointer_to_member_form)
2456 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002457 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002458 diag::note_template_arg_refers_here);
2459 return true;
2460}
2461
Douglas Gregord32e0282009-02-09 23:23:08 +00002462/// \brief Check a template argument against its corresponding
2463/// non-type template parameter.
2464///
Douglas Gregor463421d2009-03-03 04:44:36 +00002465/// This routine implements the semantics of C++ [temp.arg.nontype].
2466/// It returns true if an error occurred, and false otherwise. \p
2467/// InstantiatedParamType is the type of the non-type template
2468/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002469///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002470/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002471bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002472 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002473 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002474 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2475
Douglas Gregor86560402009-02-10 23:36:10 +00002476 // If either the parameter has a dependent type or the argument is
2477 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002478 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00002479 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2480 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002481 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002482 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002483 }
Douglas Gregor86560402009-02-10 23:36:10 +00002484
2485 // C++ [temp.arg.nontype]p5:
2486 // The following conversions are performed on each expression used
2487 // as a non-type template-argument. If a non-type
2488 // template-argument cannot be converted to the type of the
2489 // corresponding template-parameter then the program is
2490 // ill-formed.
2491 //
2492 // -- for a non-type template-parameter of integral or
2493 // enumeration type, integral promotions (4.5) and integral
2494 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002495 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002496 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002497 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002498 // C++ [temp.arg.nontype]p1:
2499 // A template-argument for a non-type, non-template
2500 // template-parameter shall be one of:
2501 //
2502 // -- an integral constant-expression of integral or enumeration
2503 // type; or
2504 // -- the name of a non-type template-parameter; or
2505 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002506 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002507 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002508 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002509 diag::err_template_arg_not_integral_or_enumeral)
2510 << ArgType << Arg->getSourceRange();
2511 Diag(Param->getLocation(), diag::note_template_param_here);
2512 return true;
2513 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002514 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002515 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2516 << ArgType << Arg->getSourceRange();
2517 return true;
2518 }
2519
2520 // FIXME: We need some way to more easily get the unqualified form
2521 // of the types without going all the way to the
2522 // canonical type.
2523 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2524 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2525 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2526 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2527
2528 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002529 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002530 // Okay: no conversion necessary
2531 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2532 !ParamType->isEnumeralType()) {
2533 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002534 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002535 } else {
2536 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002537 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002538 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002539 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002540 Diag(Param->getLocation(), diag::note_template_param_here);
2541 return true;
2542 }
2543
Douglas Gregor52aba872009-03-14 00:20:21 +00002544 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002545 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002546 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002547
2548 if (!Arg->isValueDependent()) {
2549 // Check that an unsigned parameter does not receive a negative
2550 // value.
2551 if (IntegerType->isUnsignedIntegerType()
2552 && (Value.isSigned() && Value.isNegative())) {
2553 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2554 << Value.toString(10) << Param->getType()
2555 << Arg->getSourceRange();
2556 Diag(Param->getLocation(), diag::note_template_param_here);
2557 return true;
2558 }
2559
2560 // Check that we don't overflow the template parameter type.
2561 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Eli Friedman38b9ad82009-12-23 18:44:58 +00002562 unsigned RequiredBits;
2563 if (IntegerType->isUnsignedIntegerType())
2564 RequiredBits = Value.getActiveBits();
2565 else if (Value.isUnsigned())
2566 RequiredBits = Value.getActiveBits() + 1;
2567 else
2568 RequiredBits = Value.getMinSignedBits();
2569 if (RequiredBits > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00002570 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00002571 diag::err_template_arg_too_large)
2572 << Value.toString(10) << Param->getType()
2573 << Arg->getSourceRange();
2574 Diag(Param->getLocation(), diag::note_template_param_here);
2575 return true;
2576 }
2577
2578 if (Value.getBitWidth() != AllowedBits)
2579 Value.extOrTrunc(AllowedBits);
2580 Value.setIsSigned(IntegerType->isSignedIntegerType());
2581 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002582
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002583 // Add the value of this argument to the list of converted
2584 // arguments. We use the bitwidth and signedness of the template
2585 // parameter.
2586 if (Arg->isValueDependent()) {
2587 // The argument is value-dependent. Create a new
2588 // TemplateArgument with the converted expression.
2589 Converted = TemplateArgument(Arg);
2590 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002591 }
2592
John McCall0ad16662009-10-29 08:12:44 +00002593 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002594 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002595 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002596 return false;
2597 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002598
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002599 // Handle pointer-to-function, reference-to-function, and
2600 // pointer-to-member-function all in (roughly) the same way.
2601 if (// -- For a non-type template-parameter of type pointer to
2602 // function, only the function-to-pointer conversion (4.3) is
2603 // applied. If the template-argument represents a set of
2604 // overloaded functions (or a pointer to such), the matching
2605 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002606 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002607 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002608 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002609 // -- For a non-type template-parameter of type reference to
2610 // function, no conversions apply. If the template-argument
2611 // represents a set of overloaded functions, the matching
2612 // function is selected from the set (13.4).
2613 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002614 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002615 // -- For a non-type template-parameter of type pointer to
2616 // member function, no conversions apply. If the
2617 // template-argument represents a set of overloaded member
2618 // functions, the matching member function is selected from
2619 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002620 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002621 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002622 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002623 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002624 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002625 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002626 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002627 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2628 ParamType->isMemberPointerType())) {
2629 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002630 if (ParamType->isMemberPointerType())
2631 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2632 else
2633 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002634 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002635 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002636 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002637 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002638 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002639 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2640 return true;
2641
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002642 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002643 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002644 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002645 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002646 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002647 }
2648 }
2649
Mike Stump11289f42009-09-09 15:08:12 +00002650 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002651 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002652 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002653 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002654 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002655 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002656 Diag(Param->getLocation(), diag::note_template_param_here);
2657 return true;
2658 }
Mike Stump11289f42009-09-09 15:08:12 +00002659
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002660 if (ParamType->isMemberPointerType())
2661 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump11289f42009-09-09 15:08:12 +00002662
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002663 NamedDecl *Entity = 0;
2664 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2665 return true;
2666
Chandler Carruth724a8a12010-01-31 10:01:20 +00002667 if (Arg->isValueDependent()) {
2668 Converted = TemplateArgument(Arg);
2669 } else {
2670 if (Entity)
2671 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2672 Converted = TemplateArgument(Entity);
2673 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002674 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002675 }
2676
Chris Lattner696197c2009-02-20 21:37:53 +00002677 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002678 // -- for a non-type template-parameter of type pointer to
2679 // object, qualification conversions (4.4) and the
2680 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002681 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002682 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002683 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002684
Sebastian Redl576fd422009-05-10 18:38:11 +00002685 if (ArgType->isNullPtrType()) {
2686 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002687 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002688 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002689 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002690 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002691 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002692
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002693 if (IsQualificationConversion(ArgType, ParamType)) {
2694 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002695 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002696 }
Mike Stump11289f42009-09-09 15:08:12 +00002697
Douglas Gregor1515f762009-02-11 18:22:40 +00002698 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002699 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002700 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002701 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002702 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002703 Diag(Param->getLocation(), diag::note_template_param_here);
2704 return true;
2705 }
Mike Stump11289f42009-09-09 15:08:12 +00002706
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002707 NamedDecl *Entity = 0;
2708 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2709 return true;
2710
Chandler Carruth724a8a12010-01-31 10:01:20 +00002711 if (Arg->isValueDependent()) {
2712 Converted = TemplateArgument(Arg);
2713 } else {
2714 if (Entity)
2715 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2716 Converted = TemplateArgument(Entity);
2717 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002718 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002719 }
Mike Stump11289f42009-09-09 15:08:12 +00002720
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002721 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002722 // -- For a non-type template-parameter of type reference to
2723 // object, no conversions apply. The type referred to by the
2724 // reference may be more cv-qualified than the (otherwise
2725 // identical) type of the template-argument. The
2726 // template-parameter is bound directly to the
2727 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002728 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002729 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002730
Chandler Carruth7ceffab2010-02-03 09:37:33 +00002731 QualType ReferredType = ParamRefType->getPointeeType();
2732 if (!Context.hasSameUnqualifiedType(ReferredType, ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002733 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002734 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002735 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002736 << Arg->getSourceRange();
2737 Diag(Param->getLocation(), diag::note_template_param_here);
2738 return true;
2739 }
2740
Mike Stump11289f42009-09-09 15:08:12 +00002741 unsigned ParamQuals
Chandler Carruth7ceffab2010-02-03 09:37:33 +00002742 = Context.getCanonicalType(ReferredType).getCVRQualifiers();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002743 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002744
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002745 if ((ParamQuals | ArgQuals) != ParamQuals) {
2746 Diag(Arg->getSourceRange().getBegin(),
2747 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002748 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002749 << Arg->getSourceRange();
2750 Diag(Param->getLocation(), diag::note_template_param_here);
2751 return true;
2752 }
Mike Stump11289f42009-09-09 15:08:12 +00002753
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002754 NamedDecl *Entity = 0;
2755 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2756 return true;
2757
Chandler Carruth724a8a12010-01-31 10:01:20 +00002758 if (Arg->isValueDependent()) {
2759 Converted = TemplateArgument(Arg);
2760 } else {
2761 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2762 Converted = TemplateArgument(Entity);
2763 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002764 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002765 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002766
2767 // -- For a non-type template-parameter of type pointer to data
2768 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002769 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002770 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2771
Douglas Gregor1515f762009-02-11 18:22:40 +00002772 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002773 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002774 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002775 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002776 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002777 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002778 } else {
2779 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002780 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002781 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002782 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002783 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002784 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002785 }
2786
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002787 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002788}
2789
2790/// \brief Check a template argument against its corresponding
2791/// template template parameter.
2792///
2793/// This routine implements the semantics of C++ [temp.arg.template].
2794/// It returns true if an error occurred, and false otherwise.
2795bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002796 const TemplateArgumentLoc &Arg) {
2797 TemplateName Name = Arg.getArgument().getAsTemplate();
2798 TemplateDecl *Template = Name.getAsTemplateDecl();
2799 if (!Template) {
2800 // Any dependent template name is fine.
2801 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2802 return false;
2803 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002804
2805 // C++ [temp.arg.template]p1:
2806 // A template-argument for a template template-parameter shall be
2807 // the name of a class template, expressed as id-expression. Only
2808 // primary class templates are considered when matching the
2809 // template template argument with the corresponding parameter;
2810 // partial specializations are not considered even if their
2811 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002812 //
2813 // Note that we also allow template template parameters here, which
2814 // will happen when we are dealing with, e.g., class template
2815 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002816 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002817 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002818 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002819 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002820 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002821 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002822 << Template;
2823 }
2824
2825 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2826 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002827 true,
2828 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002829 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002830}
2831
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002832/// \brief Determine whether the given template parameter lists are
2833/// equivalent.
2834///
Mike Stump11289f42009-09-09 15:08:12 +00002835/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002836/// source code as part of a new template declaration.
2837///
2838/// \param Old The old template parameter list, typically found via
2839/// name lookup of the template declared with this template parameter
2840/// list.
2841///
2842/// \param Complain If true, this routine will produce a diagnostic if
2843/// the template parameter lists are not equivalent.
2844///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002845/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00002846///
2847/// \param TemplateArgLoc If this source location is valid, then we
2848/// are actually checking the template parameter list of a template
2849/// argument (New) against the template parameter list of its
2850/// corresponding template template parameter (Old). We produce
2851/// slightly different diagnostics in this scenario.
2852///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002853/// \returns True if the template parameter lists are equal, false
2854/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002855bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002856Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2857 TemplateParameterList *Old,
2858 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002859 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002860 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002861 if (Old->size() != New->size()) {
2862 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002863 unsigned NextDiag = diag::err_template_param_list_different_arity;
2864 if (TemplateArgLoc.isValid()) {
2865 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2866 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002867 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002868 Diag(New->getTemplateLoc(), NextDiag)
2869 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002870 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002871 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002872 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002873 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002874 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2875 }
2876
2877 return false;
2878 }
2879
2880 for (TemplateParameterList::iterator OldParm = Old->begin(),
2881 OldParmEnd = Old->end(), NewParm = New->begin();
2882 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2883 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002884 if (Complain) {
2885 unsigned NextDiag = diag::err_template_param_different_kind;
2886 if (TemplateArgLoc.isValid()) {
2887 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2888 NextDiag = diag::note_template_param_different_kind;
2889 }
2890 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002891 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00002892 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002893 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00002894 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002895 return false;
2896 }
2897
2898 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2899 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002900 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00002901 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002902 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2903 // The types of non-type template parameters must agree.
2904 NonTypeTemplateParmDecl *NewNTTP
2905 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002906
2907 // If we are matching a template template argument to a template
2908 // template parameter and one of the non-type template parameter types
2909 // is dependent, then we must wait until template instantiation time
2910 // to actually compare the arguments.
2911 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2912 (OldNTTP->getType()->isDependentType() ||
2913 NewNTTP->getType()->isDependentType()))
2914 continue;
2915
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002916 if (Context.getCanonicalType(OldNTTP->getType()) !=
2917 Context.getCanonicalType(NewNTTP->getType())) {
2918 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002919 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2920 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002921 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002922 diag::err_template_arg_template_params_mismatch);
2923 NextDiag = diag::note_template_nontype_parm_different_type;
2924 }
2925 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002926 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002927 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00002928 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002929 diag::note_template_nontype_parm_prev_declaration)
2930 << OldNTTP->getType();
2931 }
2932 return false;
2933 }
2934 } else {
2935 // The template parameter lists of template template
2936 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00002937 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002938 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002939 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002940 = cast<TemplateTemplateParmDecl>(*OldParm);
2941 TemplateTemplateParmDecl *NewTTP
2942 = cast<TemplateTemplateParmDecl>(*NewParm);
2943 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2944 OldTTP->getTemplateParameters(),
2945 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002946 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00002947 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002948 return false;
2949 }
2950 }
2951
2952 return true;
2953}
2954
2955/// \brief Check whether a template can be declared within this scope.
2956///
2957/// If the template declaration is valid in this scope, returns
2958/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002959bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002960Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002961 // Find the nearest enclosing declaration scope.
2962 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2963 (S->getFlags() & Scope::TemplateParamScope) != 0)
2964 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002965
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002966 // C++ [temp]p2:
2967 // A template-declaration can appear only as a namespace scope or
2968 // class scope declaration.
2969 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002970 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2971 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002972 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002973 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002974
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002975 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002976 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002977
2978 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2979 return false;
2980
Mike Stump11289f42009-09-09 15:08:12 +00002981 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002982 diag::err_template_outside_namespace_or_class_scope)
2983 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002984}
Douglas Gregor67a65642009-02-17 23:15:12 +00002985
Douglas Gregor54888652009-10-07 00:13:32 +00002986/// \brief Determine what kind of template specialization the given declaration
2987/// is.
2988static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2989 if (!D)
2990 return TSK_Undeclared;
2991
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002992 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2993 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00002994 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2995 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002996 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2997 return Var->getTemplateSpecializationKind();
2998
Douglas Gregor54888652009-10-07 00:13:32 +00002999 return TSK_Undeclared;
3000}
3001
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003002/// \brief Check whether a specialization is well-formed in the current
3003/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003004///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003005/// This routine determines whether a template specialization can be declared
3006/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003007///
3008/// \param S the semantic analysis object for which this check is being
3009/// performed.
3010///
3011/// \param Specialized the entity being specialized or instantiated, which
3012/// may be a kind of template (class template, function template, etc.) or
3013/// a member of a class template (member function, static data member,
3014/// member class).
3015///
3016/// \param PrevDecl the previous declaration of this entity, if any.
3017///
3018/// \param Loc the location of the explicit specialization or instantiation of
3019/// this entity.
3020///
3021/// \param IsPartialSpecialization whether this is a partial specialization of
3022/// a class template.
3023///
Douglas Gregor54888652009-10-07 00:13:32 +00003024/// \returns true if there was an error that we cannot recover from, false
3025/// otherwise.
3026static bool CheckTemplateSpecializationScope(Sema &S,
3027 NamedDecl *Specialized,
3028 NamedDecl *PrevDecl,
3029 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003030 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003031 // Keep these "kind" numbers in sync with the %select statements in the
3032 // various diagnostics emitted by this routine.
3033 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003034 bool isTemplateSpecialization = false;
3035 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003036 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003037 isTemplateSpecialization = true;
3038 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003039 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003040 isTemplateSpecialization = true;
3041 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003042 EntityKind = 3;
3043 else if (isa<VarDecl>(Specialized))
3044 EntityKind = 4;
3045 else if (isa<RecordDecl>(Specialized))
3046 EntityKind = 5;
3047 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003048 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3049 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003050 return true;
3051 }
3052
Douglas Gregorf47b9112009-02-25 22:02:03 +00003053 // C++ [temp.expl.spec]p2:
3054 // An explicit specialization shall be declared in the namespace
3055 // of which the template is a member, or, for member templates, in
3056 // the namespace of which the enclosing class or enclosing class
3057 // template is a member. An explicit specialization of a member
3058 // function, member class or static data member of a class
3059 // template shall be declared in the namespace of which the class
3060 // template is a member. Such a declaration may also be a
3061 // definition. If the declaration is not a definition, the
3062 // specialization may be defined later in the name- space in which
3063 // the explicit specialization was declared, or in a namespace
3064 // that encloses the one in which the explicit specialization was
3065 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003066 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3067 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003068 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003069 return true;
3070 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003071
Douglas Gregor40fb7442009-10-07 17:30:37 +00003072 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3073 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003074 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003075 return true;
3076 }
3077
Douglas Gregore4b05162009-10-07 17:21:34 +00003078 // C++ [temp.class.spec]p6:
3079 // A class template partial specialization may be declared or redeclared
3080 // in any namespace scope in which its definition may be defined (14.5.1
3081 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003082 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003083 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003084 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003085 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003086 if ((!PrevDecl ||
3087 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3088 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3089 // There is no prior declaration of this entity, so this
3090 // specialization must be in the same context as the template
3091 // itself.
3092 if (!DC->Equals(SpecializedContext)) {
3093 if (isa<TranslationUnitDecl>(SpecializedContext))
3094 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3095 << EntityKind << Specialized;
3096 else if (isa<NamespaceDecl>(SpecializedContext))
3097 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3098 << EntityKind << Specialized
3099 << cast<NamedDecl>(SpecializedContext);
3100
3101 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3102 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003103 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003104 }
Douglas Gregor54888652009-10-07 00:13:32 +00003105
3106 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003107 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003108 // Note that HandleDeclarator() performs this check for explicit
3109 // specializations of function templates, static data members, and member
3110 // functions, so we skip the check here for those kinds of entities.
3111 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003112 // Should we refactor that check, so that it occurs later?
3113 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003114 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3115 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003116 if (isa<TranslationUnitDecl>(SpecializedContext))
3117 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3118 << EntityKind << Specialized;
3119 else if (isa<NamespaceDecl>(SpecializedContext))
3120 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3121 << EntityKind << Specialized
3122 << cast<NamedDecl>(SpecializedContext);
3123
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003124 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003125 }
Douglas Gregor54888652009-10-07 00:13:32 +00003126
3127 // FIXME: check for specialization-after-instantiation errors and such.
3128
Douglas Gregorf47b9112009-02-25 22:02:03 +00003129 return false;
3130}
Douglas Gregor54888652009-10-07 00:13:32 +00003131
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003132/// \brief Check the non-type template arguments of a class template
3133/// partial specialization according to C++ [temp.class.spec]p9.
3134///
Douglas Gregor09a30232009-06-12 22:08:06 +00003135/// \param TemplateParams the template parameters of the primary class
3136/// template.
3137///
3138/// \param TemplateArg the template arguments of the class template
3139/// partial specialization.
3140///
3141/// \param MirrorsPrimaryTemplate will be set true if the class
3142/// template partial specialization arguments are identical to the
3143/// implicit template arguments of the primary template. This is not
3144/// necessarily an error (C++0x), and it is left to the caller to diagnose
3145/// this condition when it is an error.
3146///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003147/// \returns true if there was an error, false otherwise.
3148bool Sema::CheckClassTemplatePartialSpecializationArgs(
3149 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003150 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003151 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003152 // FIXME: the interface to this function will have to change to
3153 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003154 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003155
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003156 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003157
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003158 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003159 // Determine whether the template argument list of the partial
3160 // specialization is identical to the implicit argument list of
3161 // the primary template. The caller may need to diagnostic this as
3162 // an error per C++ [temp.class.spec]p9b3.
3163 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003164 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003165 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3166 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003167 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003168 MirrorsPrimaryTemplate = false;
3169 } else if (TemplateTemplateParmDecl *TTP
3170 = dyn_cast<TemplateTemplateParmDecl>(
3171 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003172 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003173 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003174 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003175 if (!ArgDecl ||
3176 ArgDecl->getIndex() != TTP->getIndex() ||
3177 ArgDecl->getDepth() != TTP->getDepth())
3178 MirrorsPrimaryTemplate = false;
3179 }
3180 }
3181
Mike Stump11289f42009-09-09 15:08:12 +00003182 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003183 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003184 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003185 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003186 }
3187
Anders Carlsson40c1d492009-06-13 18:20:51 +00003188 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003189 if (!ArgExpr) {
3190 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003191 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003192 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003193
3194 // C++ [temp.class.spec]p8:
3195 // A non-type argument is non-specialized if it is the name of a
3196 // non-type parameter. All other non-type arguments are
3197 // specialized.
3198 //
3199 // Below, we check the two conditions that only apply to
3200 // specialized non-type arguments, so skip any non-specialized
3201 // arguments.
3202 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003203 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003204 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003205 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003206 (Param->getIndex() != NTTP->getIndex() ||
3207 Param->getDepth() != NTTP->getDepth()))
3208 MirrorsPrimaryTemplate = false;
3209
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003210 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003211 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003212
3213 // C++ [temp.class.spec]p9:
3214 // Within the argument list of a class template partial
3215 // specialization, the following restrictions apply:
3216 // -- A partially specialized non-type argument expression
3217 // shall not involve a template parameter of the partial
3218 // specialization except when the argument expression is a
3219 // simple identifier.
3220 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003221 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003222 diag::err_dependent_non_type_arg_in_partial_spec)
3223 << ArgExpr->getSourceRange();
3224 return true;
3225 }
3226
3227 // -- The type of a template parameter corresponding to a
3228 // specialized non-type argument shall not be dependent on a
3229 // parameter of the specialization.
3230 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003231 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003232 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3233 << Param->getType()
3234 << ArgExpr->getSourceRange();
3235 Diag(Param->getLocation(), diag::note_template_param_here);
3236 return true;
3237 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003238
3239 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003240 }
3241
3242 return false;
3243}
3244
Douglas Gregorc854c662010-02-26 06:03:23 +00003245/// \brief Retrieve the previous declaration of the given declaration.
3246static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3247 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3248 return VD->getPreviousDeclaration();
3249 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3250 return FD->getPreviousDeclaration();
3251 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3252 return TD->getPreviousDeclaration();
3253 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3254 return TD->getPreviousDeclaration();
3255 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3256 return FTD->getPreviousDeclaration();
3257 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3258 return CTD->getPreviousDeclaration();
3259 return 0;
3260}
3261
Douglas Gregorc08f4892009-03-25 00:13:59 +00003262Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003263Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3264 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003265 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00003266 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003267 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003268 SourceLocation TemplateNameLoc,
3269 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003270 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003271 SourceLocation RAngleLoc,
3272 AttributeList *Attr,
3273 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003274 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003275
Douglas Gregor67a65642009-02-17 23:15:12 +00003276 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003277 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003278 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003279 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3280
3281 if (!ClassTemplate) {
3282 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3283 << (Name.getAsTemplateDecl() &&
3284 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3285 return true;
3286 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003287
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003288 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003289 bool isPartialSpecialization = false;
3290
Douglas Gregorf47b9112009-02-25 22:02:03 +00003291 // Check the validity of the template headers that introduce this
3292 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003293 // FIXME: We probably shouldn't complain about these headers for
3294 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003295 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003296 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3297 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003298 TemplateParameterLists.size(),
3299 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003300 if (TemplateParams && TemplateParams->size() > 0) {
3301 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003302
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003303 // C++ [temp.class.spec]p10:
3304 // The template parameter list of a specialization shall not
3305 // contain default template argument values.
3306 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3307 Decl *Param = TemplateParams->getParam(I);
3308 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3309 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003310 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003311 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003312 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003313 }
3314 } else if (NonTypeTemplateParmDecl *NTTP
3315 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3316 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003317 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003318 diag::err_default_arg_in_partial_spec)
3319 << DefArg->getSourceRange();
3320 NTTP->setDefaultArgument(0);
3321 DefArg->Destroy(Context);
3322 }
3323 } else {
3324 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003325 if (TTP->hasDefaultArgument()) {
3326 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003327 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003328 << TTP->getDefaultArgument().getSourceRange();
3329 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003330 }
3331 }
3332 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003333 } else if (TemplateParams) {
3334 if (TUK == TUK_Friend)
3335 Diag(KWLoc, diag::err_template_spec_friend)
3336 << CodeModificationHint::CreateRemoval(
3337 SourceRange(TemplateParams->getTemplateLoc(),
3338 TemplateParams->getRAngleLoc()))
3339 << SourceRange(LAngleLoc, RAngleLoc);
3340 else
3341 isExplicitSpecialization = true;
3342 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003343 Diag(KWLoc, diag::err_template_spec_needs_header)
3344 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003345 isExplicitSpecialization = true;
3346 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003347
Douglas Gregor67a65642009-02-17 23:15:12 +00003348 // Check that the specialization uses the same tag kind as the
3349 // original template.
3350 TagDecl::TagKind Kind;
3351 switch (TagSpec) {
3352 default: assert(0 && "Unknown tag type!");
3353 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3354 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3355 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3356 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003357 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003358 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003359 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003360 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003361 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003362 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003363 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003364 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003365 diag::note_previous_use);
3366 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3367 }
3368
Douglas Gregorc40290e2009-03-09 23:48:35 +00003369 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003370 TemplateArgumentListInfo TemplateArgs;
3371 TemplateArgs.setLAngleLoc(LAngleLoc);
3372 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003373 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003374
Douglas Gregor67a65642009-02-17 23:15:12 +00003375 // Check that the template argument list is well-formed for this
3376 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003377 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3378 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003379 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3380 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003381 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003382
Mike Stump11289f42009-09-09 15:08:12 +00003383 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003384 ClassTemplate->getTemplateParameters()->size()) &&
3385 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003386
Douglas Gregor2373c592009-05-31 09:31:02 +00003387 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003388 // corresponds to these arguments.
3389 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003390 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003391 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003392 if (CheckClassTemplatePartialSpecializationArgs(
3393 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003394 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003395 return true;
3396
Douglas Gregor09a30232009-06-12 22:08:06 +00003397 if (MirrorsPrimaryTemplate) {
3398 // C++ [temp.class.spec]p9b3:
3399 //
Mike Stump11289f42009-09-09 15:08:12 +00003400 // -- The argument list of the specialization shall not be identical
3401 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003402 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003403 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00003404 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00003405 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003406 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003407 ClassTemplate->getIdentifier(),
3408 TemplateNameLoc,
3409 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003410 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003411 AS_none);
3412 }
3413
Douglas Gregor2208a292009-09-26 20:57:03 +00003414 // FIXME: Diagnose friend partial specializations
3415
Douglas Gregor92354b62010-02-09 00:37:32 +00003416 if (!Name.isDependent() &&
3417 !TemplateSpecializationType::anyDependentTemplateArguments(
3418 TemplateArgs.getArgumentArray(),
3419 TemplateArgs.size())) {
3420 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3421 << ClassTemplate->getDeclName();
3422 isPartialSpecialization = false;
3423 } else {
3424 // FIXME: Template parameter list matters, too
3425 ClassTemplatePartialSpecializationDecl::Profile(ID,
3426 Converted.getFlatArguments(),
3427 Converted.flatSize(),
3428 Context);
3429 }
3430 }
3431
3432 if (!isPartialSpecialization)
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003433 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003434 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003435 Converted.flatSize(),
3436 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003437 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003438 ClassTemplateSpecializationDecl *PrevDecl = 0;
3439
3440 if (isPartialSpecialization)
3441 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003442 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003443 InsertPos);
3444 else
3445 PrevDecl
3446 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003447
3448 ClassTemplateSpecializationDecl *Specialization = 0;
3449
Douglas Gregorf47b9112009-02-25 22:02:03 +00003450 // Check whether we can declare a class template specialization in
3451 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003452 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003453 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003454 TemplateNameLoc,
3455 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003456 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003457
Douglas Gregor15301382009-07-30 17:40:51 +00003458 // The canonical type
3459 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003460 if (PrevDecl &&
3461 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003462 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003463 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003464 // arguments was referenced but not declared, or we're only
3465 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003466 // declaration node as our own, updating its source location to
3467 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003468 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003469 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003470 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003471 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003472 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003473 // Build the canonical type that describes the converted template
3474 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003475 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3476 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003477 Converted.getFlatArguments(),
3478 Converted.flatSize());
3479
Douglas Gregor2373c592009-05-31 09:31:02 +00003480 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003481 ClassTemplatePartialSpecializationDecl *PrevPartial
3482 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003483 ClassTemplatePartialSpecializationDecl *Partial
3484 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003485 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003486 TemplateNameLoc,
3487 TemplateParams,
3488 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003489 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003490 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003491 CanonType,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003492 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00003493
3494 if (PrevPartial) {
3495 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3496 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3497 } else {
3498 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3499 }
3500 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003501
Douglas Gregor21610382009-10-29 00:04:11 +00003502 // If we are providing an explicit specialization of a member class
3503 // template specialization, make a note of that.
3504 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3505 PrevPartial->setMemberSpecialization();
3506
Douglas Gregor91772d12009-06-13 00:26:55 +00003507 // Check that all of the template parameters of the class template
3508 // partial specialization are deducible from the template
3509 // arguments. If not, this class template partial specialization
3510 // will never be used.
3511 llvm::SmallVector<bool, 8> DeducibleParams;
3512 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003513 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003514 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003515 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003516 unsigned NumNonDeducible = 0;
3517 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3518 if (!DeducibleParams[I])
3519 ++NumNonDeducible;
3520
3521 if (NumNonDeducible) {
3522 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3523 << (NumNonDeducible > 1)
3524 << SourceRange(TemplateNameLoc, RAngleLoc);
3525 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3526 if (!DeducibleParams[I]) {
3527 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3528 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003529 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003530 diag::note_partial_spec_unused_parameter)
3531 << Param->getDeclName();
3532 else
Mike Stump11289f42009-09-09 15:08:12 +00003533 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003534 diag::note_partial_spec_unused_parameter)
3535 << std::string("<anonymous>");
3536 }
3537 }
3538 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003539 } else {
3540 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003541 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003542 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003543 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003544 ClassTemplate->getDeclContext(),
3545 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003546 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003547 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003548 PrevDecl);
3549
3550 if (PrevDecl) {
3551 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3552 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3553 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003554 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003555 InsertPos);
3556 }
Douglas Gregor15301382009-07-30 17:40:51 +00003557
3558 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003559 }
3560
Douglas Gregor06db9f52009-10-12 20:18:28 +00003561 // C++ [temp.expl.spec]p6:
3562 // If a template, a member template or the member of a class template is
3563 // explicitly specialized then that specialization shall be declared
3564 // before the first use of that specialization that would cause an implicit
3565 // instantiation to take place, in every translation unit in which such a
3566 // use occurs; no diagnostic is required.
3567 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003568 bool Okay = false;
3569 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3570 // Is there any previous explicit specialization declaration?
3571 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3572 Okay = true;
3573 break;
3574 }
3575 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003576
Douglas Gregorc854c662010-02-26 06:03:23 +00003577 if (!Okay) {
3578 SourceRange Range(TemplateNameLoc, RAngleLoc);
3579 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3580 << Context.getTypeDeclType(Specialization) << Range;
3581
3582 Diag(PrevDecl->getPointOfInstantiation(),
3583 diag::note_instantiation_required_here)
3584 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003585 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003586 return true;
3587 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003588 }
3589
Douglas Gregor2208a292009-09-26 20:57:03 +00003590 // If this is not a friend, note that this is an explicit specialization.
3591 if (TUK != TUK_Friend)
3592 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003593
3594 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003595 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003596 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003597 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003598 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003599 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003600 Diag(Def->getLocation(), diag::note_previous_definition);
3601 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003602 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003603 }
3604 }
3605
Douglas Gregord56a91e2009-02-26 22:19:44 +00003606 // Build the fully-sugared type for this class template
3607 // specialization as the user wrote in the specialization
3608 // itself. This means that we'll pretty-print the type retrieved
3609 // from the specialization's declaration the way that the user
3610 // actually wrote the specialization, rather than formatting the
3611 // name based on the "canonical" representation used to store the
3612 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003613 TypeSourceInfo *WrittenTy
3614 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3615 TemplateArgs, CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003616 if (TUK != TUK_Friend)
3617 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003618 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003619
Douglas Gregor1e249f82009-02-25 22:18:32 +00003620 // C++ [temp.expl.spec]p9:
3621 // A template explicit specialization is in the scope of the
3622 // namespace in which the template was defined.
3623 //
3624 // We actually implement this paragraph where we set the semantic
3625 // context (in the creation of the ClassTemplateSpecializationDecl),
3626 // but we also maintain the lexical context where the actual
3627 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003628 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003629
Douglas Gregor67a65642009-02-17 23:15:12 +00003630 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003631 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003632 Specialization->startDefinition();
3633
Douglas Gregor2208a292009-09-26 20:57:03 +00003634 if (TUK == TUK_Friend) {
3635 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3636 TemplateNameLoc,
John McCalle78aac42010-03-10 03:28:59 +00003637 WrittenTy->getType().getTypePtr(),
Douglas Gregor2208a292009-09-26 20:57:03 +00003638 /*FIXME:*/KWLoc);
3639 Friend->setAccess(AS_public);
3640 CurContext->addDecl(Friend);
3641 } else {
3642 // Add the specialization into its lexical context, so that it can
3643 // be seen when iterating through the list of declarations in that
3644 // context. However, specializations are not found by name lookup.
3645 CurContext->addDecl(Specialization);
3646 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003647 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003648}
Douglas Gregor333489b2009-03-27 23:10:48 +00003649
Mike Stump11289f42009-09-09 15:08:12 +00003650Sema::DeclPtrTy
3651Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003652 MultiTemplateParamsArg TemplateParameterLists,
3653 Declarator &D) {
3654 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3655}
3656
Mike Stump11289f42009-09-09 15:08:12 +00003657Sema::DeclPtrTy
3658Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003659 MultiTemplateParamsArg TemplateParameterLists,
3660 Declarator &D) {
3661 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3662 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3663 "Not a function declarator!");
3664 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003665
Douglas Gregor17a7c122009-06-24 00:54:41 +00003666 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003667 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003668 }
Mike Stump11289f42009-09-09 15:08:12 +00003669
Douglas Gregor17a7c122009-06-24 00:54:41 +00003670 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003671
3672 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003673 move(TemplateParameterLists),
3674 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003675 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003676 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003677 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003678 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003679 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3680 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003681 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003682}
3683
John McCall4f7ced62010-02-11 01:33:53 +00003684/// \brief Strips various properties off an implicit instantiation
3685/// that has just been explicitly specialized.
3686static void StripImplicitInstantiation(NamedDecl *D) {
3687 D->invalidateAttrs();
3688
3689 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3690 FD->setInlineSpecified(false);
3691 }
3692}
3693
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003694/// \brief Diagnose cases where we have an explicit template specialization
3695/// before/after an explicit template instantiation, producing diagnostics
3696/// for those cases where they are required and determining whether the
3697/// new specialization/instantiation will have any effect.
3698///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003699/// \param NewLoc the location of the new explicit specialization or
3700/// instantiation.
3701///
3702/// \param NewTSK the kind of the new explicit specialization or instantiation.
3703///
3704/// \param PrevDecl the previous declaration of the entity.
3705///
3706/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3707///
3708/// \param PrevPointOfInstantiation if valid, indicates where the previus
3709/// declaration was instantiated (either implicitly or explicitly).
3710///
3711/// \param SuppressNew will be set to true to indicate that the new
3712/// specialization or instantiation has no effect and should be ignored.
3713///
3714/// \returns true if there was an error that should prevent the introduction of
3715/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003716bool
3717Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3718 TemplateSpecializationKind NewTSK,
3719 NamedDecl *PrevDecl,
3720 TemplateSpecializationKind PrevTSK,
3721 SourceLocation PrevPointOfInstantiation,
3722 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003723 SuppressNew = false;
3724
3725 switch (NewTSK) {
3726 case TSK_Undeclared:
3727 case TSK_ImplicitInstantiation:
3728 assert(false && "Don't check implicit instantiations here");
3729 return false;
3730
3731 case TSK_ExplicitSpecialization:
3732 switch (PrevTSK) {
3733 case TSK_Undeclared:
3734 case TSK_ExplicitSpecialization:
3735 // Okay, we're just specializing something that is either already
3736 // explicitly specialized or has merely been mentioned without any
3737 // instantiation.
3738 return false;
3739
3740 case TSK_ImplicitInstantiation:
3741 if (PrevPointOfInstantiation.isInvalid()) {
3742 // The declaration itself has not actually been instantiated, so it is
3743 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00003744 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003745 return false;
3746 }
3747 // Fall through
3748
3749 case TSK_ExplicitInstantiationDeclaration:
3750 case TSK_ExplicitInstantiationDefinition:
3751 assert((PrevTSK == TSK_ImplicitInstantiation ||
3752 PrevPointOfInstantiation.isValid()) &&
3753 "Explicit instantiation without point of instantiation?");
3754
3755 // C++ [temp.expl.spec]p6:
3756 // If a template, a member template or the member of a class template
3757 // is explicitly specialized then that specialization shall be declared
3758 // before the first use of that specialization that would cause an
3759 // implicit instantiation to take place, in every translation unit in
3760 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00003761 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3762 // Is there any previous explicit specialization declaration?
3763 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
3764 return false;
3765 }
3766
Douglas Gregor1d957a32009-10-27 18:42:08 +00003767 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003768 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003769 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003770 << (PrevTSK != TSK_ImplicitInstantiation);
3771
3772 return true;
3773 }
3774 break;
3775
3776 case TSK_ExplicitInstantiationDeclaration:
3777 switch (PrevTSK) {
3778 case TSK_ExplicitInstantiationDeclaration:
3779 // This explicit instantiation declaration is redundant (that's okay).
3780 SuppressNew = true;
3781 return false;
3782
3783 case TSK_Undeclared:
3784 case TSK_ImplicitInstantiation:
3785 // We're explicitly instantiating something that may have already been
3786 // implicitly instantiated; that's fine.
3787 return false;
3788
3789 case TSK_ExplicitSpecialization:
3790 // C++0x [temp.explicit]p4:
3791 // For a given set of template parameters, if an explicit instantiation
3792 // of a template appears after a declaration of an explicit
3793 // specialization for that template, the explicit instantiation has no
3794 // effect.
John McCall6b21eb52010-03-02 23:09:38 +00003795 SuppressNew = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003796 return false;
3797
3798 case TSK_ExplicitInstantiationDefinition:
3799 // C++0x [temp.explicit]p10:
3800 // If an entity is the subject of both an explicit instantiation
3801 // declaration and an explicit instantiation definition in the same
3802 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003803 Diag(NewLoc,
3804 diag::err_explicit_instantiation_declaration_after_definition);
3805 Diag(PrevPointOfInstantiation,
3806 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003807 assert(PrevPointOfInstantiation.isValid() &&
3808 "Explicit instantiation without point of instantiation?");
3809 SuppressNew = true;
3810 return false;
3811 }
3812 break;
3813
3814 case TSK_ExplicitInstantiationDefinition:
3815 switch (PrevTSK) {
3816 case TSK_Undeclared:
3817 case TSK_ImplicitInstantiation:
3818 // We're explicitly instantiating something that may have already been
3819 // implicitly instantiated; that's fine.
3820 return false;
3821
3822 case TSK_ExplicitSpecialization:
3823 // C++ DR 259, C++0x [temp.explicit]p4:
3824 // For a given set of template parameters, if an explicit
3825 // instantiation of a template appears after a declaration of
3826 // an explicit specialization for that template, the explicit
3827 // instantiation has no effect.
3828 //
3829 // In C++98/03 mode, we only give an extension warning here, because it
3830 // is not not harmful to try to explicitly instantiate something that
3831 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003832 if (!getLangOptions().CPlusPlus0x) {
3833 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003834 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003835 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003836 diag::note_previous_template_specialization);
3837 }
3838 SuppressNew = true;
3839 return false;
3840
3841 case TSK_ExplicitInstantiationDeclaration:
3842 // We're explicity instantiating a definition for something for which we
3843 // were previously asked to suppress instantiations. That's fine.
3844 return false;
3845
3846 case TSK_ExplicitInstantiationDefinition:
3847 // C++0x [temp.spec]p5:
3848 // For a given template and a given set of template-arguments,
3849 // - an explicit instantiation definition shall appear at most once
3850 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003851 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003852 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003853 Diag(PrevPointOfInstantiation,
3854 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003855 SuppressNew = true;
3856 return false;
3857 }
3858 break;
3859 }
3860
3861 assert(false && "Missing specialization/instantiation case?");
3862
3863 return false;
3864}
3865
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003866/// \brief Perform semantic analysis for the given function template
3867/// specialization.
3868///
3869/// This routine performs all of the semantic analysis required for an
3870/// explicit function template specialization. On successful completion,
3871/// the function declaration \p FD will become a function template
3872/// specialization.
3873///
3874/// \param FD the function declaration, which will be updated to become a
3875/// function template specialization.
3876///
3877/// \param HasExplicitTemplateArgs whether any template arguments were
3878/// explicitly provided.
3879///
3880/// \param LAngleLoc the location of the left angle bracket ('<'), if
3881/// template arguments were explicitly provided.
3882///
3883/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3884/// if any.
3885///
3886/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3887/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3888/// true as in, e.g., \c void sort<>(char*, char*);
3889///
3890/// \param RAngleLoc the location of the right angle bracket ('>'), if
3891/// template arguments were explicitly provided.
3892///
3893/// \param PrevDecl the set of declarations that
3894bool
3895Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00003896 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00003897 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003898 // The set of function template specializations that could match this
3899 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00003900 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003901
3902 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00003903 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3904 I != E; ++I) {
3905 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3906 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003907 // Only consider templates found within the same semantic lookup scope as
3908 // FD.
3909 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3910 continue;
3911
3912 // C++ [temp.expl.spec]p11:
3913 // A trailing template-argument can be left unspecified in the
3914 // template-id naming an explicit function template specialization
3915 // provided it can be deduced from the function argument type.
3916 // Perform template argument deduction to determine whether we may be
3917 // specializing this template.
3918 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00003919 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003920 FunctionDecl *Specialization = 0;
3921 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00003922 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003923 FD->getType(),
3924 Specialization,
3925 Info)) {
3926 // FIXME: Template argument deduction failed; record why it failed, so
3927 // that we can provide nifty diagnostics.
3928 (void)TDK;
3929 continue;
3930 }
3931
3932 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00003933 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003934 }
3935 }
3936
Douglas Gregor5de279c2009-09-26 03:41:46 +00003937 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00003938 UnresolvedSetIterator Result
3939 = getMostSpecialized(Candidates.begin(), Candidates.end(),
3940 TPOC_Other, FD->getLocation(),
Douglas Gregor5de279c2009-09-26 03:41:46 +00003941 PartialDiagnostic(diag::err_function_template_spec_no_match)
3942 << FD->getDeclName(),
3943 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00003944 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor5de279c2009-09-26 03:41:46 +00003945 PartialDiagnostic(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00003946 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003947 return true;
John McCall58cc69d2010-01-27 01:50:18 +00003948
3949 // Ignore access information; it doesn't figure into redeclaration checking.
3950 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003951
3952 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003953 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003954
Douglas Gregor54888652009-10-07 00:13:32 +00003955 // Check the scope of this explicit specialization.
3956 if (CheckTemplateSpecializationScope(*this,
3957 Specialization->getPrimaryTemplate(),
3958 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003959 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003960 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003961
3962 // C++ [temp.expl.spec]p6:
3963 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003964 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003965 // before the first use of that specialization that would cause an implicit
3966 // instantiation to take place, in every translation unit in which such a
3967 // use occurs; no diagnostic is required.
3968 FunctionTemplateSpecializationInfo *SpecInfo
3969 = Specialization->getTemplateSpecializationInfo();
3970 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00003971
3972 bool SuppressNew = false;
3973 if (CheckSpecializationInstantiationRedecl(FD->getLocation(),
3974 TSK_ExplicitSpecialization,
3975 Specialization,
3976 SpecInfo->getTemplateSpecializationKind(),
3977 SpecInfo->getPointOfInstantiation(),
3978 SuppressNew))
Douglas Gregor06db9f52009-10-12 20:18:28 +00003979 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00003980
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003981 // Mark the prior declaration as an explicit specialization, so that later
3982 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003983 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003984
3985 // Turn the given function declaration into a function template
3986 // specialization, with the template arguments from the previous
3987 // specialization.
Douglas Gregord5058122010-02-11 01:19:42 +00003988 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003989 new (Context) TemplateArgumentList(
3990 *Specialization->getTemplateSpecializationArgs()),
3991 /*InsertPos=*/0,
3992 TSK_ExplicitSpecialization);
3993
3994 // The "previous declaration" for this function template specialization is
3995 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00003996 Previous.clear();
3997 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003998 return false;
3999}
4000
Douglas Gregor86d142a2009-10-08 07:24:58 +00004001/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004002/// specialization.
4003///
4004/// This routine performs all of the semantic analysis required for an
4005/// explicit member function specialization. On successful completion,
4006/// the function declaration \p FD will become a member function
4007/// specialization.
4008///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004009/// \param Member the member declaration, which will be updated to become a
4010/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004011///
John McCall1f82f242009-11-18 22:49:29 +00004012/// \param Previous the set of declarations, one of which may be specialized
4013/// by this function specialization; the set will be modified to contain the
4014/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004015bool
John McCall1f82f242009-11-18 22:49:29 +00004016Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004017 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
4018
4019 // Try to find the member we are instantiating.
4020 NamedDecl *Instantiation = 0;
4021 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004022 MemberSpecializationInfo *MSInfo = 0;
4023
John McCall1f82f242009-11-18 22:49:29 +00004024 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004025 // Nowhere to look anyway.
4026 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004027 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4028 I != E; ++I) {
4029 NamedDecl *D = (*I)->getUnderlyingDecl();
4030 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004031 if (Context.hasSameType(Function->getType(), Method->getType())) {
4032 Instantiation = Method;
4033 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004034 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004035 break;
4036 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004037 }
4038 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004039 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004040 VarDecl *PrevVar;
4041 if (Previous.isSingleResult() &&
4042 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004043 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004044 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004045 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004046 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004047 }
4048 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004049 CXXRecordDecl *PrevRecord;
4050 if (Previous.isSingleResult() &&
4051 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4052 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004053 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004054 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004055 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004056 }
4057
4058 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004059 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004060 // specializations are always out-of-line, the caller will complain about
4061 // this mismatch later.
4062 return false;
4063 }
4064
Douglas Gregor86d142a2009-10-08 07:24:58 +00004065 // Make sure that this is a specialization of a member.
4066 if (!InstantiatedFrom) {
4067 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4068 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004069 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4070 return true;
4071 }
4072
Douglas Gregor06db9f52009-10-12 20:18:28 +00004073 // C++ [temp.expl.spec]p6:
4074 // If a template, a member template or the member of a class template is
4075 // explicitly specialized then that spe- cialization shall be declared
4076 // before the first use of that specialization that would cause an implicit
4077 // instantiation to take place, in every translation unit in which such a
4078 // use occurs; no diagnostic is required.
4079 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004080
4081 bool SuppressNew = false;
4082 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4083 TSK_ExplicitSpecialization,
4084 Instantiation,
4085 MSInfo->getTemplateSpecializationKind(),
4086 MSInfo->getPointOfInstantiation(),
4087 SuppressNew))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004088 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004089
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004090 // Check the scope of this explicit specialization.
4091 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004092 InstantiatedFrom,
4093 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004094 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004095 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004096
Douglas Gregor86d142a2009-10-08 07:24:58 +00004097 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004098 // the original declaration to note that it is an explicit specialization
4099 // (if it was previously an implicit instantiation). This latter step
4100 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004101 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004102 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4103 if (InstantiationFunction->getTemplateSpecializationKind() ==
4104 TSK_ImplicitInstantiation) {
4105 InstantiationFunction->setTemplateSpecializationKind(
4106 TSK_ExplicitSpecialization);
4107 InstantiationFunction->setLocation(Member->getLocation());
4108 }
4109
Douglas Gregor86d142a2009-10-08 07:24:58 +00004110 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4111 cast<CXXMethodDecl>(InstantiatedFrom),
4112 TSK_ExplicitSpecialization);
4113 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004114 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4115 if (InstantiationVar->getTemplateSpecializationKind() ==
4116 TSK_ImplicitInstantiation) {
4117 InstantiationVar->setTemplateSpecializationKind(
4118 TSK_ExplicitSpecialization);
4119 InstantiationVar->setLocation(Member->getLocation());
4120 }
4121
Douglas Gregor86d142a2009-10-08 07:24:58 +00004122 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4123 cast<VarDecl>(InstantiatedFrom),
4124 TSK_ExplicitSpecialization);
4125 } else {
4126 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004127 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4128 if (InstantiationClass->getTemplateSpecializationKind() ==
4129 TSK_ImplicitInstantiation) {
4130 InstantiationClass->setTemplateSpecializationKind(
4131 TSK_ExplicitSpecialization);
4132 InstantiationClass->setLocation(Member->getLocation());
4133 }
4134
Douglas Gregor86d142a2009-10-08 07:24:58 +00004135 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004136 cast<CXXRecordDecl>(InstantiatedFrom),
4137 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004138 }
4139
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004140 // Save the caller the trouble of having to figure out which declaration
4141 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004142 Previous.clear();
4143 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004144 return false;
4145}
4146
Douglas Gregore47f5a72009-10-14 23:41:34 +00004147/// \brief Check the scope of an explicit instantiation.
4148static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4149 SourceLocation InstLoc,
4150 bool WasQualifiedName) {
4151 DeclContext *ExpectedContext
4152 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4153 DeclContext *CurContext = S.CurContext->getLookupContext();
4154
4155 // C++0x [temp.explicit]p2:
4156 // An explicit instantiation shall appear in an enclosing namespace of its
4157 // template.
4158 //
4159 // This is DR275, which we do not retroactively apply to C++98/03.
4160 if (S.getLangOptions().CPlusPlus0x &&
4161 !CurContext->Encloses(ExpectedContext)) {
4162 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4163 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4164 << D << NS;
4165 else
4166 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4167 << D;
4168 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4169 return;
4170 }
4171
4172 // C++0x [temp.explicit]p2:
4173 // If the name declared in the explicit instantiation is an unqualified
4174 // name, the explicit instantiation shall appear in the namespace where
4175 // its template is declared or, if that namespace is inline (7.3.1), any
4176 // namespace from its enclosing namespace set.
4177 if (WasQualifiedName)
4178 return;
4179
4180 if (CurContext->Equals(ExpectedContext))
4181 return;
4182
4183 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4184 << D << ExpectedContext;
4185 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4186}
4187
4188/// \brief Determine whether the given scope specifier has a template-id in it.
4189static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4190 if (!SS.isSet())
4191 return false;
4192
4193 // C++0x [temp.explicit]p2:
4194 // If the explicit instantiation is for a member function, a member class
4195 // or a static data member of a class template specialization, the name of
4196 // the class template specialization in the qualified-id for the member
4197 // name shall be a simple-template-id.
4198 //
4199 // C++98 has the same restriction, just worded differently.
4200 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4201 NNS; NNS = NNS->getPrefix())
4202 if (Type *T = NNS->getAsType())
4203 if (isa<TemplateSpecializationType>(T))
4204 return true;
4205
4206 return false;
4207}
4208
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004209// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00004210// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00004211Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004212Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004213 SourceLocation ExternLoc,
4214 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004215 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004216 SourceLocation KWLoc,
4217 const CXXScopeSpec &SS,
4218 TemplateTy TemplateD,
4219 SourceLocation TemplateNameLoc,
4220 SourceLocation LAngleLoc,
4221 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004222 SourceLocation RAngleLoc,
4223 AttributeList *Attr) {
4224 // Find the class template we're specializing
4225 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004226 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004227 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4228
4229 // Check that the specialization uses the same tag kind as the
4230 // original template.
4231 TagDecl::TagKind Kind;
4232 switch (TagSpec) {
4233 default: assert(0 && "Unknown tag type!");
4234 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4235 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4236 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4237 }
Douglas Gregord9034f02009-05-14 16:41:31 +00004238 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004239 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004240 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004241 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004242 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00004243 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004244 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004245 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004246 diag::note_previous_use);
4247 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4248 }
4249
Douglas Gregore47f5a72009-10-14 23:41:34 +00004250 // C++0x [temp.explicit]p2:
4251 // There are two forms of explicit instantiation: an explicit instantiation
4252 // definition and an explicit instantiation declaration. An explicit
4253 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004254 TemplateSpecializationKind TSK
4255 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4256 : TSK_ExplicitInstantiationDeclaration;
4257
Douglas Gregora1f49972009-05-13 00:25:59 +00004258 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004259 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004260 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004261
4262 // Check that the template argument list is well-formed for this
4263 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004264 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4265 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004266 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4267 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004268 return true;
4269
Mike Stump11289f42009-09-09 15:08:12 +00004270 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004271 ClassTemplate->getTemplateParameters()->size()) &&
4272 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004273
Douglas Gregora1f49972009-05-13 00:25:59 +00004274 // Find the class template specialization declaration that
4275 // corresponds to these arguments.
4276 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004277 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004278 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004279 Converted.flatSize(),
4280 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004281 void *InsertPos = 0;
4282 ClassTemplateSpecializationDecl *PrevDecl
4283 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4284
Douglas Gregor54888652009-10-07 00:13:32 +00004285 // C++0x [temp.explicit]p2:
4286 // [...] An explicit instantiation shall appear in an enclosing
4287 // namespace of its template. [...]
4288 //
4289 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004290 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4291 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004292
Douglas Gregora1f49972009-05-13 00:25:59 +00004293 ClassTemplateSpecializationDecl *Specialization = 0;
4294
Douglas Gregor0681a352009-11-25 06:01:46 +00004295 bool ReusedDecl = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004296 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00004297 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004298 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004299 PrevDecl,
4300 PrevDecl->getSpecializationKind(),
4301 PrevDecl->getPointOfInstantiation(),
4302 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00004303 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004304
Douglas Gregor12e49d32009-10-15 22:53:21 +00004305 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004306 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00004307
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004308 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4309 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4310 // Since the only prior class template specialization with these
4311 // arguments was referenced but not declared, reuse that
4312 // declaration node as our own, updating its source location to
4313 // reflect our new declaration.
4314 Specialization = PrevDecl;
4315 Specialization->setLocation(TemplateNameLoc);
4316 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004317 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004318 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004319 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004320
4321 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004322 // Create a new class template specialization declaration node for
4323 // this explicit specialization.
4324 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00004325 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00004326 ClassTemplate->getDeclContext(),
4327 TemplateNameLoc,
4328 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004329 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004330
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004331 if (PrevDecl) {
4332 // Remove the previous declaration from the folding set, since we want
4333 // to introduce a new declaration.
4334 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4335 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4336 }
4337
4338 // Insert the new specialization.
4339 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004340 }
4341
4342 // Build the fully-sugared type for this explicit instantiation as
4343 // the user wrote in the explicit instantiation itself. This means
4344 // that we'll pretty-print the type retrieved from the
4345 // specialization's declaration the way that the user actually wrote
4346 // the explicit instantiation, rather than formatting the name based
4347 // on the "canonical" representation used to store the template
4348 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004349 TypeSourceInfo *WrittenTy
4350 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4351 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004352 Context.getTypeDeclType(Specialization));
4353 Specialization->setTypeAsWritten(WrittenTy);
4354 TemplateArgsIn.release();
4355
Douglas Gregor0681a352009-11-25 06:01:46 +00004356 if (!ReusedDecl) {
4357 // Add the explicit instantiation into its lexical context. However,
4358 // since explicit instantiations are never found by name lookup, we
4359 // just put it into the declaration context directly.
4360 Specialization->setLexicalDeclContext(CurContext);
4361 CurContext->addDecl(Specialization);
4362 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004363
4364 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004365 // A definition of a class template or class member template
4366 // shall be in scope at the point of the explicit instantiation of
4367 // the class template or class member template.
4368 //
4369 // This check comes when we actually try to perform the
4370 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004371 ClassTemplateSpecializationDecl *Def
4372 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004373 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004374 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004375 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00004376
4377 // Instantiate the members of this class template specialization.
4378 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004379 Specialization->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004380 if (Def)
Douglas Gregor12e49d32009-10-15 22:53:21 +00004381 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00004382
4383 return DeclPtrTy::make(Specialization);
4384}
4385
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004386// Explicit instantiation of a member class of a class template.
4387Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004388Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004389 SourceLocation ExternLoc,
4390 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004391 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004392 SourceLocation KWLoc,
4393 const CXXScopeSpec &SS,
4394 IdentifierInfo *Name,
4395 SourceLocation NameLoc,
4396 AttributeList *Attr) {
4397
Douglas Gregord6ab8742009-05-28 23:31:59 +00004398 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004399 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004400 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004401 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004402 MultiTemplateParamsArg(*this, 0, 0),
4403 Owned, IsDependent);
4404 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4405
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004406 if (!TagD)
4407 return true;
4408
4409 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4410 if (Tag->isEnum()) {
4411 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4412 << Context.getTypeDeclType(Tag);
4413 return true;
4414 }
4415
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004416 if (Tag->isInvalidDecl())
4417 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004418
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004419 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4420 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4421 if (!Pattern) {
4422 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4423 << Context.getTypeDeclType(Record);
4424 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4425 return true;
4426 }
4427
Douglas Gregore47f5a72009-10-14 23:41:34 +00004428 // C++0x [temp.explicit]p2:
4429 // If the explicit instantiation is for a class or member class, the
4430 // elaborated-type-specifier in the declaration shall include a
4431 // simple-template-id.
4432 //
4433 // C++98 has the same restriction, just worded differently.
4434 if (!ScopeSpecifierHasTemplateId(SS))
4435 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4436 << Record << SS.getRange();
4437
4438 // C++0x [temp.explicit]p2:
4439 // There are two forms of explicit instantiation: an explicit instantiation
4440 // definition and an explicit instantiation declaration. An explicit
4441 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004442 TemplateSpecializationKind TSK
4443 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4444 : TSK_ExplicitInstantiationDeclaration;
4445
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004446 // C++0x [temp.explicit]p2:
4447 // [...] An explicit instantiation shall appear in an enclosing
4448 // namespace of its template. [...]
4449 //
4450 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004451 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004452
4453 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004454 CXXRecordDecl *PrevDecl
4455 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004456 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004457 PrevDecl = Record;
4458 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004459 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4460 bool SuppressNew = false;
4461 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004462 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004463 PrevDecl,
4464 MSInfo->getTemplateSpecializationKind(),
4465 MSInfo->getPointOfInstantiation(),
4466 SuppressNew))
4467 return true;
4468 if (SuppressNew)
4469 return TagD;
4470 }
4471
Douglas Gregor12e49d32009-10-15 22:53:21 +00004472 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004473 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004474 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004475 // C++ [temp.explicit]p3:
4476 // A definition of a member class of a class template shall be in scope
4477 // at the point of an explicit instantiation of the member class.
4478 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004479 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004480 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004481 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4482 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004483 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4484 << Pattern;
4485 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004486 } else {
4487 if (InstantiateClass(NameLoc, Record, Def,
4488 getTemplateInstantiationArgs(Record),
4489 TSK))
4490 return true;
4491
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004492 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004493 if (!RecordDef)
4494 return true;
4495 }
4496 }
4497
4498 // Instantiate all of the members of the class.
4499 InstantiateClassMembers(NameLoc, RecordDef,
4500 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004501
Mike Stump87c57ac2009-05-16 07:39:55 +00004502 // FIXME: We don't have any representation for explicit instantiations of
4503 // member classes. Such a representation is not needed for compilation, but it
4504 // should be available for clients that want to see all of the declarations in
4505 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004506 return TagD;
4507}
4508
Douglas Gregor450f00842009-09-25 18:43:00 +00004509Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4510 SourceLocation ExternLoc,
4511 SourceLocation TemplateLoc,
4512 Declarator &D) {
4513 // Explicit instantiations always require a name.
4514 DeclarationName Name = GetNameForDeclarator(D);
4515 if (!Name) {
4516 if (!D.isInvalidType())
4517 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4518 diag::err_explicit_instantiation_requires_name)
4519 << D.getDeclSpec().getSourceRange()
4520 << D.getSourceRange();
4521
4522 return true;
4523 }
4524
4525 // The scope passed in may not be a decl scope. Zip up the scope tree until
4526 // we find one that is.
4527 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4528 (S->getFlags() & Scope::TemplateParamScope) != 0)
4529 S = S->getParent();
4530
4531 // Determine the type of the declaration.
4532 QualType R = GetTypeForDeclarator(D, S, 0);
4533 if (R.isNull())
4534 return true;
4535
4536 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4537 // Cannot explicitly instantiate a typedef.
4538 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4539 << Name;
4540 return true;
4541 }
4542
Douglas Gregor3c74d412009-10-14 20:14:33 +00004543 // C++0x [temp.explicit]p1:
4544 // [...] An explicit instantiation of a function template shall not use the
4545 // inline or constexpr specifiers.
4546 // Presumably, this also applies to member functions of class templates as
4547 // well.
4548 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4549 Diag(D.getDeclSpec().getInlineSpecLoc(),
4550 diag::err_explicit_instantiation_inline)
Chris Lattner3c7b86f2009-12-06 17:36:05 +00004551 <<CodeModificationHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004552
4553 // FIXME: check for constexpr specifier.
4554
Douglas Gregore47f5a72009-10-14 23:41:34 +00004555 // C++0x [temp.explicit]p2:
4556 // There are two forms of explicit instantiation: an explicit instantiation
4557 // definition and an explicit instantiation declaration. An explicit
4558 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004559 TemplateSpecializationKind TSK
4560 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4561 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004562
John McCall27b18f82009-11-17 02:14:36 +00004563 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4564 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004565
4566 if (!R->isFunctionType()) {
4567 // C++ [temp.explicit]p1:
4568 // A [...] static data member of a class template can be explicitly
4569 // instantiated from the member definition associated with its class
4570 // template.
John McCall27b18f82009-11-17 02:14:36 +00004571 if (Previous.isAmbiguous())
4572 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00004573
John McCall67c00872009-12-02 08:25:40 +00004574 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00004575 if (!Prev || !Prev->isStaticDataMember()) {
4576 // We expect to see a data data member here.
4577 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4578 << Name;
4579 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4580 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004581 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004582 return true;
4583 }
4584
4585 if (!Prev->getInstantiatedFromStaticDataMember()) {
4586 // FIXME: Check for explicit specialization?
4587 Diag(D.getIdentifierLoc(),
4588 diag::err_explicit_instantiation_data_member_not_instantiated)
4589 << Prev;
4590 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4591 // FIXME: Can we provide a note showing where this was declared?
4592 return true;
4593 }
4594
Douglas Gregore47f5a72009-10-14 23:41:34 +00004595 // C++0x [temp.explicit]p2:
4596 // If the explicit instantiation is for a member function, a member class
4597 // or a static data member of a class template specialization, the name of
4598 // the class template specialization in the qualified-id for the member
4599 // name shall be a simple-template-id.
4600 //
4601 // C++98 has the same restriction, just worded differently.
4602 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4603 Diag(D.getIdentifierLoc(),
4604 diag::err_explicit_instantiation_without_qualified_id)
4605 << Prev << D.getCXXScopeSpec().getRange();
4606
4607 // Check the scope of this explicit instantiation.
4608 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4609
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004610 // Verify that it is okay to explicitly instantiate here.
4611 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4612 assert(MSInfo && "Missing static data member specialization info?");
4613 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004614 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004615 MSInfo->getTemplateSpecializationKind(),
4616 MSInfo->getPointOfInstantiation(),
4617 SuppressNew))
4618 return true;
4619 if (SuppressNew)
4620 return DeclPtrTy();
4621
Douglas Gregor450f00842009-09-25 18:43:00 +00004622 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004623 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004624 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004625 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4626 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004627
4628 // FIXME: Create an ExplicitInstantiation node?
4629 return DeclPtrTy();
4630 }
4631
Douglas Gregor0e876e02009-09-25 23:53:26 +00004632 // If the declarator is a template-id, translate the parser's template
4633 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004634 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004635 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004636 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4637 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00004638 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4639 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00004640 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4641 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004642 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00004643 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00004644 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004645 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004646 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004647
Douglas Gregor450f00842009-09-25 18:43:00 +00004648 // C++ [temp.explicit]p1:
4649 // A [...] function [...] can be explicitly instantiated from its template.
4650 // A member function [...] of a class template can be explicitly
4651 // instantiated from the member definition associated with its class
4652 // template.
John McCall58cc69d2010-01-27 01:50:18 +00004653 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00004654 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4655 P != PEnd; ++P) {
4656 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004657 if (!HasExplicitTemplateArgs) {
4658 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4659 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4660 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004661
John McCall58cc69d2010-01-27 01:50:18 +00004662 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004663 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
4664 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00004665 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004666 }
4667 }
4668
4669 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4670 if (!FunTmpl)
4671 continue;
4672
John McCallbc077cf2010-02-08 23:07:23 +00004673 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004674 FunctionDecl *Specialization = 0;
4675 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004676 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00004677 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004678 R, Specialization, Info)) {
4679 // FIXME: Keep track of almost-matches?
4680 (void)TDK;
4681 continue;
4682 }
4683
John McCall58cc69d2010-01-27 01:50:18 +00004684 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00004685 }
4686
4687 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004688 UnresolvedSetIterator Result
4689 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00004690 D.getIdentifierLoc(),
4691 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4692 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4693 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4694
John McCall58cc69d2010-01-27 01:50:18 +00004695 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00004696 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004697
4698 // Ignore access control bits, we don't need them for redeclaration checking.
4699 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00004700
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004701 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004702 Diag(D.getIdentifierLoc(),
4703 diag::err_explicit_instantiation_member_function_not_instantiated)
4704 << Specialization
4705 << (Specialization->getTemplateSpecializationKind() ==
4706 TSK_ExplicitSpecialization);
4707 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4708 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004709 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004710
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004711 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004712 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4713 PrevDecl = Specialization;
4714
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004715 if (PrevDecl) {
4716 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004717 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004718 PrevDecl,
4719 PrevDecl->getTemplateSpecializationKind(),
4720 PrevDecl->getPointOfInstantiation(),
4721 SuppressNew))
4722 return true;
4723
4724 // FIXME: We may still want to build some representation of this
4725 // explicit specialization.
4726 if (SuppressNew)
4727 return DeclPtrTy();
4728 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00004729
4730 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004731
4732 if (TSK == TSK_ExplicitInstantiationDefinition)
4733 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4734 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004735
Douglas Gregore47f5a72009-10-14 23:41:34 +00004736 // C++0x [temp.explicit]p2:
4737 // If the explicit instantiation is for a member function, a member class
4738 // or a static data member of a class template specialization, the name of
4739 // the class template specialization in the qualified-id for the member
4740 // name shall be a simple-template-id.
4741 //
4742 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004743 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00004744 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00004745 D.getCXXScopeSpec().isSet() &&
4746 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4747 Diag(D.getIdentifierLoc(),
4748 diag::err_explicit_instantiation_without_qualified_id)
4749 << Specialization << D.getCXXScopeSpec().getRange();
4750
4751 CheckExplicitInstantiationScope(*this,
4752 FunTmpl? (NamedDecl *)FunTmpl
4753 : Specialization->getInstantiatedFromMemberFunction(),
4754 D.getIdentifierLoc(),
4755 D.getCXXScopeSpec().isSet());
4756
Douglas Gregor450f00842009-09-25 18:43:00 +00004757 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4758 return DeclPtrTy();
4759}
4760
Douglas Gregor333489b2009-03-27 23:10:48 +00004761Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004762Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4763 const CXXScopeSpec &SS, IdentifierInfo *Name,
4764 SourceLocation TagLoc, SourceLocation NameLoc) {
4765 // This has to hold, because SS is expected to be defined.
4766 assert(Name && "Expected a name in a dependent tag");
4767
4768 NestedNameSpecifier *NNS
4769 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4770 if (!NNS)
4771 return true;
4772
4773 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4774 if (T.isNull())
4775 return true;
4776
4777 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4778 QualType ElabType = Context.getElaboratedType(T, TagKind);
4779
4780 return ElabType.getAsOpaquePtr();
4781}
4782
4783Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004784Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4785 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004786 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004787 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4788 if (!NNS)
4789 return true;
4790
4791 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004792 if (T.isNull())
4793 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004794 return T.getAsOpaquePtr();
4795}
4796
Douglas Gregordce2b622009-04-01 00:28:59 +00004797Sema::TypeResult
4798Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4799 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004800 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004801 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004802 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004803 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004804 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004805 assert(TemplateId && "Expected a template specialization type");
4806
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004807 if (computeDeclContext(SS, false)) {
4808 // If we can compute a declaration context, then the "typename"
4809 // keyword was superfluous. Just build a QualifiedNameType to keep
4810 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004811
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004812 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4813 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4814 }
Mike Stump11289f42009-09-09 15:08:12 +00004815
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004816 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004817}
4818
Douglas Gregor333489b2009-03-27 23:10:48 +00004819/// \brief Build the type that describes a C++ typename specifier,
4820/// e.g., "typename T::type".
4821QualType
4822Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4823 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004824 CXXRecordDecl *CurrentInstantiation = 0;
4825 if (NNS->isDependent()) {
4826 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004827
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004828 // If the nested-name-specifier does not refer to the current
4829 // instantiation, then build a typename type.
4830 if (!CurrentInstantiation)
4831 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004832
Douglas Gregorc707da62009-09-02 13:12:51 +00004833 // The nested-name-specifier refers to the current instantiation, so the
4834 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004835 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004836 // extraneous "typename" keywords, and we retroactively apply this DR to
4837 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004838 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004839
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004840 DeclContext *Ctx = 0;
4841
4842 if (CurrentInstantiation)
4843 Ctx = CurrentInstantiation;
4844 else {
4845 CXXScopeSpec SS;
4846 SS.setScopeRep(NNS);
4847 SS.setRange(Range);
4848 if (RequireCompleteDeclContext(SS))
4849 return QualType();
4850
4851 Ctx = computeDeclContext(SS);
4852 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004853 assert(Ctx && "No declaration context?");
4854
4855 DeclarationName Name(&II);
John McCall27b18f82009-11-17 02:14:36 +00004856 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4857 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00004858 unsigned DiagID = 0;
4859 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00004860 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004861 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004862 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004863 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00004864
4865 case LookupResult::NotFoundInCurrentInstantiation:
4866 // Okay, it's a member of an unknown instantiation.
4867 return Context.getTypenameType(NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00004868
4869 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004870 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004871 // We found a type. Build a QualifiedNameType, since the
4872 // typename-specifier was just sugar. FIXME: Tell
4873 // QualifiedNameType that it has a "typename" prefix.
4874 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4875 }
4876
4877 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004878 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004879 break;
4880
John McCalle61f2ba2009-11-18 02:36:19 +00004881 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004882 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00004883 return QualType();
4884
Douglas Gregor333489b2009-03-27 23:10:48 +00004885 case LookupResult::FoundOverloaded:
4886 DiagID = diag::err_typename_nested_not_type;
4887 Referenced = *Result.begin();
4888 break;
4889
John McCall6538c932009-10-10 05:48:19 +00004890 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004891 return QualType();
4892 }
4893
4894 // If we get here, it's because name lookup did not find a
4895 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004896 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004897 if (Referenced)
4898 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4899 << Name;
4900 return QualType();
4901}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004902
4903namespace {
4904 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00004905 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00004906 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004907 SourceLocation Loc;
4908 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004909
Douglas Gregor15acfb92009-08-06 16:20:37 +00004910 public:
Mike Stump11289f42009-09-09 15:08:12 +00004911 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004912 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004913 DeclarationName Entity)
4914 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004915 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004916
4917 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004918 /// transformed.
4919 ///
4920 /// For the purposes of type reconstruction, a type has already been
4921 /// transformed if it is NULL or if it is not dependent.
4922 bool AlreadyTransformed(QualType T) {
4923 return T.isNull() || !T->isDependentType();
4924 }
Mike Stump11289f42009-09-09 15:08:12 +00004925
4926 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004927 /// rebuilt.
4928 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004929
Douglas Gregor15acfb92009-08-06 16:20:37 +00004930 /// \brief Returns the name of the entity whose type is being rebuilt.
4931 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004932
Douglas Gregoref6ab412009-10-27 06:26:26 +00004933 /// \brief Sets the "base" location and entity when that
4934 /// information is known based on another transformation.
4935 void setBase(SourceLocation Loc, DeclarationName Entity) {
4936 this->Loc = Loc;
4937 this->Entity = Entity;
4938 }
4939
Douglas Gregor15acfb92009-08-06 16:20:37 +00004940 /// \brief Transforms an expression by returning the expression itself
4941 /// (an identity function).
4942 ///
4943 /// FIXME: This is completely unsafe; we will need to actually clone the
4944 /// expressions.
4945 Sema::OwningExprResult TransformExpr(Expr *E) {
4946 return getSema().Owned(E);
4947 }
Mike Stump11289f42009-09-09 15:08:12 +00004948
Douglas Gregor15acfb92009-08-06 16:20:37 +00004949 /// \brief Transforms a typename type by determining whether the type now
4950 /// refers to a member of the current instantiation, and then
4951 /// type-checking and building a QualifiedNameType (when possible).
Douglas Gregorfe17d252010-02-16 19:09:40 +00004952 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL,
4953 QualType ObjectType);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004954 };
4955}
4956
Mike Stump11289f42009-09-09 15:08:12 +00004957QualType
John McCall550e0c22009-10-21 00:40:46 +00004958CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
Douglas Gregorfe17d252010-02-16 19:09:40 +00004959 TypenameTypeLoc TL,
4960 QualType ObjectType) {
John McCall0ad16662009-10-29 08:12:44 +00004961 TypenameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00004962
Douglas Gregor15acfb92009-08-06 16:20:37 +00004963 NestedNameSpecifier *NNS
4964 = TransformNestedNameSpecifier(T->getQualifier(),
Douglas Gregorfe17d252010-02-16 19:09:40 +00004965 /*FIXME:*/SourceRange(getBaseLocation()),
4966 ObjectType);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004967 if (!NNS)
4968 return QualType();
4969
4970 // If the nested-name-specifier did not change, and we cannot compute the
4971 // context corresponding to the nested-name-specifier, then this
4972 // typename type will not change; exit early.
4973 CXXScopeSpec SS;
4974 SS.setRange(SourceRange(getBaseLocation()));
4975 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00004976
4977 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004978 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00004979 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004980
4981 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004982 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00004983 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004984 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004985 = TransformType(QualType(TemplateId, 0));
4986 if (NewTemplateId.isNull())
4987 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004988
Douglas Gregor15acfb92009-08-06 16:20:37 +00004989 if (NNS == T->getQualifier() &&
4990 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00004991 Result = QualType(T, 0);
4992 else
4993 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4994 } else
4995 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4996 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00004997
Douglas Gregor281c4862010-03-07 23:26:22 +00004998 if (Result.isNull())
4999 return QualType();
5000
John McCall0ad16662009-10-29 08:12:44 +00005001 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
5002 NewTL.setNameLoc(TL.getNameLoc());
5003 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00005004}
5005
5006/// \brief Rebuilds a type within the context of the current instantiation.
5007///
Mike Stump11289f42009-09-09 15:08:12 +00005008/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005009/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005010/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005011/// partial specialization thereof). This routine will rebuild that type now
5012/// that we have entered the declarator's scope, which may produce different
5013/// canonical types, e.g.,
5014///
5015/// \code
5016/// template<typename T>
5017/// struct X {
5018/// typedef T* pointer;
5019/// pointer data();
5020/// };
5021///
5022/// template<typename T>
5023/// typename X<T>::pointer X<T>::data() { ... }
5024/// \endcode
5025///
5026/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
5027/// since we do not know that we can look into X<T> when we parsed the type.
5028/// This function will rebuild the type, performing the lookup of "pointer"
5029/// in X<T> and returning a QualifiedNameType whose canonical type is the same
5030/// as the canonical type of T*, allowing the return types of the out-of-line
5031/// definition and the declaration to match.
5032QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
5033 DeclarationName Name) {
5034 if (T.isNull() || !T->isDependentType())
5035 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005036
Douglas Gregor15acfb92009-08-06 16:20:37 +00005037 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5038 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005039}
Douglas Gregorbe999392009-09-15 16:23:51 +00005040
5041/// \brief Produces a formatted string that describes the binding of
5042/// template parameters to template arguments.
5043std::string
5044Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5045 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005046 // FIXME: For variadic templates, we'll need to get the structured list.
5047 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5048 Args.flat_size());
5049}
5050
5051std::string
5052Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5053 const TemplateArgument *Args,
5054 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005055 std::string Result;
5056
Douglas Gregore62e6a02009-11-11 19:13:48 +00005057 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005058 return Result;
5059
5060 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005061 if (I >= NumArgs)
5062 break;
5063
Douglas Gregorbe999392009-09-15 16:23:51 +00005064 if (I == 0)
5065 Result += "[with ";
5066 else
5067 Result += ", ";
5068
5069 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5070 Result += Id->getName();
5071 } else {
5072 Result += '$';
5073 Result += llvm::utostr(I);
5074 }
5075
5076 Result += " = ";
5077
5078 switch (Args[I].getKind()) {
5079 case TemplateArgument::Null:
5080 Result += "<no value>";
5081 break;
5082
5083 case TemplateArgument::Type: {
5084 std::string TypeStr;
5085 Args[I].getAsType().getAsStringInternal(TypeStr,
5086 Context.PrintingPolicy);
5087 Result += TypeStr;
5088 break;
5089 }
5090
5091 case TemplateArgument::Declaration: {
5092 bool Unnamed = true;
5093 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5094 if (ND->getDeclName()) {
5095 Unnamed = false;
5096 Result += ND->getNameAsString();
5097 }
5098 }
5099
5100 if (Unnamed) {
5101 Result += "<anonymous>";
5102 }
5103 break;
5104 }
5105
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005106 case TemplateArgument::Template: {
5107 std::string Str;
5108 llvm::raw_string_ostream OS(Str);
5109 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5110 Result += OS.str();
5111 break;
5112 }
5113
Douglas Gregorbe999392009-09-15 16:23:51 +00005114 case TemplateArgument::Integral: {
5115 Result += Args[I].getAsIntegral()->toString(10);
5116 break;
5117 }
5118
5119 case TemplateArgument::Expression: {
5120 assert(false && "No expressions in deduced template arguments!");
5121 Result += "<expression>";
5122 break;
5123 }
5124
5125 case TemplateArgument::Pack:
5126 // FIXME: Format template argument packs
5127 Result += "<template argument pack>";
5128 break;
5129 }
5130 }
5131
5132 Result += ']';
5133 return Result;
5134}