blob: e75277e823e0ae156cbb05011eeb311fa407a81f [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
Mike Stump11289f42009-09-09 15:08:12 +0000452 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
453 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
575 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000576 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000577 if (Invalid)
578 Param->setInvalidDecl();
579
580 if (D.getIdentifier()) {
581 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000582 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000583 IdResolver.AddDecl(Param);
584 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000585 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000586}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000587
Douglas Gregordba32632009-02-10 19:49:53 +0000588/// \brief Adds a default argument to the given non-type template
589/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000590void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000591 SourceLocation EqualLoc,
592 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000593 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000594 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000595 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000596
Douglas Gregordba32632009-02-10 19:49:53 +0000597 // C++ [temp.param]p14:
598 // A template-parameter shall not be used in its own default argument.
599 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000600
Douglas Gregordba32632009-02-10 19:49:53 +0000601 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000602 TemplateArgument Converted;
603 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
604 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000605 TemplateParm->setInvalidDecl();
606 return;
607 }
608
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000609 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000610}
611
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000612
613/// ActOnTemplateTemplateParameter - Called when a C++ template template
614/// parameter (e.g. T in template <template <typename> class T> class array)
615/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000616Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
617 SourceLocation TmpLoc,
618 TemplateParamsTy *Params,
619 IdentifierInfo *Name,
620 SourceLocation NameLoc,
621 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000622 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000623 assert(S->isTemplateParamScope() &&
624 "Template template parameter not in template parameter scope!");
625
626 // Construct the parameter object.
627 TemplateTemplateParmDecl *Param =
628 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
629 Position, Name,
630 (TemplateParameterList*)Params);
631
632 // Make sure the parameter is valid.
633 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
634 // do anything yet. However, if the template parameter list or (eventual)
635 // default value is ever invalidated, that will propagate here.
636 bool Invalid = false;
637 if (Invalid) {
638 Param->setInvalidDecl();
639 }
640
641 // If the tt-param has a name, then link the identifier into the scope
642 // and lookup mechanisms.
643 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000644 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000645 IdResolver.AddDecl(Param);
646 }
647
Chris Lattner83f095c2009-03-28 19:18:32 +0000648 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000649}
650
Douglas Gregordba32632009-02-10 19:49:53 +0000651/// \brief Adds a default argument to the given template template
652/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000653void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000654 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000655 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000656 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000657 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000658
Douglas Gregordba32632009-02-10 19:49:53 +0000659 // C++ [temp.param]p14:
660 // A template-parameter shall not be used in its own default argument.
661 // FIXME: Implement this check! Needs a recursive walk over the types.
662
Douglas Gregore62e6a02009-11-11 19:13:48 +0000663 // Check only that we have a template template argument. We don't want to
664 // try to check well-formedness now, because our template template parameter
665 // might have dependent types in its template parameters, which we wouldn't
666 // be able to match now.
667 //
668 // If none of the template template parameter's template arguments mention
669 // other template parameters, we could actually perform more checking here.
670 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000671 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000672 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
673 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
674 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000675 return;
676 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000677
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000678 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000679}
680
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000681/// ActOnTemplateParameterList - Builds a TemplateParameterList that
682/// contains the template parameters in Params/NumParams.
683Sema::TemplateParamsTy *
684Sema::ActOnTemplateParameterList(unsigned Depth,
685 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000686 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000687 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000688 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000689 SourceLocation RAngleLoc) {
690 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000691 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000692
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000693 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000694 (NamedDecl**)Params, NumParams,
695 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000696}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000697
Douglas Gregorc08f4892009-03-25 00:13:59 +0000698Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000699Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000700 SourceLocation KWLoc, const CXXScopeSpec &SS,
701 IdentifierInfo *Name, SourceLocation NameLoc,
702 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000703 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000704 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000705 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000706 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000707 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000708 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000709
710 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000711 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000712 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000713
John McCall27b5c252009-09-14 21:59:20 +0000714 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
715 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000716
717 // There is no such thing as an unnamed class template.
718 if (!Name) {
719 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000720 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000721 }
722
723 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000724 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000725 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000726 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000727 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000728 if (RequireCompleteDeclContext(SS))
729 return true;
730
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000731 SemanticContext = computeDeclContext(SS, true);
732 if (!SemanticContext) {
733 // FIXME: Produce a reasonable diagnostic here
734 return true;
735 }
Mike Stump11289f42009-09-09 15:08:12 +0000736
John McCall27b18f82009-11-17 02:14:36 +0000737 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000738 } else {
739 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000740 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000741 }
Mike Stump11289f42009-09-09 15:08:12 +0000742
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000743 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
744 NamedDecl *PrevDecl = 0;
745 if (Previous.begin() != Previous.end())
746 PrevDecl = *Previous.begin();
747
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000748 // If there is a previous declaration with the same name, check
749 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000750 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000751 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000752
753 // We may have found the injected-class-name of a class template,
754 // class template partial specialization, or class template specialization.
755 // In these cases, grab the template that is being defined or specialized.
756 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
757 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
758 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
759 PrevClassTemplate
760 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
761 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
762 PrevClassTemplate
763 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
764 ->getSpecializedTemplate();
765 }
766 }
767
John McCalld43784f2009-12-18 11:25:59 +0000768 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000769 // C++ [namespace.memdef]p3:
770 // [...] When looking for a prior declaration of a class or a function
771 // declared as a friend, and when the name of the friend class or
772 // function is neither a qualified name nor a template-id, scopes outside
773 // the innermost enclosing namespace scope are not considered.
774 DeclContext *OutermostContext = CurContext;
775 while (!OutermostContext->isFileContext())
776 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000777
778 if (PrevDecl &&
779 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
780 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
John McCall90d3bb92009-12-17 23:21:11 +0000781 SemanticContext = PrevDecl->getDeclContext();
782 } else {
783 // Declarations in outer scopes don't matter. However, the outermost
784 // context we computed is the semantic context for our new
785 // declaration.
786 PrevDecl = PrevClassTemplate = 0;
787 SemanticContext = OutermostContext;
788 }
789
790 if (CurContext->isDependentContext()) {
791 // If this is a dependent context, we don't want to link the friend
792 // class template to the template in scope, because that would perform
793 // checking of the template parameter lists that can't be performed
794 // until the outer context is instantiated.
795 PrevDecl = PrevClassTemplate = 0;
796 }
797 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
798 PrevDecl = PrevClassTemplate = 0;
799
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000800 if (PrevClassTemplate) {
801 // Ensure that the template parameter lists are compatible.
802 if (!TemplateParameterListsAreEqual(TemplateParams,
803 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000804 /*Complain=*/true,
805 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000806 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000807
808 // C++ [temp.class]p4:
809 // In a redeclaration, partial specialization, explicit
810 // specialization or explicit instantiation of a class template,
811 // the class-key shall agree in kind with the original class
812 // template declaration (7.1.5.3).
813 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000814 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000815 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000816 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000817 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000818 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000819 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000820 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000821 }
822
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000823 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000824 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000825 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
826 Diag(NameLoc, diag::err_redefinition) << Name;
827 Diag(Def->getLocation(), diag::note_previous_definition);
828 // FIXME: Would it make sense to try to "forget" the previous
829 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000830 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000831 }
832 }
833 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
834 // Maybe we will complain about the shadowed template parameter.
835 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
836 // Just pretend that we didn't see the previous declaration.
837 PrevDecl = 0;
838 } else if (PrevDecl) {
839 // C++ [temp]p5:
840 // A class template shall not have the same name as any other
841 // template, class, function, object, enumeration, enumerator,
842 // namespace, or type in the same scope (3.3), except as specified
843 // in (14.5.4).
844 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
845 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000846 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000847 }
848
Douglas Gregordba32632009-02-10 19:49:53 +0000849 // Check the template parameter list of this declaration, possibly
850 // merging in the template parameter list from the previous class
851 // template declaration.
852 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000853 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
854 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000855 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000856
Douglas Gregore362cea2009-05-10 22:57:19 +0000857 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000858 // declaration!
859
Mike Stump11289f42009-09-09 15:08:12 +0000860 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000861 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000862 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000863 PrevClassTemplate->getTemplatedDecl() : 0,
864 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000865
866 ClassTemplateDecl *NewTemplate
867 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
868 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000869 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000870 NewClass->setDescribedClassTemplate(NewTemplate);
871
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000872 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000873 QualType T =
874 Context.getTypeDeclType(NewClass,
875 PrevClassTemplate?
876 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000877 assert(T->isDependentType() && "Class template type is not dependent?");
878 (void)T;
879
Douglas Gregorcf915552009-10-13 16:30:37 +0000880 // If we are providing an explicit specialization of a member that is a
881 // class template, make a note of that.
882 if (PrevClassTemplate &&
883 PrevClassTemplate->getInstantiatedFromMemberTemplate())
884 PrevClassTemplate->setMemberSpecialization();
885
Anders Carlsson137108d2009-03-26 01:24:28 +0000886 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000887 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000888 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000889
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000890 // Set the lexical context of these templates
891 NewClass->setLexicalDeclContext(CurContext);
892 NewTemplate->setLexicalDeclContext(CurContext);
893
John McCall9bb74a52009-07-31 02:45:11 +0000894 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000895 NewClass->startDefinition();
896
897 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000898 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000899
John McCall27b5c252009-09-14 21:59:20 +0000900 if (TUK != TUK_Friend)
901 PushOnScopeChains(NewTemplate, S);
902 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000903 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000904 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000905 NewClass->setAccess(PrevClassTemplate->getAccess());
906 }
John McCall27b5c252009-09-14 21:59:20 +0000907
Douglas Gregor3dad8422009-09-26 06:47:28 +0000908 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
909 PrevClassTemplate != NULL);
910
John McCall27b5c252009-09-14 21:59:20 +0000911 // Friend templates are visible in fairly strange ways.
912 if (!CurContext->isDependentContext()) {
913 DeclContext *DC = SemanticContext->getLookupContext();
914 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
915 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
916 PushOnScopeChains(NewTemplate, EnclosingScope,
917 /* AddToContext = */ false);
918 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000919
920 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
921 NewClass->getLocation(),
922 NewTemplate,
923 /*FIXME:*/NewClass->getLocation());
924 Friend->setAccess(AS_public);
925 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000926 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000927
Douglas Gregordba32632009-02-10 19:49:53 +0000928 if (Invalid) {
929 NewTemplate->setInvalidDecl();
930 NewClass->setInvalidDecl();
931 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000932 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000933}
934
Douglas Gregored5731f2009-11-25 17:50:39 +0000935/// \brief Diagnose the presence of a default template argument on a
936/// template parameter, which is ill-formed in certain contexts.
937///
938/// \returns true if the default template argument should be dropped.
939static bool DiagnoseDefaultTemplateArgument(Sema &S,
940 Sema::TemplateParamListContext TPC,
941 SourceLocation ParamLoc,
942 SourceRange DefArgRange) {
943 switch (TPC) {
944 case Sema::TPC_ClassTemplate:
945 return false;
946
947 case Sema::TPC_FunctionTemplate:
948 // C++ [temp.param]p9:
949 // A default template-argument shall not be specified in a
950 // function template declaration or a function template
951 // definition [...]
952 // (This sentence is not in C++0x, per DR226).
953 if (!S.getLangOptions().CPlusPlus0x)
954 S.Diag(ParamLoc,
955 diag::err_template_parameter_default_in_function_template)
956 << DefArgRange;
957 return false;
958
959 case Sema::TPC_ClassTemplateMember:
960 // C++0x [temp.param]p9:
961 // A default template-argument shall not be specified in the
962 // template-parameter-lists of the definition of a member of a
963 // class template that appears outside of the member's class.
964 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
965 << DefArgRange;
966 return true;
967
968 case Sema::TPC_FriendFunctionTemplate:
969 // C++ [temp.param]p9:
970 // A default template-argument shall not be specified in a
971 // friend template declaration.
972 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
973 << DefArgRange;
974 return true;
975
976 // FIXME: C++0x [temp.param]p9 allows default template-arguments
977 // for friend function templates if there is only a single
978 // declaration (and it is a definition). Strange!
979 }
980
981 return false;
982}
983
Douglas Gregordba32632009-02-10 19:49:53 +0000984/// \brief Checks the validity of a template parameter list, possibly
985/// considering the template parameter list from a previous
986/// declaration.
987///
988/// If an "old" template parameter list is provided, it must be
989/// equivalent (per TemplateParameterListsAreEqual) to the "new"
990/// template parameter list.
991///
992/// \param NewParams Template parameter list for a new template
993/// declaration. This template parameter list will be updated with any
994/// default arguments that are carried through from the previous
995/// template parameter list.
996///
997/// \param OldParams If provided, template parameter list from a
998/// previous declaration of the same template. Default template
999/// arguments will be merged from the old template parameter list to
1000/// the new template parameter list.
1001///
Douglas Gregored5731f2009-11-25 17:50:39 +00001002/// \param TPC Describes the context in which we are checking the given
1003/// template parameter list.
1004///
Douglas Gregordba32632009-02-10 19:49:53 +00001005/// \returns true if an error occurred, false otherwise.
1006bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001007 TemplateParameterList *OldParams,
1008 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001009 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001010
Douglas Gregordba32632009-02-10 19:49:53 +00001011 // C++ [temp.param]p10:
1012 // The set of default template-arguments available for use with a
1013 // template declaration or definition is obtained by merging the
1014 // default arguments from the definition (if in scope) and all
1015 // declarations in scope in the same way default function
1016 // arguments are (8.3.6).
1017 bool SawDefaultArgument = false;
1018 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001019
Anders Carlsson327865d2009-06-12 23:20:15 +00001020 bool SawParameterPack = false;
1021 SourceLocation ParameterPackLoc;
1022
Mike Stumpc89c8e32009-02-11 23:03:27 +00001023 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001024 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001025 if (OldParams)
1026 OldParam = OldParams->begin();
1027
1028 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1029 NewParamEnd = NewParams->end();
1030 NewParam != NewParamEnd; ++NewParam) {
1031 // Variables used to diagnose redundant default arguments
1032 bool RedundantDefaultArg = false;
1033 SourceLocation OldDefaultLoc;
1034 SourceLocation NewDefaultLoc;
1035
1036 // Variables used to diagnose missing default arguments
1037 bool MissingDefaultArg = false;
1038
Anders Carlsson327865d2009-06-12 23:20:15 +00001039 // C++0x [temp.param]p11:
1040 // If a template parameter of a class template is a template parameter pack,
1041 // it must be the last template parameter.
1042 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001043 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001044 diag::err_template_param_pack_must_be_last_template_parameter);
1045 Invalid = true;
1046 }
1047
Douglas Gregordba32632009-02-10 19:49:53 +00001048 if (TemplateTypeParmDecl *NewTypeParm
1049 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001050 // Check the presence of a default argument here.
1051 if (NewTypeParm->hasDefaultArgument() &&
1052 DiagnoseDefaultTemplateArgument(*this, TPC,
1053 NewTypeParm->getLocation(),
1054 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1055 .getFullSourceRange()))
1056 NewTypeParm->removeDefaultArgument();
1057
1058 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001059 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001060 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001061
Anders Carlsson327865d2009-06-12 23:20:15 +00001062 if (NewTypeParm->isParameterPack()) {
1063 assert(!NewTypeParm->hasDefaultArgument() &&
1064 "Parameter packs can't have a default argument!");
1065 SawParameterPack = true;
1066 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001067 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001068 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001069 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1070 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1071 SawDefaultArgument = true;
1072 RedundantDefaultArg = true;
1073 PreviousDefaultArgLoc = NewDefaultLoc;
1074 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1075 // Merge the default argument from the old declaration to the
1076 // new declaration.
1077 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001078 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001079 true);
1080 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1081 } else if (NewTypeParm->hasDefaultArgument()) {
1082 SawDefaultArgument = true;
1083 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1084 } else if (SawDefaultArgument)
1085 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001086 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001087 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001088 // Check the presence of a default argument here.
1089 if (NewNonTypeParm->hasDefaultArgument() &&
1090 DiagnoseDefaultTemplateArgument(*this, TPC,
1091 NewNonTypeParm->getLocation(),
1092 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1093 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1094 NewNonTypeParm->setDefaultArgument(0);
1095 }
1096
Mike Stump12b8ce12009-08-04 21:02:39 +00001097 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001098 NonTypeTemplateParmDecl *OldNonTypeParm
1099 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001100 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001101 NewNonTypeParm->hasDefaultArgument()) {
1102 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1103 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1104 SawDefaultArgument = true;
1105 RedundantDefaultArg = true;
1106 PreviousDefaultArgLoc = NewDefaultLoc;
1107 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1108 // Merge the default argument from the old declaration to the
1109 // new declaration.
1110 SawDefaultArgument = true;
1111 // FIXME: We need to create a new kind of "default argument"
1112 // expression that points to a previous template template
1113 // parameter.
1114 NewNonTypeParm->setDefaultArgument(
1115 OldNonTypeParm->getDefaultArgument());
1116 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1117 } else if (NewNonTypeParm->hasDefaultArgument()) {
1118 SawDefaultArgument = true;
1119 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1120 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001121 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001122 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001123 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001124 TemplateTemplateParmDecl *NewTemplateParm
1125 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001126 if (NewTemplateParm->hasDefaultArgument() &&
1127 DiagnoseDefaultTemplateArgument(*this, TPC,
1128 NewTemplateParm->getLocation(),
1129 NewTemplateParm->getDefaultArgument().getSourceRange()))
1130 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1131
1132 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001133 TemplateTemplateParmDecl *OldTemplateParm
1134 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001135 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001136 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001137 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1138 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001139 SawDefaultArgument = true;
1140 RedundantDefaultArg = true;
1141 PreviousDefaultArgLoc = NewDefaultLoc;
1142 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1143 // Merge the default argument from the old declaration to the
1144 // new declaration.
1145 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001146 // FIXME: We need to create a new kind of "default argument" expression
1147 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001148 NewTemplateParm->setDefaultArgument(
1149 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001150 PreviousDefaultArgLoc
1151 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001152 } else if (NewTemplateParm->hasDefaultArgument()) {
1153 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001154 PreviousDefaultArgLoc
1155 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001156 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001157 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001158 }
1159
1160 if (RedundantDefaultArg) {
1161 // C++ [temp.param]p12:
1162 // A template-parameter shall not be given default arguments
1163 // by two different declarations in the same scope.
1164 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1165 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1166 Invalid = true;
1167 } else if (MissingDefaultArg) {
1168 // C++ [temp.param]p11:
1169 // If a template-parameter has a default template-argument,
1170 // all subsequent template-parameters shall have a default
1171 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001172 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001173 diag::err_template_param_default_arg_missing);
1174 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1175 Invalid = true;
1176 }
1177
1178 // If we have an old template parameter list that we're merging
1179 // in, move on to the next parameter.
1180 if (OldParams)
1181 ++OldParam;
1182 }
1183
1184 return Invalid;
1185}
Douglas Gregord32e0282009-02-09 23:23:08 +00001186
Mike Stump11289f42009-09-09 15:08:12 +00001187/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001188/// specifier, returning the template parameter list that applies to the
1189/// name.
1190///
1191/// \param DeclStartLoc the start of the declaration that has a scope
1192/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001193///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001194/// \param SS the scope specifier that will be matched to the given template
1195/// parameter lists. This scope specifier precedes a qualified name that is
1196/// being declared.
1197///
1198/// \param ParamLists the template parameter lists, from the outermost to the
1199/// innermost template parameter lists.
1200///
1201/// \param NumParamLists the number of template parameter lists in ParamLists.
1202///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001203/// \param IsExplicitSpecialization will be set true if the entity being
1204/// declared is an explicit specialization, false otherwise.
1205///
Mike Stump11289f42009-09-09 15:08:12 +00001206/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001207/// name that is preceded by the scope specifier @p SS. This template
1208/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001209/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001210/// template specialization), or may be NULL (if we were's declaring isn't
1211/// itself a template).
1212TemplateParameterList *
1213Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1214 const CXXScopeSpec &SS,
1215 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001216 unsigned NumParamLists,
1217 bool &IsExplicitSpecialization) {
1218 IsExplicitSpecialization = false;
1219
Douglas Gregord8d297c2009-07-21 23:53:31 +00001220 // Find the template-ids that occur within the nested-name-specifier. These
1221 // template-ids will match up with the template parameter lists.
1222 llvm::SmallVector<const TemplateSpecializationType *, 4>
1223 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001224 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1225 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001226 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1227 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001228 const Type *T = NNS->getAsType();
1229 if (!T) break;
1230
1231 // C++0x [temp.expl.spec]p17:
1232 // A member or a member template may be nested within many
1233 // enclosing class templates. In an explicit specialization for
1234 // such a member, the member declaration shall be preceded by a
1235 // template<> for each enclosing class template that is
1236 // explicitly specialized.
1237 // We interpret this as forbidding typedefs of template
1238 // specializations in the scope specifiers of out-of-line decls.
1239 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) {
1240 const Type *UnderlyingT = TT->LookThroughTypedefs().getTypePtr();
1241 if (isa<TemplateSpecializationType>(UnderlyingT))
1242 // FIXME: better source location information.
1243 Diag(DeclStartLoc, diag::err_typedef_in_def_scope) << QualType(T,0);
1244 T = UnderlyingT;
1245 }
1246
Mike Stump11289f42009-09-09 15:08:12 +00001247 if (const TemplateSpecializationType *SpecType
John McCall90034062009-12-15 02:19:47 +00001248 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001249 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1250 if (!Template)
1251 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001252
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001253 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001254 ClassTemplateSpecializationDecl *SpecDecl
1255 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1256 // If the nested name specifier refers to an explicit specialization,
1257 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001258 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1259 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001260 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001261 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001262 }
Mike Stump11289f42009-09-09 15:08:12 +00001263
Douglas Gregord8d297c2009-07-21 23:53:31 +00001264 TemplateIdsInSpecifier.push_back(SpecType);
1265 }
1266 }
Mike Stump11289f42009-09-09 15:08:12 +00001267
Douglas Gregord8d297c2009-07-21 23:53:31 +00001268 // Reverse the list of template-ids in the scope specifier, so that we can
1269 // more easily match up the template-ids and the template parameter lists.
1270 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001271
Douglas Gregord8d297c2009-07-21 23:53:31 +00001272 SourceLocation FirstTemplateLoc = DeclStartLoc;
1273 if (NumParamLists)
1274 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001275
Douglas Gregord8d297c2009-07-21 23:53:31 +00001276 // Match the template-ids found in the specifier to the template parameter
1277 // lists.
1278 unsigned Idx = 0;
1279 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1280 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001281 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1282 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001283 if (Idx >= NumParamLists) {
1284 // We have a template-id without a corresponding template parameter
1285 // list.
1286 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001287 // FIXME: the location information here isn't great.
1288 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001289 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001290 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001291 << SS.getRange();
1292 } else {
1293 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1294 << SS.getRange()
1295 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1296 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001297 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001298 }
1299 return 0;
1300 }
Mike Stump11289f42009-09-09 15:08:12 +00001301
Douglas Gregord8d297c2009-07-21 23:53:31 +00001302 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001303 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001304 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001305 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1306
Mike Stump11289f42009-09-09 15:08:12 +00001307 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001308 = dyn_cast<ClassTemplateDecl>(Template)) {
1309 TemplateParameterList *ExpectedTemplateParams = 0;
1310 // Is this template-id naming the primary template?
1311 if (Context.hasSameType(TemplateId,
1312 ClassTemplate->getInjectedClassNameType(Context)))
1313 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1314 // ... or a partial specialization?
1315 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1316 = ClassTemplate->findPartialSpecialization(TemplateId))
1317 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1318
1319 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001320 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001321 ExpectedTemplateParams,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001322 true, TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00001323 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001324
1325 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001326 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001327 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001328 diag::err_template_param_list_matches_nontemplate)
1329 << TemplateId
1330 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001331 else
1332 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001333 }
Mike Stump11289f42009-09-09 15:08:12 +00001334
Douglas Gregord8d297c2009-07-21 23:53:31 +00001335 // If there were at least as many template-ids as there were template
1336 // parameter lists, then there are no template parameter lists remaining for
1337 // the declaration itself.
1338 if (Idx >= NumParamLists)
1339 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001340
Douglas Gregord8d297c2009-07-21 23:53:31 +00001341 // If there were too many template parameter lists, complain about that now.
1342 if (Idx != NumParamLists - 1) {
1343 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001344 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001345 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001346 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1347 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001348 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1349 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001350
1351 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1352 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1353 diag::note_explicit_template_spec_does_not_need_header)
1354 << ExplicitSpecializationsInSpecifier.back();
1355 ExplicitSpecializationsInSpecifier.pop_back();
1356 }
1357
Douglas Gregord8d297c2009-07-21 23:53:31 +00001358 ++Idx;
1359 }
1360 }
Mike Stump11289f42009-09-09 15:08:12 +00001361
Douglas Gregord8d297c2009-07-21 23:53:31 +00001362 // Return the last template parameter list, which corresponds to the
1363 // entity being declared.
1364 return ParamLists[NumParamLists - 1];
1365}
1366
Douglas Gregordc572a32009-03-30 22:58:21 +00001367QualType Sema::CheckTemplateIdType(TemplateName Name,
1368 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001369 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001370 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001371 if (!Template) {
1372 // The template name does not resolve to a template, so we just
1373 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001374 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001375 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001376
Douglas Gregorc40290e2009-03-09 23:48:35 +00001377 // Check that the template argument list is well-formed for this
1378 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001379 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001380 TemplateArgs.size());
1381 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001382 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001383 return QualType();
1384
Mike Stump11289f42009-09-09 15:08:12 +00001385 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001386 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001387 "Converted template argument list is too short!");
1388
1389 QualType CanonType;
1390
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001391 if (Name.isDependent() ||
1392 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001393 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001394 // This class template specialization is a dependent
1395 // type. Therefore, its canonical type is another class template
1396 // specialization type that contains all of the converted
1397 // arguments in canonical form. This ensures that, e.g., A<T> and
1398 // A<T, T> have identical types when A is declared as:
1399 //
1400 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001401 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001402 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001403 Converted.getFlatArguments(),
1404 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001405
Douglas Gregora8e02e72009-07-28 23:00:59 +00001406 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001407 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001408 // In the future, we need to teach getTemplateSpecializationType to only
1409 // build the canonical type and return that to us.
1410 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001411 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001412 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001413 // Find the class template specialization declaration that
1414 // corresponds to these arguments.
1415 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001416 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001417 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001418 Converted.flatSize(),
1419 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001420 void *InsertPos = 0;
1421 ClassTemplateSpecializationDecl *Decl
1422 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1423 if (!Decl) {
1424 // This is the first time we have referenced this class template
1425 // specialization. Create the canonical declaration and add it to
1426 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001427 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001428 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001429 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001430 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001431 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001432 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1433 Decl->setLexicalDeclContext(CurContext);
1434 }
1435
1436 CanonType = Context.getTypeDeclType(Decl);
1437 }
Mike Stump11289f42009-09-09 15:08:12 +00001438
Douglas Gregorc40290e2009-03-09 23:48:35 +00001439 // Build the fully-sugared type for this class template
1440 // specialization, which refers back to the class template
1441 // specialization we created or found.
John McCall6b51f282009-11-23 01:53:49 +00001442 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001443}
1444
Douglas Gregor67a65642009-02-17 23:15:12 +00001445Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001446Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001447 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001448 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001449 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001450 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001451
Douglas Gregorc40290e2009-03-09 23:48:35 +00001452 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001453 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001454 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001455
John McCall6b51f282009-11-23 01:53:49 +00001456 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001457 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001458
1459 if (Result.isNull())
1460 return true;
1461
John McCallbcd03502009-12-07 02:54:59 +00001462 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001463 TemplateSpecializationTypeLoc TL
1464 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1465 TL.setTemplateNameLoc(TemplateLoc);
1466 TL.setLAngleLoc(LAngleLoc);
1467 TL.setRAngleLoc(RAngleLoc);
1468 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1469 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1470
1471 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001472}
John McCall06f6fe8d2009-09-04 01:14:41 +00001473
John McCalld8fe9af2009-09-08 17:47:29 +00001474Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1475 TagUseKind TUK,
1476 DeclSpec::TST TagSpec,
1477 SourceLocation TagLoc) {
1478 if (TypeResult.isInvalid())
1479 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001480
John McCall0ad16662009-10-29 08:12:44 +00001481 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001482 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001483 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001484
John McCalld8fe9af2009-09-08 17:47:29 +00001485 // Verify the tag specifier.
1486 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001487
John McCalld8fe9af2009-09-08 17:47:29 +00001488 if (const RecordType *RT = Type->getAs<RecordType>()) {
1489 RecordDecl *D = RT->getDecl();
1490
1491 IdentifierInfo *Id = D->getIdentifier();
1492 assert(Id && "templated class must have an identifier");
1493
1494 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1495 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001496 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001497 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1498 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001499 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001500 }
1501 }
1502
John McCalld8fe9af2009-09-08 17:47:29 +00001503 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1504
1505 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001506}
1507
John McCalle66edc12009-11-24 19:00:30 +00001508Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1509 LookupResult &R,
1510 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001511 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001512 // FIXME: Can we do any checking at this point? I guess we could check the
1513 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001514 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001515 // though.
John McCalle66edc12009-11-24 19:00:30 +00001516
1517 // These should be filtered out by our callers.
1518 assert(!R.empty() && "empty lookup results when building templateid");
1519 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1520
1521 NestedNameSpecifier *Qualifier = 0;
1522 SourceRange QualifierRange;
1523 if (SS.isSet()) {
1524 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1525 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001526 }
1527
John McCalle66edc12009-11-24 19:00:30 +00001528 bool Dependent
1529 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1530 &TemplateArgs);
1531 UnresolvedLookupExpr *ULE
1532 = UnresolvedLookupExpr::Create(Context, Dependent,
1533 Qualifier, QualifierRange,
1534 R.getLookupName(), R.getNameLoc(),
1535 RequiresADL, TemplateArgs);
1536 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1537 ULE->addDecl(*I);
1538
1539 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001540}
1541
John McCalle66edc12009-11-24 19:00:30 +00001542// We actually only call this from template instantiation.
1543Sema::OwningExprResult
1544Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1545 DeclarationName Name,
1546 SourceLocation NameLoc,
1547 const TemplateArgumentListInfo &TemplateArgs) {
1548 DeclContext *DC;
1549 if (!(DC = computeDeclContext(SS, false)) ||
1550 DC->isDependentContext() ||
1551 RequireCompleteDeclContext(SS))
1552 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001553
John McCalle66edc12009-11-24 19:00:30 +00001554 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1555 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00001556
John McCalle66edc12009-11-24 19:00:30 +00001557 if (R.isAmbiguous())
1558 return ExprError();
1559
1560 if (R.empty()) {
1561 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1562 << Name << SS.getRange();
1563 return ExprError();
1564 }
1565
1566 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1567 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1568 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1569 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1570 return ExprError();
1571 }
1572
1573 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001574}
1575
Douglas Gregorb67535d2009-03-31 00:43:58 +00001576/// \brief Form a dependent template name.
1577///
1578/// This action forms a dependent template name given the template
1579/// name and its (presumably dependent) scope specifier. For
1580/// example, given "MetaFun::template apply", the scope specifier \p
1581/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1582/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001583Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001584Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001585 const CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001586 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001587 TypeTy *ObjectType,
1588 bool EnteringContext) {
Mike Stump11289f42009-09-09 15:08:12 +00001589 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001590 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001591 (SS.isSet() && computeDeclContext(SS, EnteringContext))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001592 // C++0x [temp.names]p5:
1593 // If a name prefixed by the keyword template is not the name of
1594 // a template, the program is ill-formed. [Note: the keyword
1595 // template may not be applied to non-template members of class
1596 // templates. -end note ] [ Note: as is the case with the
1597 // typename prefix, the template prefix is allowed in cases
1598 // where it is not strictly necessary; i.e., when the
1599 // nested-name-specifier or the expression on the left of the ->
1600 // or . is not dependent on a template-parameter, or the use
1601 // does not appear in the scope of a template. -end note]
1602 //
1603 // Note: C++03 was more strict here, because it banned the use of
1604 // the "template" keyword prior to a template-name that was not a
1605 // dependent name. C++ DR468 relaxed this requirement (the
1606 // "template" keyword is now permitted). We follow the C++0x
1607 // rules, even in C++03 mode, retroactively applying the DR.
1608 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001609 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001610 EnteringContext, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001611 if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001612 Diag(Name.getSourceRange().getBegin(),
1613 diag::err_template_kw_refers_to_non_template)
1614 << GetNameFromUnqualifiedId(Name)
1615 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001616 return TemplateTy();
1617 }
1618
1619 return Template;
1620 }
1621
Mike Stump11289f42009-09-09 15:08:12 +00001622 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001623 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001624
1625 switch (Name.getKind()) {
1626 case UnqualifiedId::IK_Identifier:
1627 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1628 Name.Identifier));
1629
Douglas Gregor71395fa2009-11-04 00:56:37 +00001630 case UnqualifiedId::IK_OperatorFunctionId:
1631 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1632 Name.OperatorFunctionId.Operator));
Alexis Hunted0530f2009-11-28 08:58:14 +00001633
1634 case UnqualifiedId::IK_LiteralOperatorId:
1635 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1636
Douglas Gregor3cf81312009-11-03 23:16:33 +00001637 default:
1638 break;
1639 }
1640
1641 Diag(Name.getSourceRange().getBegin(),
1642 diag::err_template_kw_refers_to_non_template)
1643 << GetNameFromUnqualifiedId(Name)
1644 << Name.getSourceRange();
1645 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001646}
1647
Mike Stump11289f42009-09-09 15:08:12 +00001648bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001649 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001650 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001651 const TemplateArgument &Arg = AL.getArgument();
1652
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001653 // Check template type parameter.
1654 if (Arg.getKind() != TemplateArgument::Type) {
1655 // C++ [temp.arg.type]p1:
1656 // A template-argument for a template-parameter which is a
1657 // type shall be a type-id.
1658
1659 // We have a template type parameter but the template argument
1660 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001661 SourceRange SR = AL.getSourceRange();
1662 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001663 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001664
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001665 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001666 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001667
John McCallbcd03502009-12-07 02:54:59 +00001668 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001669 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001670
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001671 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001672 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001673 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001674 return false;
1675}
1676
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001677/// \brief Substitute template arguments into the default template argument for
1678/// the given template type parameter.
1679///
1680/// \param SemaRef the semantic analysis object for which we are performing
1681/// the substitution.
1682///
1683/// \param Template the template that we are synthesizing template arguments
1684/// for.
1685///
1686/// \param TemplateLoc the location of the template name that started the
1687/// template-id we are checking.
1688///
1689/// \param RAngleLoc the location of the right angle bracket ('>') that
1690/// terminates the template-id.
1691///
1692/// \param Param the template template parameter whose default we are
1693/// substituting into.
1694///
1695/// \param Converted the list of template arguments provided for template
1696/// parameters that precede \p Param in the template parameter list.
1697///
1698/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001699static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001700SubstDefaultTemplateArgument(Sema &SemaRef,
1701 TemplateDecl *Template,
1702 SourceLocation TemplateLoc,
1703 SourceLocation RAngleLoc,
1704 TemplateTypeParmDecl *Param,
1705 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001706 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001707
1708 // If the argument type is dependent, instantiate it now based
1709 // on the previously-computed template arguments.
1710 if (ArgType->getType()->isDependentType()) {
1711 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1712 /*TakeArgs=*/false);
1713
1714 MultiLevelTemplateArgumentList AllTemplateArgs
1715 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1716
1717 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1718 Template, Converted.getFlatArguments(),
1719 Converted.flatSize(),
1720 SourceRange(TemplateLoc, RAngleLoc));
1721
1722 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1723 Param->getDefaultArgumentLoc(),
1724 Param->getDeclName());
1725 }
1726
1727 return ArgType;
1728}
1729
1730/// \brief Substitute template arguments into the default template argument for
1731/// the given non-type template parameter.
1732///
1733/// \param SemaRef the semantic analysis object for which we are performing
1734/// the substitution.
1735///
1736/// \param Template the template that we are synthesizing template arguments
1737/// for.
1738///
1739/// \param TemplateLoc the location of the template name that started the
1740/// template-id we are checking.
1741///
1742/// \param RAngleLoc the location of the right angle bracket ('>') that
1743/// terminates the template-id.
1744///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001745/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001746/// substituting into.
1747///
1748/// \param Converted the list of template arguments provided for template
1749/// parameters that precede \p Param in the template parameter list.
1750///
1751/// \returns the substituted template argument, or NULL if an error occurred.
1752static Sema::OwningExprResult
1753SubstDefaultTemplateArgument(Sema &SemaRef,
1754 TemplateDecl *Template,
1755 SourceLocation TemplateLoc,
1756 SourceLocation RAngleLoc,
1757 NonTypeTemplateParmDecl *Param,
1758 TemplateArgumentListBuilder &Converted) {
1759 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1760 /*TakeArgs=*/false);
1761
1762 MultiLevelTemplateArgumentList AllTemplateArgs
1763 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1764
1765 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1766 Template, Converted.getFlatArguments(),
1767 Converted.flatSize(),
1768 SourceRange(TemplateLoc, RAngleLoc));
1769
1770 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1771}
1772
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001773/// \brief Substitute template arguments into the default template argument for
1774/// the given template template parameter.
1775///
1776/// \param SemaRef the semantic analysis object for which we are performing
1777/// the substitution.
1778///
1779/// \param Template the template that we are synthesizing template arguments
1780/// for.
1781///
1782/// \param TemplateLoc the location of the template name that started the
1783/// template-id we are checking.
1784///
1785/// \param RAngleLoc the location of the right angle bracket ('>') that
1786/// terminates the template-id.
1787///
1788/// \param Param the template template parameter whose default we are
1789/// substituting into.
1790///
1791/// \param Converted the list of template arguments provided for template
1792/// parameters that precede \p Param in the template parameter list.
1793///
1794/// \returns the substituted template argument, or NULL if an error occurred.
1795static TemplateName
1796SubstDefaultTemplateArgument(Sema &SemaRef,
1797 TemplateDecl *Template,
1798 SourceLocation TemplateLoc,
1799 SourceLocation RAngleLoc,
1800 TemplateTemplateParmDecl *Param,
1801 TemplateArgumentListBuilder &Converted) {
1802 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1803 /*TakeArgs=*/false);
1804
1805 MultiLevelTemplateArgumentList AllTemplateArgs
1806 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1807
1808 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1809 Template, Converted.getFlatArguments(),
1810 Converted.flatSize(),
1811 SourceRange(TemplateLoc, RAngleLoc));
1812
1813 return SemaRef.SubstTemplateName(
1814 Param->getDefaultArgument().getArgument().getAsTemplate(),
1815 Param->getDefaultArgument().getTemplateNameLoc(),
1816 AllTemplateArgs);
1817}
1818
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001819/// \brief If the given template parameter has a default template
1820/// argument, substitute into that default template argument and
1821/// return the corresponding template argument.
1822TemplateArgumentLoc
1823Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1824 SourceLocation TemplateLoc,
1825 SourceLocation RAngleLoc,
1826 Decl *Param,
1827 TemplateArgumentListBuilder &Converted) {
1828 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1829 if (!TypeParm->hasDefaultArgument())
1830 return TemplateArgumentLoc();
1831
John McCallbcd03502009-12-07 02:54:59 +00001832 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001833 TemplateLoc,
1834 RAngleLoc,
1835 TypeParm,
1836 Converted);
1837 if (DI)
1838 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1839
1840 return TemplateArgumentLoc();
1841 }
1842
1843 if (NonTypeTemplateParmDecl *NonTypeParm
1844 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1845 if (!NonTypeParm->hasDefaultArgument())
1846 return TemplateArgumentLoc();
1847
1848 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1849 TemplateLoc,
1850 RAngleLoc,
1851 NonTypeParm,
1852 Converted);
1853 if (Arg.isInvalid())
1854 return TemplateArgumentLoc();
1855
1856 Expr *ArgE = Arg.takeAs<Expr>();
1857 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1858 }
1859
1860 TemplateTemplateParmDecl *TempTempParm
1861 = cast<TemplateTemplateParmDecl>(Param);
1862 if (!TempTempParm->hasDefaultArgument())
1863 return TemplateArgumentLoc();
1864
1865 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1866 TemplateLoc,
1867 RAngleLoc,
1868 TempTempParm,
1869 Converted);
1870 if (TName.isNull())
1871 return TemplateArgumentLoc();
1872
1873 return TemplateArgumentLoc(TemplateArgument(TName),
1874 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1875 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1876}
1877
Douglas Gregorda0fb532009-11-11 19:31:23 +00001878/// \brief Check that the given template argument corresponds to the given
1879/// template parameter.
1880bool Sema::CheckTemplateArgument(NamedDecl *Param,
1881 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001882 TemplateDecl *Template,
1883 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001884 SourceLocation RAngleLoc,
1885 TemplateArgumentListBuilder &Converted) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001886 // Check template type parameters.
1887 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001888 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001889
Douglas Gregoreebed722009-11-11 19:41:09 +00001890 // Check non-type template parameters.
1891 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001892 // Do substitution on the type of the non-type template parameter
1893 // with the template arguments we've seen thus far.
1894 QualType NTTPType = NTTP->getType();
1895 if (NTTPType->isDependentType()) {
1896 // Do substitution on the type of the non-type template parameter.
1897 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1898 NTTP, Converted.getFlatArguments(),
1899 Converted.flatSize(),
1900 SourceRange(TemplateLoc, RAngleLoc));
1901
1902 TemplateArgumentList TemplateArgs(Context, Converted,
1903 /*TakeArgs=*/false);
1904 NTTPType = SubstType(NTTPType,
1905 MultiLevelTemplateArgumentList(TemplateArgs),
1906 NTTP->getLocation(),
1907 NTTP->getDeclName());
1908 // If that worked, check the non-type template parameter type
1909 // for validity.
1910 if (!NTTPType.isNull())
1911 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1912 NTTP->getLocation());
1913 if (NTTPType.isNull())
1914 return true;
1915 }
1916
1917 switch (Arg.getArgument().getKind()) {
1918 case TemplateArgument::Null:
1919 assert(false && "Should never see a NULL template argument here");
1920 return true;
1921
1922 case TemplateArgument::Expression: {
1923 Expr *E = Arg.getArgument().getAsExpr();
1924 TemplateArgument Result;
1925 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1926 return true;
1927
1928 Converted.Append(Result);
1929 break;
1930 }
1931
1932 case TemplateArgument::Declaration:
1933 case TemplateArgument::Integral:
1934 // We've already checked this template argument, so just copy
1935 // it to the list of converted arguments.
1936 Converted.Append(Arg.getArgument());
1937 break;
1938
1939 case TemplateArgument::Template:
1940 // We were given a template template argument. It may not be ill-formed;
1941 // see below.
1942 if (DependentTemplateName *DTN
1943 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1944 // We have a template argument such as \c T::template X, which we
1945 // parsed as a template template argument. However, since we now
1946 // know that we need a non-type template argument, convert this
1947 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00001948 Expr *E = DependentScopeDeclRefExpr::Create(Context,
1949 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00001950 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00001951 DTN->getIdentifier(),
1952 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00001953
1954 TemplateArgument Result;
1955 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1956 return true;
1957
1958 Converted.Append(Result);
1959 break;
1960 }
1961
1962 // We have a template argument that actually does refer to a class
1963 // template, template alias, or template template parameter, and
1964 // therefore cannot be a non-type template argument.
1965 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1966 << Arg.getSourceRange();
1967
1968 Diag(Param->getLocation(), diag::note_template_param_here);
1969 return true;
1970
1971 case TemplateArgument::Type: {
1972 // We have a non-type template parameter but the template
1973 // argument is a type.
1974
1975 // C++ [temp.arg]p2:
1976 // In a template-argument, an ambiguity between a type-id and
1977 // an expression is resolved to a type-id, regardless of the
1978 // form of the corresponding template-parameter.
1979 //
1980 // We warn specifically about this case, since it can be rather
1981 // confusing for users.
1982 QualType T = Arg.getArgument().getAsType();
1983 SourceRange SR = Arg.getSourceRange();
1984 if (T->isFunctionType())
1985 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1986 else
1987 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1988 Diag(Param->getLocation(), diag::note_template_param_here);
1989 return true;
1990 }
1991
1992 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001993 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00001994 break;
1995 }
1996
1997 return false;
1998 }
1999
2000
2001 // Check template template parameters.
2002 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2003
2004 // Substitute into the template parameter list of the template
2005 // template parameter, since previously-supplied template arguments
2006 // may appear within the template template parameter.
2007 {
2008 // Set up a template instantiation context.
2009 LocalInstantiationScope Scope(*this);
2010 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2011 TempParm, Converted.getFlatArguments(),
2012 Converted.flatSize(),
2013 SourceRange(TemplateLoc, RAngleLoc));
2014
2015 TemplateArgumentList TemplateArgs(Context, Converted,
2016 /*TakeArgs=*/false);
2017 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2018 SubstDecl(TempParm, CurContext,
2019 MultiLevelTemplateArgumentList(TemplateArgs)));
2020 if (!TempParm)
2021 return true;
2022
2023 // FIXME: TempParam is leaked.
2024 }
2025
2026 switch (Arg.getArgument().getKind()) {
2027 case TemplateArgument::Null:
2028 assert(false && "Should never see a NULL template argument here");
2029 return true;
2030
2031 case TemplateArgument::Template:
2032 if (CheckTemplateArgument(TempParm, Arg))
2033 return true;
2034
2035 Converted.Append(Arg.getArgument());
2036 break;
2037
2038 case TemplateArgument::Expression:
2039 case TemplateArgument::Type:
2040 // We have a template template parameter but the template
2041 // argument does not refer to a template.
2042 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2043 return true;
2044
2045 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002046 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002047 "Declaration argument with template template parameter");
2048 break;
2049 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002050 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002051 "Integral argument with template template parameter");
2052 break;
2053
2054 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002055 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002056 break;
2057 }
2058
2059 return false;
2060}
2061
Douglas Gregord32e0282009-02-09 23:23:08 +00002062/// \brief Check that the given template argument list is well-formed
2063/// for specializing the given template.
2064bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2065 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002066 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002067 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002068 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002069 TemplateParameterList *Params = Template->getTemplateParameters();
2070 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002071 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002072 bool Invalid = false;
2073
John McCall6b51f282009-11-23 01:53:49 +00002074 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2075
Mike Stump11289f42009-09-09 15:08:12 +00002076 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002077 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002078
Anders Carlsson15201f12009-06-13 02:08:00 +00002079 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002080 (NumArgs < Params->getMinRequiredArguments() &&
2081 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002082 // FIXME: point at either the first arg beyond what we can handle,
2083 // or the '>', depending on whether we have too many or too few
2084 // arguments.
2085 SourceRange Range;
2086 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002087 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002088 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2089 << (NumArgs > NumParams)
2090 << (isa<ClassTemplateDecl>(Template)? 0 :
2091 isa<FunctionTemplateDecl>(Template)? 1 :
2092 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2093 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002094 Diag(Template->getLocation(), diag::note_template_decl_here)
2095 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002096 Invalid = true;
2097 }
Mike Stump11289f42009-09-09 15:08:12 +00002098
2099 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002100 // [...] The type and form of each template-argument specified in
2101 // a template-id shall match the type and form specified for the
2102 // corresponding parameter declared by the template in its
2103 // template-parameter-list.
2104 unsigned ArgIdx = 0;
2105 for (TemplateParameterList::iterator Param = Params->begin(),
2106 ParamEnd = Params->end();
2107 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002108 if (ArgIdx > NumArgs && PartialTemplateArgs)
2109 break;
Mike Stump11289f42009-09-09 15:08:12 +00002110
Douglas Gregoreebed722009-11-11 19:41:09 +00002111 // If we have a template parameter pack, check every remaining template
2112 // argument against that template parameter pack.
2113 if ((*Param)->isTemplateParameterPack()) {
2114 Converted.BeginPack();
2115 for (; ArgIdx < NumArgs; ++ArgIdx) {
2116 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2117 TemplateLoc, RAngleLoc, Converted)) {
2118 Invalid = true;
2119 break;
2120 }
2121 }
2122 Converted.EndPack();
2123 continue;
2124 }
2125
Douglas Gregor84d49a22009-11-11 21:54:23 +00002126 if (ArgIdx < NumArgs) {
2127 // Check the template argument we were given.
2128 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2129 TemplateLoc, RAngleLoc, Converted))
2130 return true;
2131
2132 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002133 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002134
Douglas Gregor84d49a22009-11-11 21:54:23 +00002135 // We have a default template argument that we will use.
2136 TemplateArgumentLoc Arg;
2137
2138 // Retrieve the default template argument from the template
2139 // parameter. For each kind of template parameter, we substitute the
2140 // template arguments provided thus far and any "outer" template arguments
2141 // (when the template parameter was part of a nested template) into
2142 // the default argument.
2143 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2144 if (!TTP->hasDefaultArgument()) {
2145 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2146 break;
2147 }
2148
John McCallbcd03502009-12-07 02:54:59 +00002149 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002150 Template,
2151 TemplateLoc,
2152 RAngleLoc,
2153 TTP,
2154 Converted);
2155 if (!ArgType)
2156 return true;
2157
2158 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2159 ArgType);
2160 } else if (NonTypeTemplateParmDecl *NTTP
2161 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2162 if (!NTTP->hasDefaultArgument()) {
2163 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2164 break;
2165 }
2166
2167 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2168 TemplateLoc,
2169 RAngleLoc,
2170 NTTP,
2171 Converted);
2172 if (E.isInvalid())
2173 return true;
2174
2175 Expr *Ex = E.takeAs<Expr>();
2176 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2177 } else {
2178 TemplateTemplateParmDecl *TempParm
2179 = cast<TemplateTemplateParmDecl>(*Param);
2180
2181 if (!TempParm->hasDefaultArgument()) {
2182 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2183 break;
2184 }
2185
2186 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2187 TemplateLoc,
2188 RAngleLoc,
2189 TempParm,
2190 Converted);
2191 if (Name.isNull())
2192 return true;
2193
2194 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2195 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2196 TempParm->getDefaultArgument().getTemplateNameLoc());
2197 }
2198
2199 // Introduce an instantiation record that describes where we are using
2200 // the default template argument.
2201 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2202 Converted.getFlatArguments(),
2203 Converted.flatSize(),
2204 SourceRange(TemplateLoc, RAngleLoc));
2205
2206 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002207 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002208 RAngleLoc, Converted))
2209 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002210 }
2211
2212 return Invalid;
2213}
2214
2215/// \brief Check a template argument against its corresponding
2216/// template type parameter.
2217///
2218/// This routine implements the semantics of C++ [temp.arg.type]. It
2219/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002220bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002221 TypeSourceInfo *ArgInfo) {
2222 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002223 QualType Arg = ArgInfo->getType();
2224
Douglas Gregord32e0282009-02-09 23:23:08 +00002225 // C++ [temp.arg.type]p2:
2226 // A local type, a type with no linkage, an unnamed type or a type
2227 // compounded from any of these types shall not be used as a
2228 // template-argument for a template type-parameter.
2229 //
2230 // FIXME: Perform the recursive and no-linkage type checks.
2231 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002232 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002233 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002234 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002235 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002236 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2237 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2238 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2239 << QualType(Tag, 0) << SR;
2240 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002241 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002242 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2243 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002244 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2245 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002246 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2247 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2248 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002249 }
2250
2251 return false;
2252}
2253
Douglas Gregorccb07762009-02-11 19:52:55 +00002254/// \brief Checks whether the given template argument is the address
2255/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002256bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2257 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002258 bool Invalid = false;
2259
2260 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002261 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002262 Arg = Cast->getSubExpr();
2263
Sebastian Redl576fd422009-05-10 18:38:11 +00002264 // C++0x allows nullptr, and there's no further checking to be done for that.
2265 if (Arg->getType()->isNullPtrType())
2266 return false;
2267
Douglas Gregorccb07762009-02-11 19:52:55 +00002268 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002269 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002270 // A template-argument for a non-type, non-template
2271 // template-parameter shall be one of: [...]
2272 //
2273 // -- the address of an object or function with external
2274 // linkage, including function templates and function
2275 // template-ids but excluding non-static class members,
2276 // expressed as & id-expression where the & is optional if
2277 // the name refers to a function or array, or if the
2278 // corresponding template-parameter is a reference; or
2279 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002280
Douglas Gregorccb07762009-02-11 19:52:55 +00002281 // Ignore (and complain about) any excess parentheses.
2282 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2283 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002284 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002285 diag::err_template_arg_extra_parens)
2286 << Arg->getSourceRange();
2287 Invalid = true;
2288 }
2289
2290 Arg = Parens->getSubExpr();
2291 }
2292
2293 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2294 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2295 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2296 } else
2297 DRE = dyn_cast<DeclRefExpr>(Arg);
2298
2299 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00002300 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002301 diag::err_template_arg_not_object_or_func_form)
2302 << Arg->getSourceRange();
2303
2304 // Cannot refer to non-static data members
2305 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2306 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2307 << Field << Arg->getSourceRange();
2308
2309 // Cannot refer to non-static member functions
2310 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2311 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00002312 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002313 diag::err_template_arg_method)
2314 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002315
Douglas Gregorccb07762009-02-11 19:52:55 +00002316 // Functions must have external linkage.
2317 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregorf73b2822009-11-25 22:24:25 +00002318 if (Func->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump11289f42009-09-09 15:08:12 +00002319 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002320 diag::err_template_arg_function_not_extern)
2321 << Func << Arg->getSourceRange();
2322 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2323 << true;
2324 return true;
2325 }
2326
2327 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002328 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002329 return Invalid;
2330 }
2331
2332 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregorf73b2822009-11-25 22:24:25 +00002333 if (Var->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump11289f42009-09-09 15:08:12 +00002334 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002335 diag::err_template_arg_object_not_extern)
2336 << Var << Arg->getSourceRange();
2337 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2338 << true;
2339 return true;
2340 }
2341
2342 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002343 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00002344 return Invalid;
2345 }
Mike Stump11289f42009-09-09 15:08:12 +00002346
Douglas Gregorccb07762009-02-11 19:52:55 +00002347 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002348 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002349 diag::err_template_arg_not_object_or_func)
2350 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002351 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002352 diag::note_template_arg_refers_here);
2353 return true;
2354}
2355
2356/// \brief Checks whether the given template argument is a pointer to
2357/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002358bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2359 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002360 bool Invalid = false;
2361
2362 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002363 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002364 Arg = Cast->getSubExpr();
2365
Sebastian Redl576fd422009-05-10 18:38:11 +00002366 // C++0x allows nullptr, and there's no further checking to be done for that.
2367 if (Arg->getType()->isNullPtrType())
2368 return false;
2369
Douglas Gregorccb07762009-02-11 19:52:55 +00002370 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002371 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002372 // A template-argument for a non-type, non-template
2373 // template-parameter shall be one of: [...]
2374 //
2375 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002376 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002377
2378 // Ignore (and complain about) any excess parentheses.
2379 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2380 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002381 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002382 diag::err_template_arg_extra_parens)
2383 << Arg->getSourceRange();
2384 Invalid = true;
2385 }
2386
2387 Arg = Parens->getSubExpr();
2388 }
2389
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002390 // A pointer-to-member constant written &Class::member.
2391 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002392 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2393 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2394 if (DRE && !DRE->getQualifier())
2395 DRE = 0;
2396 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002397 }
2398 // A constant of pointer-to-member type.
2399 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2400 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2401 if (VD->getType()->isMemberPointerType()) {
2402 if (isa<NonTypeTemplateParmDecl>(VD) ||
2403 (isa<VarDecl>(VD) &&
2404 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2405 if (Arg->isTypeDependent() || Arg->isValueDependent())
2406 Converted = TemplateArgument(Arg->Retain());
2407 else
2408 Converted = TemplateArgument(VD->getCanonicalDecl());
2409 return Invalid;
2410 }
2411 }
2412 }
2413
2414 DRE = 0;
2415 }
2416
Douglas Gregorccb07762009-02-11 19:52:55 +00002417 if (!DRE)
2418 return Diag(Arg->getSourceRange().getBegin(),
2419 diag::err_template_arg_not_pointer_to_member_form)
2420 << Arg->getSourceRange();
2421
2422 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2423 assert((isa<FieldDecl>(DRE->getDecl()) ||
2424 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2425 "Only non-static member pointers can make it here");
2426
2427 // Okay: this is the address of a non-static member, and therefore
2428 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002429 if (Arg->isTypeDependent() || Arg->isValueDependent())
2430 Converted = TemplateArgument(Arg->Retain());
2431 else
2432 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002433 return Invalid;
2434 }
2435
2436 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002437 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002438 diag::err_template_arg_not_pointer_to_member_form)
2439 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002440 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002441 diag::note_template_arg_refers_here);
2442 return true;
2443}
2444
Douglas Gregord32e0282009-02-09 23:23:08 +00002445/// \brief Check a template argument against its corresponding
2446/// non-type template parameter.
2447///
Douglas Gregor463421d2009-03-03 04:44:36 +00002448/// This routine implements the semantics of C++ [temp.arg.nontype].
2449/// It returns true if an error occurred, and false otherwise. \p
2450/// InstantiatedParamType is the type of the non-type template
2451/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002452///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002453/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002454bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002455 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002456 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002457 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2458
Douglas Gregor86560402009-02-10 23:36:10 +00002459 // If either the parameter has a dependent type or the argument is
2460 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002461 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00002462 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2463 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002464 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002465 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002466 }
Douglas Gregor86560402009-02-10 23:36:10 +00002467
2468 // C++ [temp.arg.nontype]p5:
2469 // The following conversions are performed on each expression used
2470 // as a non-type template-argument. If a non-type
2471 // template-argument cannot be converted to the type of the
2472 // corresponding template-parameter then the program is
2473 // ill-formed.
2474 //
2475 // -- for a non-type template-parameter of integral or
2476 // enumeration type, integral promotions (4.5) and integral
2477 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002478 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002479 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002480 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002481 // C++ [temp.arg.nontype]p1:
2482 // A template-argument for a non-type, non-template
2483 // template-parameter shall be one of:
2484 //
2485 // -- an integral constant-expression of integral or enumeration
2486 // type; or
2487 // -- the name of a non-type template-parameter; or
2488 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002489 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002490 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002491 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002492 diag::err_template_arg_not_integral_or_enumeral)
2493 << ArgType << Arg->getSourceRange();
2494 Diag(Param->getLocation(), diag::note_template_param_here);
2495 return true;
2496 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002497 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002498 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2499 << ArgType << Arg->getSourceRange();
2500 return true;
2501 }
2502
2503 // FIXME: We need some way to more easily get the unqualified form
2504 // of the types without going all the way to the
2505 // canonical type.
2506 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2507 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2508 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2509 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2510
2511 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002512 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002513 // Okay: no conversion necessary
2514 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2515 !ParamType->isEnumeralType()) {
2516 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002517 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002518 } else {
2519 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002520 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002521 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002522 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002523 Diag(Param->getLocation(), diag::note_template_param_here);
2524 return true;
2525 }
2526
Douglas Gregor52aba872009-03-14 00:20:21 +00002527 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002528 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002529 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002530
2531 if (!Arg->isValueDependent()) {
2532 // Check that an unsigned parameter does not receive a negative
2533 // value.
2534 if (IntegerType->isUnsignedIntegerType()
2535 && (Value.isSigned() && Value.isNegative())) {
2536 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2537 << Value.toString(10) << Param->getType()
2538 << Arg->getSourceRange();
2539 Diag(Param->getLocation(), diag::note_template_param_here);
2540 return true;
2541 }
2542
2543 // Check that we don't overflow the template parameter type.
2544 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Eli Friedman38b9ad82009-12-23 18:44:58 +00002545 unsigned RequiredBits;
2546 if (IntegerType->isUnsignedIntegerType())
2547 RequiredBits = Value.getActiveBits();
2548 else if (Value.isUnsigned())
2549 RequiredBits = Value.getActiveBits() + 1;
2550 else
2551 RequiredBits = Value.getMinSignedBits();
2552 if (RequiredBits > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00002553 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00002554 diag::err_template_arg_too_large)
2555 << Value.toString(10) << Param->getType()
2556 << Arg->getSourceRange();
2557 Diag(Param->getLocation(), diag::note_template_param_here);
2558 return true;
2559 }
2560
2561 if (Value.getBitWidth() != AllowedBits)
2562 Value.extOrTrunc(AllowedBits);
2563 Value.setIsSigned(IntegerType->isSignedIntegerType());
2564 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002565
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002566 // Add the value of this argument to the list of converted
2567 // arguments. We use the bitwidth and signedness of the template
2568 // parameter.
2569 if (Arg->isValueDependent()) {
2570 // The argument is value-dependent. Create a new
2571 // TemplateArgument with the converted expression.
2572 Converted = TemplateArgument(Arg);
2573 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002574 }
2575
John McCall0ad16662009-10-29 08:12:44 +00002576 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002577 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002578 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002579 return false;
2580 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002581
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002582 // Handle pointer-to-function, reference-to-function, and
2583 // pointer-to-member-function all in (roughly) the same way.
2584 if (// -- For a non-type template-parameter of type pointer to
2585 // function, only the function-to-pointer conversion (4.3) is
2586 // applied. If the template-argument represents a set of
2587 // overloaded functions (or a pointer to such), the matching
2588 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002589 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002590 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002591 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002592 // -- For a non-type template-parameter of type reference to
2593 // function, no conversions apply. If the template-argument
2594 // represents a set of overloaded functions, the matching
2595 // function is selected from the set (13.4).
2596 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002597 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002598 // -- For a non-type template-parameter of type pointer to
2599 // member function, no conversions apply. If the
2600 // template-argument represents a set of overloaded member
2601 // functions, the matching member function is selected from
2602 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002603 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002604 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002605 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002606 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002607 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002608 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002609 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002610 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2611 ParamType->isMemberPointerType())) {
2612 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002613 if (ParamType->isMemberPointerType())
2614 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2615 else
2616 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002617 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002618 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002619 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002620 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002621 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002622 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2623 return true;
2624
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002625 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002626 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002627 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002628 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002629 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002630 }
2631 }
2632
Mike Stump11289f42009-09-09 15:08:12 +00002633 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002634 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002635 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002636 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002637 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002638 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002639 Diag(Param->getLocation(), diag::note_template_param_here);
2640 return true;
2641 }
Mike Stump11289f42009-09-09 15:08:12 +00002642
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002643 if (ParamType->isMemberPointerType())
2644 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump11289f42009-09-09 15:08:12 +00002645
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002646 NamedDecl *Entity = 0;
2647 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2648 return true;
2649
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002650 if (Entity)
2651 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002652 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002653 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002654 }
2655
Chris Lattner696197c2009-02-20 21:37:53 +00002656 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002657 // -- for a non-type template-parameter of type pointer to
2658 // object, qualification conversions (4.4) and the
2659 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002660 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002661 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002662 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002663
Sebastian Redl576fd422009-05-10 18:38:11 +00002664 if (ArgType->isNullPtrType()) {
2665 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002666 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002667 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002668 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002669 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002670 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002671
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002672 if (IsQualificationConversion(ArgType, ParamType)) {
2673 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002674 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002675 }
Mike Stump11289f42009-09-09 15:08:12 +00002676
Douglas Gregor1515f762009-02-11 18:22:40 +00002677 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002678 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002679 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002680 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002681 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002682 Diag(Param->getLocation(), diag::note_template_param_here);
2683 return true;
2684 }
Mike Stump11289f42009-09-09 15:08:12 +00002685
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002686 NamedDecl *Entity = 0;
2687 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2688 return true;
2689
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002690 if (Entity)
2691 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002692 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002693 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002694 }
Mike Stump11289f42009-09-09 15:08:12 +00002695
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002696 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002697 // -- For a non-type template-parameter of type reference to
2698 // object, no conversions apply. The type referred to by the
2699 // reference may be more cv-qualified than the (otherwise
2700 // identical) type of the template-argument. The
2701 // template-parameter is bound directly to the
2702 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002703 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002704 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002705
Douglas Gregor1515f762009-02-11 18:22:40 +00002706 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002707 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002708 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002709 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002710 << Arg->getSourceRange();
2711 Diag(Param->getLocation(), diag::note_template_param_here);
2712 return true;
2713 }
2714
Mike Stump11289f42009-09-09 15:08:12 +00002715 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002716 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2717 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002718
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002719 if ((ParamQuals | ArgQuals) != ParamQuals) {
2720 Diag(Arg->getSourceRange().getBegin(),
2721 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002722 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002723 << Arg->getSourceRange();
2724 Diag(Param->getLocation(), diag::note_template_param_here);
2725 return true;
2726 }
Mike Stump11289f42009-09-09 15:08:12 +00002727
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002728 NamedDecl *Entity = 0;
2729 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2730 return true;
2731
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002732 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002733 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002734 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002735 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002736
2737 // -- For a non-type template-parameter of type pointer to data
2738 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002739 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002740 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2741
Douglas Gregor1515f762009-02-11 18:22:40 +00002742 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002743 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002744 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002745 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002746 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002747 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002748 } else {
2749 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002750 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002751 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002752 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002753 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002754 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002755 }
2756
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002757 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002758}
2759
2760/// \brief Check a template argument against its corresponding
2761/// template template parameter.
2762///
2763/// This routine implements the semantics of C++ [temp.arg.template].
2764/// It returns true if an error occurred, and false otherwise.
2765bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002766 const TemplateArgumentLoc &Arg) {
2767 TemplateName Name = Arg.getArgument().getAsTemplate();
2768 TemplateDecl *Template = Name.getAsTemplateDecl();
2769 if (!Template) {
2770 // Any dependent template name is fine.
2771 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2772 return false;
2773 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002774
2775 // C++ [temp.arg.template]p1:
2776 // A template-argument for a template template-parameter shall be
2777 // the name of a class template, expressed as id-expression. Only
2778 // primary class templates are considered when matching the
2779 // template template argument with the corresponding parameter;
2780 // partial specializations are not considered even if their
2781 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002782 //
2783 // Note that we also allow template template parameters here, which
2784 // will happen when we are dealing with, e.g., class template
2785 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002786 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002787 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002788 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002789 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002790 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002791 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002792 << Template;
2793 }
2794
2795 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2796 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002797 true,
2798 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002799 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002800}
2801
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002802/// \brief Determine whether the given template parameter lists are
2803/// equivalent.
2804///
Mike Stump11289f42009-09-09 15:08:12 +00002805/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002806/// source code as part of a new template declaration.
2807///
2808/// \param Old The old template parameter list, typically found via
2809/// name lookup of the template declared with this template parameter
2810/// list.
2811///
2812/// \param Complain If true, this routine will produce a diagnostic if
2813/// the template parameter lists are not equivalent.
2814///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002815/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00002816///
2817/// \param TemplateArgLoc If this source location is valid, then we
2818/// are actually checking the template parameter list of a template
2819/// argument (New) against the template parameter list of its
2820/// corresponding template template parameter (Old). We produce
2821/// slightly different diagnostics in this scenario.
2822///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002823/// \returns True if the template parameter lists are equal, false
2824/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002825bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002826Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2827 TemplateParameterList *Old,
2828 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002829 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002830 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002831 if (Old->size() != New->size()) {
2832 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002833 unsigned NextDiag = diag::err_template_param_list_different_arity;
2834 if (TemplateArgLoc.isValid()) {
2835 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2836 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002837 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002838 Diag(New->getTemplateLoc(), NextDiag)
2839 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002840 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002841 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002842 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002843 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002844 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2845 }
2846
2847 return false;
2848 }
2849
2850 for (TemplateParameterList::iterator OldParm = Old->begin(),
2851 OldParmEnd = Old->end(), NewParm = New->begin();
2852 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2853 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002854 if (Complain) {
2855 unsigned NextDiag = diag::err_template_param_different_kind;
2856 if (TemplateArgLoc.isValid()) {
2857 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2858 NextDiag = diag::note_template_param_different_kind;
2859 }
2860 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002861 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00002862 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002863 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00002864 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002865 return false;
2866 }
2867
2868 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2869 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002870 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00002871 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002872 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2873 // The types of non-type template parameters must agree.
2874 NonTypeTemplateParmDecl *NewNTTP
2875 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002876
2877 // If we are matching a template template argument to a template
2878 // template parameter and one of the non-type template parameter types
2879 // is dependent, then we must wait until template instantiation time
2880 // to actually compare the arguments.
2881 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2882 (OldNTTP->getType()->isDependentType() ||
2883 NewNTTP->getType()->isDependentType()))
2884 continue;
2885
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002886 if (Context.getCanonicalType(OldNTTP->getType()) !=
2887 Context.getCanonicalType(NewNTTP->getType())) {
2888 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002889 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2890 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002891 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002892 diag::err_template_arg_template_params_mismatch);
2893 NextDiag = diag::note_template_nontype_parm_different_type;
2894 }
2895 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002896 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002897 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00002898 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002899 diag::note_template_nontype_parm_prev_declaration)
2900 << OldNTTP->getType();
2901 }
2902 return false;
2903 }
2904 } else {
2905 // The template parameter lists of template template
2906 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00002907 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002908 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002909 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002910 = cast<TemplateTemplateParmDecl>(*OldParm);
2911 TemplateTemplateParmDecl *NewTTP
2912 = cast<TemplateTemplateParmDecl>(*NewParm);
2913 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2914 OldTTP->getTemplateParameters(),
2915 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002916 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00002917 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002918 return false;
2919 }
2920 }
2921
2922 return true;
2923}
2924
2925/// \brief Check whether a template can be declared within this scope.
2926///
2927/// If the template declaration is valid in this scope, returns
2928/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002929bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002930Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002931 // Find the nearest enclosing declaration scope.
2932 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2933 (S->getFlags() & Scope::TemplateParamScope) != 0)
2934 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002935
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002936 // C++ [temp]p2:
2937 // A template-declaration can appear only as a namespace scope or
2938 // class scope declaration.
2939 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002940 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2941 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002942 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002943 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002944
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002945 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002946 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002947
2948 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2949 return false;
2950
Mike Stump11289f42009-09-09 15:08:12 +00002951 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002952 diag::err_template_outside_namespace_or_class_scope)
2953 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002954}
Douglas Gregor67a65642009-02-17 23:15:12 +00002955
Douglas Gregor54888652009-10-07 00:13:32 +00002956/// \brief Determine what kind of template specialization the given declaration
2957/// is.
2958static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2959 if (!D)
2960 return TSK_Undeclared;
2961
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002962 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2963 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00002964 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2965 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002966 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2967 return Var->getTemplateSpecializationKind();
2968
Douglas Gregor54888652009-10-07 00:13:32 +00002969 return TSK_Undeclared;
2970}
2971
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002972/// \brief Check whether a specialization is well-formed in the current
2973/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002974///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002975/// This routine determines whether a template specialization can be declared
2976/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00002977///
2978/// \param S the semantic analysis object for which this check is being
2979/// performed.
2980///
2981/// \param Specialized the entity being specialized or instantiated, which
2982/// may be a kind of template (class template, function template, etc.) or
2983/// a member of a class template (member function, static data member,
2984/// member class).
2985///
2986/// \param PrevDecl the previous declaration of this entity, if any.
2987///
2988/// \param Loc the location of the explicit specialization or instantiation of
2989/// this entity.
2990///
2991/// \param IsPartialSpecialization whether this is a partial specialization of
2992/// a class template.
2993///
Douglas Gregor54888652009-10-07 00:13:32 +00002994/// \returns true if there was an error that we cannot recover from, false
2995/// otherwise.
2996static bool CheckTemplateSpecializationScope(Sema &S,
2997 NamedDecl *Specialized,
2998 NamedDecl *PrevDecl,
2999 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003000 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003001 // Keep these "kind" numbers in sync with the %select statements in the
3002 // various diagnostics emitted by this routine.
3003 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003004 bool isTemplateSpecialization = false;
3005 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003006 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003007 isTemplateSpecialization = true;
3008 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003009 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003010 isTemplateSpecialization = true;
3011 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003012 EntityKind = 3;
3013 else if (isa<VarDecl>(Specialized))
3014 EntityKind = 4;
3015 else if (isa<RecordDecl>(Specialized))
3016 EntityKind = 5;
3017 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003018 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3019 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003020 return true;
3021 }
3022
Douglas Gregorf47b9112009-02-25 22:02:03 +00003023 // C++ [temp.expl.spec]p2:
3024 // An explicit specialization shall be declared in the namespace
3025 // of which the template is a member, or, for member templates, in
3026 // the namespace of which the enclosing class or enclosing class
3027 // template is a member. An explicit specialization of a member
3028 // function, member class or static data member of a class
3029 // template shall be declared in the namespace of which the class
3030 // template is a member. Such a declaration may also be a
3031 // definition. If the declaration is not a definition, the
3032 // specialization may be defined later in the name- space in which
3033 // the explicit specialization was declared, or in a namespace
3034 // that encloses the one in which the explicit specialization was
3035 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003036 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3037 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003038 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003039 return true;
3040 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003041
Douglas Gregor40fb7442009-10-07 17:30:37 +00003042 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3043 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003044 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003045 return true;
3046 }
3047
Douglas Gregore4b05162009-10-07 17:21:34 +00003048 // C++ [temp.class.spec]p6:
3049 // A class template partial specialization may be declared or redeclared
3050 // in any namespace scope in which its definition may be defined (14.5.1
3051 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003052 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003053 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003054 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003055 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003056 if ((!PrevDecl ||
3057 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3058 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3059 // There is no prior declaration of this entity, so this
3060 // specialization must be in the same context as the template
3061 // itself.
3062 if (!DC->Equals(SpecializedContext)) {
3063 if (isa<TranslationUnitDecl>(SpecializedContext))
3064 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3065 << EntityKind << Specialized;
3066 else if (isa<NamespaceDecl>(SpecializedContext))
3067 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3068 << EntityKind << Specialized
3069 << cast<NamedDecl>(SpecializedContext);
3070
3071 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3072 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003073 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003074 }
Douglas Gregor54888652009-10-07 00:13:32 +00003075
3076 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003077 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003078 // Note that HandleDeclarator() performs this check for explicit
3079 // specializations of function templates, static data members, and member
3080 // functions, so we skip the check here for those kinds of entities.
3081 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003082 // Should we refactor that check, so that it occurs later?
3083 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003084 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3085 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003086 if (isa<TranslationUnitDecl>(SpecializedContext))
3087 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3088 << EntityKind << Specialized;
3089 else if (isa<NamespaceDecl>(SpecializedContext))
3090 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3091 << EntityKind << Specialized
3092 << cast<NamedDecl>(SpecializedContext);
3093
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003094 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003095 }
Douglas Gregor54888652009-10-07 00:13:32 +00003096
3097 // FIXME: check for specialization-after-instantiation errors and such.
3098
Douglas Gregorf47b9112009-02-25 22:02:03 +00003099 return false;
3100}
Douglas Gregor54888652009-10-07 00:13:32 +00003101
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003102/// \brief Check the non-type template arguments of a class template
3103/// partial specialization according to C++ [temp.class.spec]p9.
3104///
Douglas Gregor09a30232009-06-12 22:08:06 +00003105/// \param TemplateParams the template parameters of the primary class
3106/// template.
3107///
3108/// \param TemplateArg the template arguments of the class template
3109/// partial specialization.
3110///
3111/// \param MirrorsPrimaryTemplate will be set true if the class
3112/// template partial specialization arguments are identical to the
3113/// implicit template arguments of the primary template. This is not
3114/// necessarily an error (C++0x), and it is left to the caller to diagnose
3115/// this condition when it is an error.
3116///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003117/// \returns true if there was an error, false otherwise.
3118bool Sema::CheckClassTemplatePartialSpecializationArgs(
3119 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003120 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003121 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003122 // FIXME: the interface to this function will have to change to
3123 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003124 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003125
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003126 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003127
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003128 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003129 // Determine whether the template argument list of the partial
3130 // specialization is identical to the implicit argument list of
3131 // the primary template. The caller may need to diagnostic this as
3132 // an error per C++ [temp.class.spec]p9b3.
3133 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003134 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003135 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3136 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003137 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003138 MirrorsPrimaryTemplate = false;
3139 } else if (TemplateTemplateParmDecl *TTP
3140 = dyn_cast<TemplateTemplateParmDecl>(
3141 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003142 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003143 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003144 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003145 if (!ArgDecl ||
3146 ArgDecl->getIndex() != TTP->getIndex() ||
3147 ArgDecl->getDepth() != TTP->getDepth())
3148 MirrorsPrimaryTemplate = false;
3149 }
3150 }
3151
Mike Stump11289f42009-09-09 15:08:12 +00003152 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003153 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003154 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003155 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003156 }
3157
Anders Carlsson40c1d492009-06-13 18:20:51 +00003158 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003159 if (!ArgExpr) {
3160 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003161 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003162 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003163
3164 // C++ [temp.class.spec]p8:
3165 // A non-type argument is non-specialized if it is the name of a
3166 // non-type parameter. All other non-type arguments are
3167 // specialized.
3168 //
3169 // Below, we check the two conditions that only apply to
3170 // specialized non-type arguments, so skip any non-specialized
3171 // arguments.
3172 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003173 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003174 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003175 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003176 (Param->getIndex() != NTTP->getIndex() ||
3177 Param->getDepth() != NTTP->getDepth()))
3178 MirrorsPrimaryTemplate = false;
3179
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003180 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003181 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003182
3183 // C++ [temp.class.spec]p9:
3184 // Within the argument list of a class template partial
3185 // specialization, the following restrictions apply:
3186 // -- A partially specialized non-type argument expression
3187 // shall not involve a template parameter of the partial
3188 // specialization except when the argument expression is a
3189 // simple identifier.
3190 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003191 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003192 diag::err_dependent_non_type_arg_in_partial_spec)
3193 << ArgExpr->getSourceRange();
3194 return true;
3195 }
3196
3197 // -- The type of a template parameter corresponding to a
3198 // specialized non-type argument shall not be dependent on a
3199 // parameter of the specialization.
3200 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003201 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003202 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3203 << Param->getType()
3204 << ArgExpr->getSourceRange();
3205 Diag(Param->getLocation(), diag::note_template_param_here);
3206 return true;
3207 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003208
3209 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003210 }
3211
3212 return false;
3213}
3214
Douglas Gregorc08f4892009-03-25 00:13:59 +00003215Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003216Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3217 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003218 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00003219 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003220 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003221 SourceLocation TemplateNameLoc,
3222 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003223 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003224 SourceLocation RAngleLoc,
3225 AttributeList *Attr,
3226 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003227 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003228
Douglas Gregor67a65642009-02-17 23:15:12 +00003229 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003230 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003231 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003232 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3233
3234 if (!ClassTemplate) {
3235 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3236 << (Name.getAsTemplateDecl() &&
3237 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3238 return true;
3239 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003240
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003241 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003242 bool isPartialSpecialization = false;
3243
Douglas Gregorf47b9112009-02-25 22:02:03 +00003244 // Check the validity of the template headers that introduce this
3245 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003246 // FIXME: We probably shouldn't complain about these headers for
3247 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003248 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003249 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3250 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003251 TemplateParameterLists.size(),
3252 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003253 if (TemplateParams && TemplateParams->size() > 0) {
3254 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003255
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003256 // C++ [temp.class.spec]p10:
3257 // The template parameter list of a specialization shall not
3258 // contain default template argument values.
3259 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3260 Decl *Param = TemplateParams->getParam(I);
3261 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3262 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003263 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003264 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003265 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003266 }
3267 } else if (NonTypeTemplateParmDecl *NTTP
3268 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3269 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003270 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003271 diag::err_default_arg_in_partial_spec)
3272 << DefArg->getSourceRange();
3273 NTTP->setDefaultArgument(0);
3274 DefArg->Destroy(Context);
3275 }
3276 } else {
3277 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003278 if (TTP->hasDefaultArgument()) {
3279 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003280 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003281 << TTP->getDefaultArgument().getSourceRange();
3282 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003283 }
3284 }
3285 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003286 } else if (TemplateParams) {
3287 if (TUK == TUK_Friend)
3288 Diag(KWLoc, diag::err_template_spec_friend)
3289 << CodeModificationHint::CreateRemoval(
3290 SourceRange(TemplateParams->getTemplateLoc(),
3291 TemplateParams->getRAngleLoc()))
3292 << SourceRange(LAngleLoc, RAngleLoc);
3293 else
3294 isExplicitSpecialization = true;
3295 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003296 Diag(KWLoc, diag::err_template_spec_needs_header)
3297 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003298 isExplicitSpecialization = true;
3299 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003300
Douglas Gregor67a65642009-02-17 23:15:12 +00003301 // Check that the specialization uses the same tag kind as the
3302 // original template.
3303 TagDecl::TagKind Kind;
3304 switch (TagSpec) {
3305 default: assert(0 && "Unknown tag type!");
3306 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3307 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3308 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3309 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003310 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003311 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003312 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003313 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003314 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003315 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003316 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003317 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003318 diag::note_previous_use);
3319 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3320 }
3321
Douglas Gregorc40290e2009-03-09 23:48:35 +00003322 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003323 TemplateArgumentListInfo TemplateArgs;
3324 TemplateArgs.setLAngleLoc(LAngleLoc);
3325 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003326 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003327
Douglas Gregor67a65642009-02-17 23:15:12 +00003328 // Check that the template argument list is well-formed for this
3329 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003330 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3331 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003332 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3333 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003334 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003335
Mike Stump11289f42009-09-09 15:08:12 +00003336 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003337 ClassTemplate->getTemplateParameters()->size()) &&
3338 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003339
Douglas Gregor2373c592009-05-31 09:31:02 +00003340 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003341 // corresponds to these arguments.
3342 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003343 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003344 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003345 if (CheckClassTemplatePartialSpecializationArgs(
3346 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003347 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003348 return true;
3349
Douglas Gregor09a30232009-06-12 22:08:06 +00003350 if (MirrorsPrimaryTemplate) {
3351 // C++ [temp.class.spec]p9b3:
3352 //
Mike Stump11289f42009-09-09 15:08:12 +00003353 // -- The argument list of the specialization shall not be identical
3354 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003355 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003356 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00003357 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00003358 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003359 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003360 ClassTemplate->getIdentifier(),
3361 TemplateNameLoc,
3362 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003363 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003364 AS_none);
3365 }
3366
Douglas Gregor2208a292009-09-26 20:57:03 +00003367 // FIXME: Diagnose friend partial specializations
3368
Douglas Gregor2373c592009-05-31 09:31:02 +00003369 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00003370 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003371 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003372 Converted.flatSize(),
3373 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003374 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003375 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003376 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003377 Converted.flatSize(),
3378 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003379 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003380 ClassTemplateSpecializationDecl *PrevDecl = 0;
3381
3382 if (isPartialSpecialization)
3383 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003384 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003385 InsertPos);
3386 else
3387 PrevDecl
3388 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003389
3390 ClassTemplateSpecializationDecl *Specialization = 0;
3391
Douglas Gregorf47b9112009-02-25 22:02:03 +00003392 // Check whether we can declare a class template specialization in
3393 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003394 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003395 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003396 TemplateNameLoc,
3397 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003398 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003399
Douglas Gregor15301382009-07-30 17:40:51 +00003400 // The canonical type
3401 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003402 if (PrevDecl &&
3403 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3404 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003405 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003406 // arguments was referenced but not declared, or we're only
3407 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003408 // declaration node as our own, updating its source location to
3409 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003410 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003411 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003412 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003413 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003414 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003415 // Build the canonical type that describes the converted template
3416 // arguments of the class template partial specialization.
3417 CanonType = Context.getTemplateSpecializationType(
3418 TemplateName(ClassTemplate),
3419 Converted.getFlatArguments(),
3420 Converted.flatSize());
3421
Douglas Gregor2373c592009-05-31 09:31:02 +00003422 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003423 ClassTemplatePartialSpecializationDecl *PrevPartial
3424 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003425 ClassTemplatePartialSpecializationDecl *Partial
3426 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003427 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003428 TemplateNameLoc,
3429 TemplateParams,
3430 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003431 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003432 TemplateArgs,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003433 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00003434
3435 if (PrevPartial) {
3436 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3437 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3438 } else {
3439 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3440 }
3441 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003442
Douglas Gregor21610382009-10-29 00:04:11 +00003443 // If we are providing an explicit specialization of a member class
3444 // template specialization, make a note of that.
3445 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3446 PrevPartial->setMemberSpecialization();
3447
Douglas Gregor91772d12009-06-13 00:26:55 +00003448 // Check that all of the template parameters of the class template
3449 // partial specialization are deducible from the template
3450 // arguments. If not, this class template partial specialization
3451 // will never be used.
3452 llvm::SmallVector<bool, 8> DeducibleParams;
3453 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003454 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003455 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003456 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003457 unsigned NumNonDeducible = 0;
3458 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3459 if (!DeducibleParams[I])
3460 ++NumNonDeducible;
3461
3462 if (NumNonDeducible) {
3463 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3464 << (NumNonDeducible > 1)
3465 << SourceRange(TemplateNameLoc, RAngleLoc);
3466 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3467 if (!DeducibleParams[I]) {
3468 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3469 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003470 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003471 diag::note_partial_spec_unused_parameter)
3472 << Param->getDeclName();
3473 else
Mike Stump11289f42009-09-09 15:08:12 +00003474 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003475 diag::note_partial_spec_unused_parameter)
3476 << std::string("<anonymous>");
3477 }
3478 }
3479 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003480 } else {
3481 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003482 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003483 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003484 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003485 ClassTemplate->getDeclContext(),
3486 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003487 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003488 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003489 PrevDecl);
3490
3491 if (PrevDecl) {
3492 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3493 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3494 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003495 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003496 InsertPos);
3497 }
Douglas Gregor15301382009-07-30 17:40:51 +00003498
3499 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003500 }
3501
Douglas Gregor06db9f52009-10-12 20:18:28 +00003502 // C++ [temp.expl.spec]p6:
3503 // If a template, a member template or the member of a class template is
3504 // explicitly specialized then that specialization shall be declared
3505 // before the first use of that specialization that would cause an implicit
3506 // instantiation to take place, in every translation unit in which such a
3507 // use occurs; no diagnostic is required.
3508 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3509 SourceRange Range(TemplateNameLoc, RAngleLoc);
3510 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3511 << Context.getTypeDeclType(Specialization) << Range;
3512
3513 Diag(PrevDecl->getPointOfInstantiation(),
3514 diag::note_instantiation_required_here)
3515 << (PrevDecl->getTemplateSpecializationKind()
3516 != TSK_ImplicitInstantiation);
3517 return true;
3518 }
3519
Douglas Gregor2208a292009-09-26 20:57:03 +00003520 // If this is not a friend, note that this is an explicit specialization.
3521 if (TUK != TUK_Friend)
3522 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003523
3524 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003525 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003526 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003527 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003528 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003529 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003530 Diag(Def->getLocation(), diag::note_previous_definition);
3531 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003532 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003533 }
3534 }
3535
Douglas Gregord56a91e2009-02-26 22:19:44 +00003536 // Build the fully-sugared type for this class template
3537 // specialization as the user wrote in the specialization
3538 // itself. This means that we'll pretty-print the type retrieved
3539 // from the specialization's declaration the way that the user
3540 // actually wrote the specialization, rather than formatting the
3541 // name based on the "canonical" representation used to store the
3542 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003543 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00003544 = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003545 if (TUK != TUK_Friend)
3546 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003547 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003548
Douglas Gregor1e249f82009-02-25 22:18:32 +00003549 // C++ [temp.expl.spec]p9:
3550 // A template explicit specialization is in the scope of the
3551 // namespace in which the template was defined.
3552 //
3553 // We actually implement this paragraph where we set the semantic
3554 // context (in the creation of the ClassTemplateSpecializationDecl),
3555 // but we also maintain the lexical context where the actual
3556 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003557 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003558
Douglas Gregor67a65642009-02-17 23:15:12 +00003559 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003560 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003561 Specialization->startDefinition();
3562
Douglas Gregor2208a292009-09-26 20:57:03 +00003563 if (TUK == TUK_Friend) {
3564 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3565 TemplateNameLoc,
3566 WrittenTy.getTypePtr(),
3567 /*FIXME:*/KWLoc);
3568 Friend->setAccess(AS_public);
3569 CurContext->addDecl(Friend);
3570 } else {
3571 // Add the specialization into its lexical context, so that it can
3572 // be seen when iterating through the list of declarations in that
3573 // context. However, specializations are not found by name lookup.
3574 CurContext->addDecl(Specialization);
3575 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003576 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003577}
Douglas Gregor333489b2009-03-27 23:10:48 +00003578
Mike Stump11289f42009-09-09 15:08:12 +00003579Sema::DeclPtrTy
3580Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003581 MultiTemplateParamsArg TemplateParameterLists,
3582 Declarator &D) {
3583 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3584}
3585
Mike Stump11289f42009-09-09 15:08:12 +00003586Sema::DeclPtrTy
3587Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003588 MultiTemplateParamsArg TemplateParameterLists,
3589 Declarator &D) {
3590 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3591 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3592 "Not a function declarator!");
3593 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003594
Douglas Gregor17a7c122009-06-24 00:54:41 +00003595 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003596 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003597 }
Mike Stump11289f42009-09-09 15:08:12 +00003598
Douglas Gregor17a7c122009-06-24 00:54:41 +00003599 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003600
3601 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003602 move(TemplateParameterLists),
3603 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003604 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003605 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003606 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003607 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003608 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3609 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003610 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003611}
3612
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003613/// \brief Diagnose cases where we have an explicit template specialization
3614/// before/after an explicit template instantiation, producing diagnostics
3615/// for those cases where they are required and determining whether the
3616/// new specialization/instantiation will have any effect.
3617///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003618/// \param NewLoc the location of the new explicit specialization or
3619/// instantiation.
3620///
3621/// \param NewTSK the kind of the new explicit specialization or instantiation.
3622///
3623/// \param PrevDecl the previous declaration of the entity.
3624///
3625/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3626///
3627/// \param PrevPointOfInstantiation if valid, indicates where the previus
3628/// declaration was instantiated (either implicitly or explicitly).
3629///
3630/// \param SuppressNew will be set to true to indicate that the new
3631/// specialization or instantiation has no effect and should be ignored.
3632///
3633/// \returns true if there was an error that should prevent the introduction of
3634/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003635bool
3636Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3637 TemplateSpecializationKind NewTSK,
3638 NamedDecl *PrevDecl,
3639 TemplateSpecializationKind PrevTSK,
3640 SourceLocation PrevPointOfInstantiation,
3641 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003642 SuppressNew = false;
3643
3644 switch (NewTSK) {
3645 case TSK_Undeclared:
3646 case TSK_ImplicitInstantiation:
3647 assert(false && "Don't check implicit instantiations here");
3648 return false;
3649
3650 case TSK_ExplicitSpecialization:
3651 switch (PrevTSK) {
3652 case TSK_Undeclared:
3653 case TSK_ExplicitSpecialization:
3654 // Okay, we're just specializing something that is either already
3655 // explicitly specialized or has merely been mentioned without any
3656 // instantiation.
3657 return false;
3658
3659 case TSK_ImplicitInstantiation:
3660 if (PrevPointOfInstantiation.isInvalid()) {
3661 // The declaration itself has not actually been instantiated, so it is
3662 // still okay to specialize it.
3663 return false;
3664 }
3665 // Fall through
3666
3667 case TSK_ExplicitInstantiationDeclaration:
3668 case TSK_ExplicitInstantiationDefinition:
3669 assert((PrevTSK == TSK_ImplicitInstantiation ||
3670 PrevPointOfInstantiation.isValid()) &&
3671 "Explicit instantiation without point of instantiation?");
3672
3673 // C++ [temp.expl.spec]p6:
3674 // If a template, a member template or the member of a class template
3675 // is explicitly specialized then that specialization shall be declared
3676 // before the first use of that specialization that would cause an
3677 // implicit instantiation to take place, in every translation unit in
3678 // which such a use occurs; no diagnostic is required.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003679 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003680 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003681 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003682 << (PrevTSK != TSK_ImplicitInstantiation);
3683
3684 return true;
3685 }
3686 break;
3687
3688 case TSK_ExplicitInstantiationDeclaration:
3689 switch (PrevTSK) {
3690 case TSK_ExplicitInstantiationDeclaration:
3691 // This explicit instantiation declaration is redundant (that's okay).
3692 SuppressNew = true;
3693 return false;
3694
3695 case TSK_Undeclared:
3696 case TSK_ImplicitInstantiation:
3697 // We're explicitly instantiating something that may have already been
3698 // implicitly instantiated; that's fine.
3699 return false;
3700
3701 case TSK_ExplicitSpecialization:
3702 // C++0x [temp.explicit]p4:
3703 // For a given set of template parameters, if an explicit instantiation
3704 // of a template appears after a declaration of an explicit
3705 // specialization for that template, the explicit instantiation has no
3706 // effect.
3707 return false;
3708
3709 case TSK_ExplicitInstantiationDefinition:
3710 // C++0x [temp.explicit]p10:
3711 // If an entity is the subject of both an explicit instantiation
3712 // declaration and an explicit instantiation definition in the same
3713 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003714 Diag(NewLoc,
3715 diag::err_explicit_instantiation_declaration_after_definition);
3716 Diag(PrevPointOfInstantiation,
3717 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003718 assert(PrevPointOfInstantiation.isValid() &&
3719 "Explicit instantiation without point of instantiation?");
3720 SuppressNew = true;
3721 return false;
3722 }
3723 break;
3724
3725 case TSK_ExplicitInstantiationDefinition:
3726 switch (PrevTSK) {
3727 case TSK_Undeclared:
3728 case TSK_ImplicitInstantiation:
3729 // We're explicitly instantiating something that may have already been
3730 // implicitly instantiated; that's fine.
3731 return false;
3732
3733 case TSK_ExplicitSpecialization:
3734 // C++ DR 259, C++0x [temp.explicit]p4:
3735 // For a given set of template parameters, if an explicit
3736 // instantiation of a template appears after a declaration of
3737 // an explicit specialization for that template, the explicit
3738 // instantiation has no effect.
3739 //
3740 // In C++98/03 mode, we only give an extension warning here, because it
3741 // is not not harmful to try to explicitly instantiate something that
3742 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003743 if (!getLangOptions().CPlusPlus0x) {
3744 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003745 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003746 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003747 diag::note_previous_template_specialization);
3748 }
3749 SuppressNew = true;
3750 return false;
3751
3752 case TSK_ExplicitInstantiationDeclaration:
3753 // We're explicity instantiating a definition for something for which we
3754 // were previously asked to suppress instantiations. That's fine.
3755 return false;
3756
3757 case TSK_ExplicitInstantiationDefinition:
3758 // C++0x [temp.spec]p5:
3759 // For a given template and a given set of template-arguments,
3760 // - an explicit instantiation definition shall appear at most once
3761 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003762 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003763 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003764 Diag(PrevPointOfInstantiation,
3765 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003766 SuppressNew = true;
3767 return false;
3768 }
3769 break;
3770 }
3771
3772 assert(false && "Missing specialization/instantiation case?");
3773
3774 return false;
3775}
3776
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003777/// \brief Perform semantic analysis for the given function template
3778/// specialization.
3779///
3780/// This routine performs all of the semantic analysis required for an
3781/// explicit function template specialization. On successful completion,
3782/// the function declaration \p FD will become a function template
3783/// specialization.
3784///
3785/// \param FD the function declaration, which will be updated to become a
3786/// function template specialization.
3787///
3788/// \param HasExplicitTemplateArgs whether any template arguments were
3789/// explicitly provided.
3790///
3791/// \param LAngleLoc the location of the left angle bracket ('<'), if
3792/// template arguments were explicitly provided.
3793///
3794/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3795/// if any.
3796///
3797/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3798/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3799/// true as in, e.g., \c void sort<>(char*, char*);
3800///
3801/// \param RAngleLoc the location of the right angle bracket ('>'), if
3802/// template arguments were explicitly provided.
3803///
3804/// \param PrevDecl the set of declarations that
3805bool
3806Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00003807 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00003808 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003809 // The set of function template specializations that could match this
3810 // explicit function template specialization.
3811 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3812 CandidateSet Candidates;
3813
3814 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00003815 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3816 I != E; ++I) {
3817 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3818 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003819 // Only consider templates found within the same semantic lookup scope as
3820 // FD.
3821 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3822 continue;
3823
3824 // C++ [temp.expl.spec]p11:
3825 // A trailing template-argument can be left unspecified in the
3826 // template-id naming an explicit function template specialization
3827 // provided it can be deduced from the function argument type.
3828 // Perform template argument deduction to determine whether we may be
3829 // specializing this template.
3830 // FIXME: It is somewhat wasteful to build
3831 TemplateDeductionInfo Info(Context);
3832 FunctionDecl *Specialization = 0;
3833 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00003834 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003835 FD->getType(),
3836 Specialization,
3837 Info)) {
3838 // FIXME: Template argument deduction failed; record why it failed, so
3839 // that we can provide nifty diagnostics.
3840 (void)TDK;
3841 continue;
3842 }
3843
3844 // Record this candidate.
3845 Candidates.push_back(Specialization);
3846 }
3847 }
3848
Douglas Gregor5de279c2009-09-26 03:41:46 +00003849 // Find the most specialized function template.
3850 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3851 Candidates.size(),
3852 TPOC_Other,
3853 FD->getLocation(),
3854 PartialDiagnostic(diag::err_function_template_spec_no_match)
3855 << FD->getDeclName(),
3856 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00003857 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor5de279c2009-09-26 03:41:46 +00003858 PartialDiagnostic(diag::note_function_template_spec_matched));
3859 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003860 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003861
3862 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003863 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003864
Douglas Gregor54888652009-10-07 00:13:32 +00003865 // Check the scope of this explicit specialization.
3866 if (CheckTemplateSpecializationScope(*this,
3867 Specialization->getPrimaryTemplate(),
3868 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003869 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003870 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003871
3872 // C++ [temp.expl.spec]p6:
3873 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003874 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003875 // before the first use of that specialization that would cause an implicit
3876 // instantiation to take place, in every translation unit in which such a
3877 // use occurs; no diagnostic is required.
3878 FunctionTemplateSpecializationInfo *SpecInfo
3879 = Specialization->getTemplateSpecializationInfo();
3880 assert(SpecInfo && "Function template specialization info missing?");
3881 if (SpecInfo->getPointOfInstantiation().isValid()) {
3882 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3883 << FD;
3884 Diag(SpecInfo->getPointOfInstantiation(),
3885 diag::note_instantiation_required_here)
3886 << (Specialization->getTemplateSpecializationKind()
3887 != TSK_ImplicitInstantiation);
3888 return true;
3889 }
Douglas Gregor54888652009-10-07 00:13:32 +00003890
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003891 // Mark the prior declaration as an explicit specialization, so that later
3892 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003893 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003894
3895 // Turn the given function declaration into a function template
3896 // specialization, with the template arguments from the previous
3897 // specialization.
3898 FD->setFunctionTemplateSpecialization(Context,
3899 Specialization->getPrimaryTemplate(),
3900 new (Context) TemplateArgumentList(
3901 *Specialization->getTemplateSpecializationArgs()),
3902 /*InsertPos=*/0,
3903 TSK_ExplicitSpecialization);
3904
3905 // The "previous declaration" for this function template specialization is
3906 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00003907 Previous.clear();
3908 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003909 return false;
3910}
3911
Douglas Gregor86d142a2009-10-08 07:24:58 +00003912/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003913/// specialization.
3914///
3915/// This routine performs all of the semantic analysis required for an
3916/// explicit member function specialization. On successful completion,
3917/// the function declaration \p FD will become a member function
3918/// specialization.
3919///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003920/// \param Member the member declaration, which will be updated to become a
3921/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003922///
John McCall1f82f242009-11-18 22:49:29 +00003923/// \param Previous the set of declarations, one of which may be specialized
3924/// by this function specialization; the set will be modified to contain the
3925/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003926bool
John McCall1f82f242009-11-18 22:49:29 +00003927Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003928 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3929
3930 // Try to find the member we are instantiating.
3931 NamedDecl *Instantiation = 0;
3932 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003933 MemberSpecializationInfo *MSInfo = 0;
3934
John McCall1f82f242009-11-18 22:49:29 +00003935 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003936 // Nowhere to look anyway.
3937 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003938 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3939 I != E; ++I) {
3940 NamedDecl *D = (*I)->getUnderlyingDecl();
3941 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003942 if (Context.hasSameType(Function->getType(), Method->getType())) {
3943 Instantiation = Method;
3944 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003945 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003946 break;
3947 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003948 }
3949 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003950 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003951 VarDecl *PrevVar;
3952 if (Previous.isSingleResult() &&
3953 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00003954 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00003955 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003956 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003957 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003958 }
3959 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003960 CXXRecordDecl *PrevRecord;
3961 if (Previous.isSingleResult() &&
3962 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
3963 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003964 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003965 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003966 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003967 }
3968
3969 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003970 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003971 // specializations are always out-of-line, the caller will complain about
3972 // this mismatch later.
3973 return false;
3974 }
3975
Douglas Gregor86d142a2009-10-08 07:24:58 +00003976 // Make sure that this is a specialization of a member.
3977 if (!InstantiatedFrom) {
3978 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3979 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003980 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3981 return true;
3982 }
3983
Douglas Gregor06db9f52009-10-12 20:18:28 +00003984 // C++ [temp.expl.spec]p6:
3985 // If a template, a member template or the member of a class template is
3986 // explicitly specialized then that spe- cialization shall be declared
3987 // before the first use of that specialization that would cause an implicit
3988 // instantiation to take place, in every translation unit in which such a
3989 // use occurs; no diagnostic is required.
3990 assert(MSInfo && "Member specialization info missing?");
3991 if (MSInfo->getPointOfInstantiation().isValid()) {
3992 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3993 << Member;
3994 Diag(MSInfo->getPointOfInstantiation(),
3995 diag::note_instantiation_required_here)
3996 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3997 return true;
3998 }
3999
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004000 // Check the scope of this explicit specialization.
4001 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004002 InstantiatedFrom,
4003 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004004 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004005 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004006
Douglas Gregor86d142a2009-10-08 07:24:58 +00004007 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004008 // the original declaration to note that it is an explicit specialization
4009 // (if it was previously an implicit instantiation). This latter step
4010 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004011 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004012 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4013 if (InstantiationFunction->getTemplateSpecializationKind() ==
4014 TSK_ImplicitInstantiation) {
4015 InstantiationFunction->setTemplateSpecializationKind(
4016 TSK_ExplicitSpecialization);
4017 InstantiationFunction->setLocation(Member->getLocation());
4018 }
4019
Douglas Gregor86d142a2009-10-08 07:24:58 +00004020 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4021 cast<CXXMethodDecl>(InstantiatedFrom),
4022 TSK_ExplicitSpecialization);
4023 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004024 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4025 if (InstantiationVar->getTemplateSpecializationKind() ==
4026 TSK_ImplicitInstantiation) {
4027 InstantiationVar->setTemplateSpecializationKind(
4028 TSK_ExplicitSpecialization);
4029 InstantiationVar->setLocation(Member->getLocation());
4030 }
4031
Douglas Gregor86d142a2009-10-08 07:24:58 +00004032 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4033 cast<VarDecl>(InstantiatedFrom),
4034 TSK_ExplicitSpecialization);
4035 } else {
4036 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004037 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4038 if (InstantiationClass->getTemplateSpecializationKind() ==
4039 TSK_ImplicitInstantiation) {
4040 InstantiationClass->setTemplateSpecializationKind(
4041 TSK_ExplicitSpecialization);
4042 InstantiationClass->setLocation(Member->getLocation());
4043 }
4044
Douglas Gregor86d142a2009-10-08 07:24:58 +00004045 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004046 cast<CXXRecordDecl>(InstantiatedFrom),
4047 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004048 }
4049
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004050 // Save the caller the trouble of having to figure out which declaration
4051 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004052 Previous.clear();
4053 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004054 return false;
4055}
4056
Douglas Gregore47f5a72009-10-14 23:41:34 +00004057/// \brief Check the scope of an explicit instantiation.
4058static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4059 SourceLocation InstLoc,
4060 bool WasQualifiedName) {
4061 DeclContext *ExpectedContext
4062 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4063 DeclContext *CurContext = S.CurContext->getLookupContext();
4064
4065 // C++0x [temp.explicit]p2:
4066 // An explicit instantiation shall appear in an enclosing namespace of its
4067 // template.
4068 //
4069 // This is DR275, which we do not retroactively apply to C++98/03.
4070 if (S.getLangOptions().CPlusPlus0x &&
4071 !CurContext->Encloses(ExpectedContext)) {
4072 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4073 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4074 << D << NS;
4075 else
4076 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4077 << D;
4078 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4079 return;
4080 }
4081
4082 // C++0x [temp.explicit]p2:
4083 // If the name declared in the explicit instantiation is an unqualified
4084 // name, the explicit instantiation shall appear in the namespace where
4085 // its template is declared or, if that namespace is inline (7.3.1), any
4086 // namespace from its enclosing namespace set.
4087 if (WasQualifiedName)
4088 return;
4089
4090 if (CurContext->Equals(ExpectedContext))
4091 return;
4092
4093 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4094 << D << ExpectedContext;
4095 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4096}
4097
4098/// \brief Determine whether the given scope specifier has a template-id in it.
4099static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4100 if (!SS.isSet())
4101 return false;
4102
4103 // C++0x [temp.explicit]p2:
4104 // If the explicit instantiation is for a member function, a member class
4105 // or a static data member of a class template specialization, the name of
4106 // the class template specialization in the qualified-id for the member
4107 // name shall be a simple-template-id.
4108 //
4109 // C++98 has the same restriction, just worded differently.
4110 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4111 NNS; NNS = NNS->getPrefix())
4112 if (Type *T = NNS->getAsType())
4113 if (isa<TemplateSpecializationType>(T))
4114 return true;
4115
4116 return false;
4117}
4118
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004119// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00004120// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00004121Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004122Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004123 SourceLocation ExternLoc,
4124 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004125 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004126 SourceLocation KWLoc,
4127 const CXXScopeSpec &SS,
4128 TemplateTy TemplateD,
4129 SourceLocation TemplateNameLoc,
4130 SourceLocation LAngleLoc,
4131 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004132 SourceLocation RAngleLoc,
4133 AttributeList *Attr) {
4134 // Find the class template we're specializing
4135 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004136 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004137 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4138
4139 // Check that the specialization uses the same tag kind as the
4140 // original template.
4141 TagDecl::TagKind Kind;
4142 switch (TagSpec) {
4143 default: assert(0 && "Unknown tag type!");
4144 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4145 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4146 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4147 }
Douglas Gregord9034f02009-05-14 16:41:31 +00004148 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004149 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004150 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004151 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004152 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00004153 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004154 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004155 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004156 diag::note_previous_use);
4157 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4158 }
4159
Douglas Gregore47f5a72009-10-14 23:41:34 +00004160 // C++0x [temp.explicit]p2:
4161 // There are two forms of explicit instantiation: an explicit instantiation
4162 // definition and an explicit instantiation declaration. An explicit
4163 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004164 TemplateSpecializationKind TSK
4165 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4166 : TSK_ExplicitInstantiationDeclaration;
4167
Douglas Gregora1f49972009-05-13 00:25:59 +00004168 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004169 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004170 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004171
4172 // Check that the template argument list is well-formed for this
4173 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004174 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4175 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004176 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4177 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004178 return true;
4179
Mike Stump11289f42009-09-09 15:08:12 +00004180 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004181 ClassTemplate->getTemplateParameters()->size()) &&
4182 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004183
Douglas Gregora1f49972009-05-13 00:25:59 +00004184 // Find the class template specialization declaration that
4185 // corresponds to these arguments.
4186 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004187 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004188 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004189 Converted.flatSize(),
4190 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004191 void *InsertPos = 0;
4192 ClassTemplateSpecializationDecl *PrevDecl
4193 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4194
Douglas Gregor54888652009-10-07 00:13:32 +00004195 // C++0x [temp.explicit]p2:
4196 // [...] An explicit instantiation shall appear in an enclosing
4197 // namespace of its template. [...]
4198 //
4199 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004200 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4201 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004202
Douglas Gregora1f49972009-05-13 00:25:59 +00004203 ClassTemplateSpecializationDecl *Specialization = 0;
4204
Douglas Gregor0681a352009-11-25 06:01:46 +00004205 bool ReusedDecl = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004206 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00004207 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004208 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004209 PrevDecl,
4210 PrevDecl->getSpecializationKind(),
4211 PrevDecl->getPointOfInstantiation(),
4212 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00004213 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004214
Douglas Gregor12e49d32009-10-15 22:53:21 +00004215 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004216 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00004217
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004218 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4219 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4220 // Since the only prior class template specialization with these
4221 // arguments was referenced but not declared, reuse that
4222 // declaration node as our own, updating its source location to
4223 // reflect our new declaration.
4224 Specialization = PrevDecl;
4225 Specialization->setLocation(TemplateNameLoc);
4226 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004227 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004228 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004229 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004230
4231 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004232 // Create a new class template specialization declaration node for
4233 // this explicit specialization.
4234 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00004235 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00004236 ClassTemplate->getDeclContext(),
4237 TemplateNameLoc,
4238 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004239 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004240
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004241 if (PrevDecl) {
4242 // Remove the previous declaration from the folding set, since we want
4243 // to introduce a new declaration.
4244 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4245 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4246 }
4247
4248 // Insert the new specialization.
4249 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004250 }
4251
4252 // Build the fully-sugared type for this explicit instantiation as
4253 // the user wrote in the explicit instantiation itself. This means
4254 // that we'll pretty-print the type retrieved from the
4255 // specialization's declaration the way that the user actually wrote
4256 // the explicit instantiation, rather than formatting the name based
4257 // on the "canonical" representation used to store the template
4258 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004259 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00004260 = Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004261 Context.getTypeDeclType(Specialization));
4262 Specialization->setTypeAsWritten(WrittenTy);
4263 TemplateArgsIn.release();
4264
Douglas Gregor0681a352009-11-25 06:01:46 +00004265 if (!ReusedDecl) {
4266 // Add the explicit instantiation into its lexical context. However,
4267 // since explicit instantiations are never found by name lookup, we
4268 // just put it into the declaration context directly.
4269 Specialization->setLexicalDeclContext(CurContext);
4270 CurContext->addDecl(Specialization);
4271 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004272
4273 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004274 // A definition of a class template or class member template
4275 // shall be in scope at the point of the explicit instantiation of
4276 // the class template or class member template.
4277 //
4278 // This check comes when we actually try to perform the
4279 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004280 ClassTemplateSpecializationDecl *Def
4281 = cast_or_null<ClassTemplateSpecializationDecl>(
4282 Specialization->getDefinition(Context));
4283 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004284 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00004285
4286 // Instantiate the members of this class template specialization.
4287 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4288 Specialization->getDefinition(Context));
4289 if (Def)
Douglas Gregor12e49d32009-10-15 22:53:21 +00004290 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00004291
4292 return DeclPtrTy::make(Specialization);
4293}
4294
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004295// Explicit instantiation of a member class of a class template.
4296Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004297Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004298 SourceLocation ExternLoc,
4299 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004300 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004301 SourceLocation KWLoc,
4302 const CXXScopeSpec &SS,
4303 IdentifierInfo *Name,
4304 SourceLocation NameLoc,
4305 AttributeList *Attr) {
4306
Douglas Gregord6ab8742009-05-28 23:31:59 +00004307 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004308 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004309 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004310 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004311 MultiTemplateParamsArg(*this, 0, 0),
4312 Owned, IsDependent);
4313 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4314
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004315 if (!TagD)
4316 return true;
4317
4318 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4319 if (Tag->isEnum()) {
4320 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4321 << Context.getTypeDeclType(Tag);
4322 return true;
4323 }
4324
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004325 if (Tag->isInvalidDecl())
4326 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004327
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004328 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4329 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4330 if (!Pattern) {
4331 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4332 << Context.getTypeDeclType(Record);
4333 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4334 return true;
4335 }
4336
Douglas Gregore47f5a72009-10-14 23:41:34 +00004337 // C++0x [temp.explicit]p2:
4338 // If the explicit instantiation is for a class or member class, the
4339 // elaborated-type-specifier in the declaration shall include a
4340 // simple-template-id.
4341 //
4342 // C++98 has the same restriction, just worded differently.
4343 if (!ScopeSpecifierHasTemplateId(SS))
4344 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4345 << Record << SS.getRange();
4346
4347 // C++0x [temp.explicit]p2:
4348 // There are two forms of explicit instantiation: an explicit instantiation
4349 // definition and an explicit instantiation declaration. An explicit
4350 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004351 TemplateSpecializationKind TSK
4352 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4353 : TSK_ExplicitInstantiationDeclaration;
4354
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004355 // C++0x [temp.explicit]p2:
4356 // [...] An explicit instantiation shall appear in an enclosing
4357 // namespace of its template. [...]
4358 //
4359 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004360 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004361
4362 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004363 CXXRecordDecl *PrevDecl
4364 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4365 if (!PrevDecl && Record->getDefinition(Context))
4366 PrevDecl = Record;
4367 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004368 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4369 bool SuppressNew = false;
4370 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004371 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004372 PrevDecl,
4373 MSInfo->getTemplateSpecializationKind(),
4374 MSInfo->getPointOfInstantiation(),
4375 SuppressNew))
4376 return true;
4377 if (SuppressNew)
4378 return TagD;
4379 }
4380
Douglas Gregor12e49d32009-10-15 22:53:21 +00004381 CXXRecordDecl *RecordDef
4382 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4383 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004384 // C++ [temp.explicit]p3:
4385 // A definition of a member class of a class template shall be in scope
4386 // at the point of an explicit instantiation of the member class.
4387 CXXRecordDecl *Def
4388 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4389 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004390 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4391 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004392 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4393 << Pattern;
4394 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004395 } else {
4396 if (InstantiateClass(NameLoc, Record, Def,
4397 getTemplateInstantiationArgs(Record),
4398 TSK))
4399 return true;
4400
4401 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4402 if (!RecordDef)
4403 return true;
4404 }
4405 }
4406
4407 // Instantiate all of the members of the class.
4408 InstantiateClassMembers(NameLoc, RecordDef,
4409 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004410
Mike Stump87c57ac2009-05-16 07:39:55 +00004411 // FIXME: We don't have any representation for explicit instantiations of
4412 // member classes. Such a representation is not needed for compilation, but it
4413 // should be available for clients that want to see all of the declarations in
4414 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004415 return TagD;
4416}
4417
Douglas Gregor450f00842009-09-25 18:43:00 +00004418Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4419 SourceLocation ExternLoc,
4420 SourceLocation TemplateLoc,
4421 Declarator &D) {
4422 // Explicit instantiations always require a name.
4423 DeclarationName Name = GetNameForDeclarator(D);
4424 if (!Name) {
4425 if (!D.isInvalidType())
4426 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4427 diag::err_explicit_instantiation_requires_name)
4428 << D.getDeclSpec().getSourceRange()
4429 << D.getSourceRange();
4430
4431 return true;
4432 }
4433
4434 // The scope passed in may not be a decl scope. Zip up the scope tree until
4435 // we find one that is.
4436 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4437 (S->getFlags() & Scope::TemplateParamScope) != 0)
4438 S = S->getParent();
4439
4440 // Determine the type of the declaration.
4441 QualType R = GetTypeForDeclarator(D, S, 0);
4442 if (R.isNull())
4443 return true;
4444
4445 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4446 // Cannot explicitly instantiate a typedef.
4447 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4448 << Name;
4449 return true;
4450 }
4451
Douglas Gregor3c74d412009-10-14 20:14:33 +00004452 // C++0x [temp.explicit]p1:
4453 // [...] An explicit instantiation of a function template shall not use the
4454 // inline or constexpr specifiers.
4455 // Presumably, this also applies to member functions of class templates as
4456 // well.
4457 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4458 Diag(D.getDeclSpec().getInlineSpecLoc(),
4459 diag::err_explicit_instantiation_inline)
Chris Lattner3c7b86f2009-12-06 17:36:05 +00004460 <<CodeModificationHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004461
4462 // FIXME: check for constexpr specifier.
4463
Douglas Gregore47f5a72009-10-14 23:41:34 +00004464 // C++0x [temp.explicit]p2:
4465 // There are two forms of explicit instantiation: an explicit instantiation
4466 // definition and an explicit instantiation declaration. An explicit
4467 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004468 TemplateSpecializationKind TSK
4469 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4470 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004471
John McCall27b18f82009-11-17 02:14:36 +00004472 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4473 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004474
4475 if (!R->isFunctionType()) {
4476 // C++ [temp.explicit]p1:
4477 // A [...] static data member of a class template can be explicitly
4478 // instantiated from the member definition associated with its class
4479 // template.
John McCall27b18f82009-11-17 02:14:36 +00004480 if (Previous.isAmbiguous())
4481 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00004482
John McCall67c00872009-12-02 08:25:40 +00004483 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00004484 if (!Prev || !Prev->isStaticDataMember()) {
4485 // We expect to see a data data member here.
4486 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4487 << Name;
4488 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4489 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004490 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004491 return true;
4492 }
4493
4494 if (!Prev->getInstantiatedFromStaticDataMember()) {
4495 // FIXME: Check for explicit specialization?
4496 Diag(D.getIdentifierLoc(),
4497 diag::err_explicit_instantiation_data_member_not_instantiated)
4498 << Prev;
4499 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4500 // FIXME: Can we provide a note showing where this was declared?
4501 return true;
4502 }
4503
Douglas Gregore47f5a72009-10-14 23:41:34 +00004504 // C++0x [temp.explicit]p2:
4505 // If the explicit instantiation is for a member function, a member class
4506 // or a static data member of a class template specialization, the name of
4507 // the class template specialization in the qualified-id for the member
4508 // name shall be a simple-template-id.
4509 //
4510 // C++98 has the same restriction, just worded differently.
4511 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4512 Diag(D.getIdentifierLoc(),
4513 diag::err_explicit_instantiation_without_qualified_id)
4514 << Prev << D.getCXXScopeSpec().getRange();
4515
4516 // Check the scope of this explicit instantiation.
4517 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4518
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004519 // Verify that it is okay to explicitly instantiate here.
4520 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4521 assert(MSInfo && "Missing static data member specialization info?");
4522 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004523 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004524 MSInfo->getTemplateSpecializationKind(),
4525 MSInfo->getPointOfInstantiation(),
4526 SuppressNew))
4527 return true;
4528 if (SuppressNew)
4529 return DeclPtrTy();
4530
Douglas Gregor450f00842009-09-25 18:43:00 +00004531 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004532 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004533 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004534 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4535 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004536
4537 // FIXME: Create an ExplicitInstantiation node?
4538 return DeclPtrTy();
4539 }
4540
Douglas Gregor0e876e02009-09-25 23:53:26 +00004541 // If the declarator is a template-id, translate the parser's template
4542 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004543 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004544 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004545 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4546 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00004547 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4548 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00004549 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4550 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004551 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00004552 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00004553 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004554 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004555 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004556
Douglas Gregor450f00842009-09-25 18:43:00 +00004557 // C++ [temp.explicit]p1:
4558 // A [...] function [...] can be explicitly instantiated from its template.
4559 // A member function [...] of a class template can be explicitly
4560 // instantiated from the member definition associated with its class
4561 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00004562 llvm::SmallVector<FunctionDecl *, 8> Matches;
4563 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4564 P != PEnd; ++P) {
4565 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004566 if (!HasExplicitTemplateArgs) {
4567 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4568 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4569 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004570
Douglas Gregord90fd522009-09-25 21:45:23 +00004571 Matches.push_back(Method);
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004572 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
4573 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00004574 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004575 }
4576 }
4577
4578 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4579 if (!FunTmpl)
4580 continue;
4581
4582 TemplateDeductionInfo Info(Context);
4583 FunctionDecl *Specialization = 0;
4584 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004585 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00004586 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004587 R, Specialization, Info)) {
4588 // FIXME: Keep track of almost-matches?
4589 (void)TDK;
4590 continue;
4591 }
4592
4593 Matches.push_back(Specialization);
4594 }
4595
4596 // Find the most specialized function template specialization.
4597 FunctionDecl *Specialization
4598 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4599 D.getIdentifierLoc(),
4600 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4601 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4602 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4603
4604 if (!Specialization)
4605 return true;
4606
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004607 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004608 Diag(D.getIdentifierLoc(),
4609 diag::err_explicit_instantiation_member_function_not_instantiated)
4610 << Specialization
4611 << (Specialization->getTemplateSpecializationKind() ==
4612 TSK_ExplicitSpecialization);
4613 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4614 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004615 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004616
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004617 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004618 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4619 PrevDecl = Specialization;
4620
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004621 if (PrevDecl) {
4622 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004623 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004624 PrevDecl,
4625 PrevDecl->getTemplateSpecializationKind(),
4626 PrevDecl->getPointOfInstantiation(),
4627 SuppressNew))
4628 return true;
4629
4630 // FIXME: We may still want to build some representation of this
4631 // explicit specialization.
4632 if (SuppressNew)
4633 return DeclPtrTy();
4634 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00004635
4636 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004637
4638 if (TSK == TSK_ExplicitInstantiationDefinition)
4639 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4640 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004641
Douglas Gregore47f5a72009-10-14 23:41:34 +00004642 // C++0x [temp.explicit]p2:
4643 // If the explicit instantiation is for a member function, a member class
4644 // or a static data member of a class template specialization, the name of
4645 // the class template specialization in the qualified-id for the member
4646 // name shall be a simple-template-id.
4647 //
4648 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004649 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00004650 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00004651 D.getCXXScopeSpec().isSet() &&
4652 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4653 Diag(D.getIdentifierLoc(),
4654 diag::err_explicit_instantiation_without_qualified_id)
4655 << Specialization << D.getCXXScopeSpec().getRange();
4656
4657 CheckExplicitInstantiationScope(*this,
4658 FunTmpl? (NamedDecl *)FunTmpl
4659 : Specialization->getInstantiatedFromMemberFunction(),
4660 D.getIdentifierLoc(),
4661 D.getCXXScopeSpec().isSet());
4662
Douglas Gregor450f00842009-09-25 18:43:00 +00004663 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4664 return DeclPtrTy();
4665}
4666
Douglas Gregor333489b2009-03-27 23:10:48 +00004667Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004668Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4669 const CXXScopeSpec &SS, IdentifierInfo *Name,
4670 SourceLocation TagLoc, SourceLocation NameLoc) {
4671 // This has to hold, because SS is expected to be defined.
4672 assert(Name && "Expected a name in a dependent tag");
4673
4674 NestedNameSpecifier *NNS
4675 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4676 if (!NNS)
4677 return true;
4678
4679 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4680 if (T.isNull())
4681 return true;
4682
4683 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4684 QualType ElabType = Context.getElaboratedType(T, TagKind);
4685
4686 return ElabType.getAsOpaquePtr();
4687}
4688
4689Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004690Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4691 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004692 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004693 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4694 if (!NNS)
4695 return true;
4696
4697 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004698 if (T.isNull())
4699 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004700 return T.getAsOpaquePtr();
4701}
4702
Douglas Gregordce2b622009-04-01 00:28:59 +00004703Sema::TypeResult
4704Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4705 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004706 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004707 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004708 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004709 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004710 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004711 assert(TemplateId && "Expected a template specialization type");
4712
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004713 if (computeDeclContext(SS, false)) {
4714 // If we can compute a declaration context, then the "typename"
4715 // keyword was superfluous. Just build a QualifiedNameType to keep
4716 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004717
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004718 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4719 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4720 }
Mike Stump11289f42009-09-09 15:08:12 +00004721
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004722 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004723}
4724
Douglas Gregor333489b2009-03-27 23:10:48 +00004725/// \brief Build the type that describes a C++ typename specifier,
4726/// e.g., "typename T::type".
4727QualType
4728Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4729 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004730 CXXRecordDecl *CurrentInstantiation = 0;
4731 if (NNS->isDependent()) {
4732 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004733
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004734 // If the nested-name-specifier does not refer to the current
4735 // instantiation, then build a typename type.
4736 if (!CurrentInstantiation)
4737 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004738
Douglas Gregorc707da62009-09-02 13:12:51 +00004739 // The nested-name-specifier refers to the current instantiation, so the
4740 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004741 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004742 // extraneous "typename" keywords, and we retroactively apply this DR to
4743 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004744 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004745
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004746 DeclContext *Ctx = 0;
4747
4748 if (CurrentInstantiation)
4749 Ctx = CurrentInstantiation;
4750 else {
4751 CXXScopeSpec SS;
4752 SS.setScopeRep(NNS);
4753 SS.setRange(Range);
4754 if (RequireCompleteDeclContext(SS))
4755 return QualType();
4756
4757 Ctx = computeDeclContext(SS);
4758 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004759 assert(Ctx && "No declaration context?");
4760
4761 DeclarationName Name(&II);
John McCall27b18f82009-11-17 02:14:36 +00004762 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4763 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00004764 unsigned DiagID = 0;
4765 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00004766 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004767 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004768 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004769 break;
4770
4771 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004772 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004773 // We found a type. Build a QualifiedNameType, since the
4774 // typename-specifier was just sugar. FIXME: Tell
4775 // QualifiedNameType that it has a "typename" prefix.
4776 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4777 }
4778
4779 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004780 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004781 break;
4782
John McCalle61f2ba2009-11-18 02:36:19 +00004783 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004784 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00004785 return QualType();
4786
Douglas Gregor333489b2009-03-27 23:10:48 +00004787 case LookupResult::FoundOverloaded:
4788 DiagID = diag::err_typename_nested_not_type;
4789 Referenced = *Result.begin();
4790 break;
4791
John McCall6538c932009-10-10 05:48:19 +00004792 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004793 return QualType();
4794 }
4795
4796 // If we get here, it's because name lookup did not find a
4797 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004798 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004799 if (Referenced)
4800 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4801 << Name;
4802 return QualType();
4803}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004804
4805namespace {
4806 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00004807 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00004808 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004809 SourceLocation Loc;
4810 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004811
Douglas Gregor15acfb92009-08-06 16:20:37 +00004812 public:
Mike Stump11289f42009-09-09 15:08:12 +00004813 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004814 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004815 DeclarationName Entity)
4816 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004817 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004818
4819 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004820 /// transformed.
4821 ///
4822 /// For the purposes of type reconstruction, a type has already been
4823 /// transformed if it is NULL or if it is not dependent.
4824 bool AlreadyTransformed(QualType T) {
4825 return T.isNull() || !T->isDependentType();
4826 }
Mike Stump11289f42009-09-09 15:08:12 +00004827
4828 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004829 /// rebuilt.
4830 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004831
Douglas Gregor15acfb92009-08-06 16:20:37 +00004832 /// \brief Returns the name of the entity whose type is being rebuilt.
4833 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004834
Douglas Gregoref6ab412009-10-27 06:26:26 +00004835 /// \brief Sets the "base" location and entity when that
4836 /// information is known based on another transformation.
4837 void setBase(SourceLocation Loc, DeclarationName Entity) {
4838 this->Loc = Loc;
4839 this->Entity = Entity;
4840 }
4841
Douglas Gregor15acfb92009-08-06 16:20:37 +00004842 /// \brief Transforms an expression by returning the expression itself
4843 /// (an identity function).
4844 ///
4845 /// FIXME: This is completely unsafe; we will need to actually clone the
4846 /// expressions.
4847 Sema::OwningExprResult TransformExpr(Expr *E) {
4848 return getSema().Owned(E);
4849 }
Mike Stump11289f42009-09-09 15:08:12 +00004850
Douglas Gregor15acfb92009-08-06 16:20:37 +00004851 /// \brief Transforms a typename type by determining whether the type now
4852 /// refers to a member of the current instantiation, and then
4853 /// type-checking and building a QualifiedNameType (when possible).
John McCall550e0c22009-10-21 00:40:46 +00004854 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004855 };
4856}
4857
Mike Stump11289f42009-09-09 15:08:12 +00004858QualType
John McCall550e0c22009-10-21 00:40:46 +00004859CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4860 TypenameTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00004861 TypenameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00004862
Douglas Gregor15acfb92009-08-06 16:20:37 +00004863 NestedNameSpecifier *NNS
4864 = TransformNestedNameSpecifier(T->getQualifier(),
4865 /*FIXME:*/SourceRange(getBaseLocation()));
4866 if (!NNS)
4867 return QualType();
4868
4869 // If the nested-name-specifier did not change, and we cannot compute the
4870 // context corresponding to the nested-name-specifier, then this
4871 // typename type will not change; exit early.
4872 CXXScopeSpec SS;
4873 SS.setRange(SourceRange(getBaseLocation()));
4874 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00004875
4876 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004877 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00004878 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004879
4880 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004881 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00004882 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004883 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004884 = TransformType(QualType(TemplateId, 0));
4885 if (NewTemplateId.isNull())
4886 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004887
Douglas Gregor15acfb92009-08-06 16:20:37 +00004888 if (NNS == T->getQualifier() &&
4889 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00004890 Result = QualType(T, 0);
4891 else
4892 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4893 } else
4894 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4895 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00004896
John McCall0ad16662009-10-29 08:12:44 +00004897 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4898 NewTL.setNameLoc(TL.getNameLoc());
4899 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004900}
4901
4902/// \brief Rebuilds a type within the context of the current instantiation.
4903///
Mike Stump11289f42009-09-09 15:08:12 +00004904/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00004905/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00004906/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00004907/// partial specialization thereof). This routine will rebuild that type now
4908/// that we have entered the declarator's scope, which may produce different
4909/// canonical types, e.g.,
4910///
4911/// \code
4912/// template<typename T>
4913/// struct X {
4914/// typedef T* pointer;
4915/// pointer data();
4916/// };
4917///
4918/// template<typename T>
4919/// typename X<T>::pointer X<T>::data() { ... }
4920/// \endcode
4921///
4922/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4923/// since we do not know that we can look into X<T> when we parsed the type.
4924/// This function will rebuild the type, performing the lookup of "pointer"
4925/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4926/// as the canonical type of T*, allowing the return types of the out-of-line
4927/// definition and the declaration to match.
4928QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4929 DeclarationName Name) {
4930 if (T.isNull() || !T->isDependentType())
4931 return T;
Mike Stump11289f42009-09-09 15:08:12 +00004932
Douglas Gregor15acfb92009-08-06 16:20:37 +00004933 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4934 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00004935}
Douglas Gregorbe999392009-09-15 16:23:51 +00004936
4937/// \brief Produces a formatted string that describes the binding of
4938/// template parameters to template arguments.
4939std::string
4940Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4941 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004942 // FIXME: For variadic templates, we'll need to get the structured list.
4943 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4944 Args.flat_size());
4945}
4946
4947std::string
4948Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4949 const TemplateArgument *Args,
4950 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004951 std::string Result;
4952
Douglas Gregore62e6a02009-11-11 19:13:48 +00004953 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00004954 return Result;
4955
4956 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004957 if (I >= NumArgs)
4958 break;
4959
Douglas Gregorbe999392009-09-15 16:23:51 +00004960 if (I == 0)
4961 Result += "[with ";
4962 else
4963 Result += ", ";
4964
4965 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4966 Result += Id->getName();
4967 } else {
4968 Result += '$';
4969 Result += llvm::utostr(I);
4970 }
4971
4972 Result += " = ";
4973
4974 switch (Args[I].getKind()) {
4975 case TemplateArgument::Null:
4976 Result += "<no value>";
4977 break;
4978
4979 case TemplateArgument::Type: {
4980 std::string TypeStr;
4981 Args[I].getAsType().getAsStringInternal(TypeStr,
4982 Context.PrintingPolicy);
4983 Result += TypeStr;
4984 break;
4985 }
4986
4987 case TemplateArgument::Declaration: {
4988 bool Unnamed = true;
4989 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4990 if (ND->getDeclName()) {
4991 Unnamed = false;
4992 Result += ND->getNameAsString();
4993 }
4994 }
4995
4996 if (Unnamed) {
4997 Result += "<anonymous>";
4998 }
4999 break;
5000 }
5001
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005002 case TemplateArgument::Template: {
5003 std::string Str;
5004 llvm::raw_string_ostream OS(Str);
5005 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5006 Result += OS.str();
5007 break;
5008 }
5009
Douglas Gregorbe999392009-09-15 16:23:51 +00005010 case TemplateArgument::Integral: {
5011 Result += Args[I].getAsIntegral()->toString(10);
5012 break;
5013 }
5014
5015 case TemplateArgument::Expression: {
5016 assert(false && "No expressions in deduced template arguments!");
5017 Result += "<expression>";
5018 break;
5019 }
5020
5021 case TemplateArgument::Pack:
5022 // FIXME: Format template argument packs
5023 Result += "<template argument pack>";
5024 break;
5025 }
5026 }
5027
5028 Result += ']';
5029 return Result;
5030}