blob: 2fad8325d4dda930c6fe53c6c19f1766cbe72faa [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 Gregord2e6a452010-01-14 17:47:39 +00001611 if (TNK == TNK_Non_template &&
1612 isCurrentInstantiationWithDependentBases(SS)) {
1613 // This is a dependent template.
1614 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001615 Diag(Name.getSourceRange().getBegin(),
1616 diag::err_template_kw_refers_to_non_template)
1617 << GetNameFromUnqualifiedId(Name)
1618 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001619 return TemplateTy();
Douglas Gregord2e6a452010-01-14 17:47:39 +00001620 } else {
1621 // We found something; return it.
1622 return Template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001623 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001624 }
1625
Mike Stump11289f42009-09-09 15:08:12 +00001626 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001627 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001628
1629 switch (Name.getKind()) {
1630 case UnqualifiedId::IK_Identifier:
1631 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1632 Name.Identifier));
1633
Douglas Gregor71395fa2009-11-04 00:56:37 +00001634 case UnqualifiedId::IK_OperatorFunctionId:
1635 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1636 Name.OperatorFunctionId.Operator));
Alexis Hunted0530f2009-11-28 08:58:14 +00001637
1638 case UnqualifiedId::IK_LiteralOperatorId:
1639 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1640
Douglas Gregor3cf81312009-11-03 23:16:33 +00001641 default:
1642 break;
1643 }
1644
1645 Diag(Name.getSourceRange().getBegin(),
1646 diag::err_template_kw_refers_to_non_template)
1647 << GetNameFromUnqualifiedId(Name)
1648 << Name.getSourceRange();
1649 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001650}
1651
Mike Stump11289f42009-09-09 15:08:12 +00001652bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001653 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001654 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001655 const TemplateArgument &Arg = AL.getArgument();
1656
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001657 // Check template type parameter.
1658 if (Arg.getKind() != TemplateArgument::Type) {
1659 // C++ [temp.arg.type]p1:
1660 // A template-argument for a template-parameter which is a
1661 // type shall be a type-id.
1662
1663 // We have a template type parameter but the template argument
1664 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001665 SourceRange SR = AL.getSourceRange();
1666 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001667 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001668
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
John McCallbcd03502009-12-07 02:54:59 +00001672 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001673 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001674
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001675 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001676 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001677 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001678 return false;
1679}
1680
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001681/// \brief Substitute template arguments into the default template argument for
1682/// the given template type parameter.
1683///
1684/// \param SemaRef the semantic analysis object for which we are performing
1685/// the substitution.
1686///
1687/// \param Template the template that we are synthesizing template arguments
1688/// for.
1689///
1690/// \param TemplateLoc the location of the template name that started the
1691/// template-id we are checking.
1692///
1693/// \param RAngleLoc the location of the right angle bracket ('>') that
1694/// terminates the template-id.
1695///
1696/// \param Param the template template parameter whose default we are
1697/// substituting into.
1698///
1699/// \param Converted the list of template arguments provided for template
1700/// parameters that precede \p Param in the template parameter list.
1701///
1702/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001703static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001704SubstDefaultTemplateArgument(Sema &SemaRef,
1705 TemplateDecl *Template,
1706 SourceLocation TemplateLoc,
1707 SourceLocation RAngleLoc,
1708 TemplateTypeParmDecl *Param,
1709 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001710 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001711
1712 // If the argument type is dependent, instantiate it now based
1713 // on the previously-computed template arguments.
1714 if (ArgType->getType()->isDependentType()) {
1715 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1716 /*TakeArgs=*/false);
1717
1718 MultiLevelTemplateArgumentList AllTemplateArgs
1719 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1720
1721 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1722 Template, Converted.getFlatArguments(),
1723 Converted.flatSize(),
1724 SourceRange(TemplateLoc, RAngleLoc));
1725
1726 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1727 Param->getDefaultArgumentLoc(),
1728 Param->getDeclName());
1729 }
1730
1731 return ArgType;
1732}
1733
1734/// \brief Substitute template arguments into the default template argument for
1735/// the given non-type template parameter.
1736///
1737/// \param SemaRef the semantic analysis object for which we are performing
1738/// the substitution.
1739///
1740/// \param Template the template that we are synthesizing template arguments
1741/// for.
1742///
1743/// \param TemplateLoc the location of the template name that started the
1744/// template-id we are checking.
1745///
1746/// \param RAngleLoc the location of the right angle bracket ('>') that
1747/// terminates the template-id.
1748///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001749/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001750/// substituting into.
1751///
1752/// \param Converted the list of template arguments provided for template
1753/// parameters that precede \p Param in the template parameter list.
1754///
1755/// \returns the substituted template argument, or NULL if an error occurred.
1756static Sema::OwningExprResult
1757SubstDefaultTemplateArgument(Sema &SemaRef,
1758 TemplateDecl *Template,
1759 SourceLocation TemplateLoc,
1760 SourceLocation RAngleLoc,
1761 NonTypeTemplateParmDecl *Param,
1762 TemplateArgumentListBuilder &Converted) {
1763 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1764 /*TakeArgs=*/false);
1765
1766 MultiLevelTemplateArgumentList AllTemplateArgs
1767 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1768
1769 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1770 Template, Converted.getFlatArguments(),
1771 Converted.flatSize(),
1772 SourceRange(TemplateLoc, RAngleLoc));
1773
1774 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1775}
1776
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001777/// \brief Substitute template arguments into the default template argument for
1778/// the given template template parameter.
1779///
1780/// \param SemaRef the semantic analysis object for which we are performing
1781/// the substitution.
1782///
1783/// \param Template the template that we are synthesizing template arguments
1784/// for.
1785///
1786/// \param TemplateLoc the location of the template name that started the
1787/// template-id we are checking.
1788///
1789/// \param RAngleLoc the location of the right angle bracket ('>') that
1790/// terminates the template-id.
1791///
1792/// \param Param the template template parameter whose default we are
1793/// substituting into.
1794///
1795/// \param Converted the list of template arguments provided for template
1796/// parameters that precede \p Param in the template parameter list.
1797///
1798/// \returns the substituted template argument, or NULL if an error occurred.
1799static TemplateName
1800SubstDefaultTemplateArgument(Sema &SemaRef,
1801 TemplateDecl *Template,
1802 SourceLocation TemplateLoc,
1803 SourceLocation RAngleLoc,
1804 TemplateTemplateParmDecl *Param,
1805 TemplateArgumentListBuilder &Converted) {
1806 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1807 /*TakeArgs=*/false);
1808
1809 MultiLevelTemplateArgumentList AllTemplateArgs
1810 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1811
1812 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1813 Template, Converted.getFlatArguments(),
1814 Converted.flatSize(),
1815 SourceRange(TemplateLoc, RAngleLoc));
1816
1817 return SemaRef.SubstTemplateName(
1818 Param->getDefaultArgument().getArgument().getAsTemplate(),
1819 Param->getDefaultArgument().getTemplateNameLoc(),
1820 AllTemplateArgs);
1821}
1822
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001823/// \brief If the given template parameter has a default template
1824/// argument, substitute into that default template argument and
1825/// return the corresponding template argument.
1826TemplateArgumentLoc
1827Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1828 SourceLocation TemplateLoc,
1829 SourceLocation RAngleLoc,
1830 Decl *Param,
1831 TemplateArgumentListBuilder &Converted) {
1832 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1833 if (!TypeParm->hasDefaultArgument())
1834 return TemplateArgumentLoc();
1835
John McCallbcd03502009-12-07 02:54:59 +00001836 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001837 TemplateLoc,
1838 RAngleLoc,
1839 TypeParm,
1840 Converted);
1841 if (DI)
1842 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1843
1844 return TemplateArgumentLoc();
1845 }
1846
1847 if (NonTypeTemplateParmDecl *NonTypeParm
1848 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1849 if (!NonTypeParm->hasDefaultArgument())
1850 return TemplateArgumentLoc();
1851
1852 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1853 TemplateLoc,
1854 RAngleLoc,
1855 NonTypeParm,
1856 Converted);
1857 if (Arg.isInvalid())
1858 return TemplateArgumentLoc();
1859
1860 Expr *ArgE = Arg.takeAs<Expr>();
1861 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1862 }
1863
1864 TemplateTemplateParmDecl *TempTempParm
1865 = cast<TemplateTemplateParmDecl>(Param);
1866 if (!TempTempParm->hasDefaultArgument())
1867 return TemplateArgumentLoc();
1868
1869 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1870 TemplateLoc,
1871 RAngleLoc,
1872 TempTempParm,
1873 Converted);
1874 if (TName.isNull())
1875 return TemplateArgumentLoc();
1876
1877 return TemplateArgumentLoc(TemplateArgument(TName),
1878 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1879 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1880}
1881
Douglas Gregorda0fb532009-11-11 19:31:23 +00001882/// \brief Check that the given template argument corresponds to the given
1883/// template parameter.
1884bool Sema::CheckTemplateArgument(NamedDecl *Param,
1885 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001886 TemplateDecl *Template,
1887 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001888 SourceLocation RAngleLoc,
1889 TemplateArgumentListBuilder &Converted) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001890 // Check template type parameters.
1891 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001892 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001893
Douglas Gregoreebed722009-11-11 19:41:09 +00001894 // Check non-type template parameters.
1895 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001896 // Do substitution on the type of the non-type template parameter
1897 // with the template arguments we've seen thus far.
1898 QualType NTTPType = NTTP->getType();
1899 if (NTTPType->isDependentType()) {
1900 // Do substitution on the type of the non-type template parameter.
1901 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1902 NTTP, Converted.getFlatArguments(),
1903 Converted.flatSize(),
1904 SourceRange(TemplateLoc, RAngleLoc));
1905
1906 TemplateArgumentList TemplateArgs(Context, Converted,
1907 /*TakeArgs=*/false);
1908 NTTPType = SubstType(NTTPType,
1909 MultiLevelTemplateArgumentList(TemplateArgs),
1910 NTTP->getLocation(),
1911 NTTP->getDeclName());
1912 // If that worked, check the non-type template parameter type
1913 // for validity.
1914 if (!NTTPType.isNull())
1915 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1916 NTTP->getLocation());
1917 if (NTTPType.isNull())
1918 return true;
1919 }
1920
1921 switch (Arg.getArgument().getKind()) {
1922 case TemplateArgument::Null:
1923 assert(false && "Should never see a NULL template argument here");
1924 return true;
1925
1926 case TemplateArgument::Expression: {
1927 Expr *E = Arg.getArgument().getAsExpr();
1928 TemplateArgument Result;
1929 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1930 return true;
1931
1932 Converted.Append(Result);
1933 break;
1934 }
1935
1936 case TemplateArgument::Declaration:
1937 case TemplateArgument::Integral:
1938 // We've already checked this template argument, so just copy
1939 // it to the list of converted arguments.
1940 Converted.Append(Arg.getArgument());
1941 break;
1942
1943 case TemplateArgument::Template:
1944 // We were given a template template argument. It may not be ill-formed;
1945 // see below.
1946 if (DependentTemplateName *DTN
1947 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1948 // We have a template argument such as \c T::template X, which we
1949 // parsed as a template template argument. However, since we now
1950 // know that we need a non-type template argument, convert this
1951 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00001952 Expr *E = DependentScopeDeclRefExpr::Create(Context,
1953 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00001954 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00001955 DTN->getIdentifier(),
1956 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00001957
1958 TemplateArgument Result;
1959 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1960 return true;
1961
1962 Converted.Append(Result);
1963 break;
1964 }
1965
1966 // We have a template argument that actually does refer to a class
1967 // template, template alias, or template template parameter, and
1968 // therefore cannot be a non-type template argument.
1969 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1970 << Arg.getSourceRange();
1971
1972 Diag(Param->getLocation(), diag::note_template_param_here);
1973 return true;
1974
1975 case TemplateArgument::Type: {
1976 // We have a non-type template parameter but the template
1977 // argument is a type.
1978
1979 // C++ [temp.arg]p2:
1980 // In a template-argument, an ambiguity between a type-id and
1981 // an expression is resolved to a type-id, regardless of the
1982 // form of the corresponding template-parameter.
1983 //
1984 // We warn specifically about this case, since it can be rather
1985 // confusing for users.
1986 QualType T = Arg.getArgument().getAsType();
1987 SourceRange SR = Arg.getSourceRange();
1988 if (T->isFunctionType())
1989 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1990 else
1991 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1992 Diag(Param->getLocation(), diag::note_template_param_here);
1993 return true;
1994 }
1995
1996 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001997 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00001998 break;
1999 }
2000
2001 return false;
2002 }
2003
2004
2005 // Check template template parameters.
2006 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2007
2008 // Substitute into the template parameter list of the template
2009 // template parameter, since previously-supplied template arguments
2010 // may appear within the template template parameter.
2011 {
2012 // Set up a template instantiation context.
2013 LocalInstantiationScope Scope(*this);
2014 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2015 TempParm, Converted.getFlatArguments(),
2016 Converted.flatSize(),
2017 SourceRange(TemplateLoc, RAngleLoc));
2018
2019 TemplateArgumentList TemplateArgs(Context, Converted,
2020 /*TakeArgs=*/false);
2021 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2022 SubstDecl(TempParm, CurContext,
2023 MultiLevelTemplateArgumentList(TemplateArgs)));
2024 if (!TempParm)
2025 return true;
2026
2027 // FIXME: TempParam is leaked.
2028 }
2029
2030 switch (Arg.getArgument().getKind()) {
2031 case TemplateArgument::Null:
2032 assert(false && "Should never see a NULL template argument here");
2033 return true;
2034
2035 case TemplateArgument::Template:
2036 if (CheckTemplateArgument(TempParm, Arg))
2037 return true;
2038
2039 Converted.Append(Arg.getArgument());
2040 break;
2041
2042 case TemplateArgument::Expression:
2043 case TemplateArgument::Type:
2044 // We have a template template parameter but the template
2045 // argument does not refer to a template.
2046 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2047 return true;
2048
2049 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002050 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002051 "Declaration argument with template template parameter");
2052 break;
2053 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002054 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002055 "Integral argument with template template parameter");
2056 break;
2057
2058 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002059 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002060 break;
2061 }
2062
2063 return false;
2064}
2065
Douglas Gregord32e0282009-02-09 23:23:08 +00002066/// \brief Check that the given template argument list is well-formed
2067/// for specializing the given template.
2068bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2069 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002070 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002071 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002072 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002073 TemplateParameterList *Params = Template->getTemplateParameters();
2074 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002075 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002076 bool Invalid = false;
2077
John McCall6b51f282009-11-23 01:53:49 +00002078 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2079
Mike Stump11289f42009-09-09 15:08:12 +00002080 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002081 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002082
Anders Carlsson15201f12009-06-13 02:08:00 +00002083 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002084 (NumArgs < Params->getMinRequiredArguments() &&
2085 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002086 // FIXME: point at either the first arg beyond what we can handle,
2087 // or the '>', depending on whether we have too many or too few
2088 // arguments.
2089 SourceRange Range;
2090 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002091 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002092 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2093 << (NumArgs > NumParams)
2094 << (isa<ClassTemplateDecl>(Template)? 0 :
2095 isa<FunctionTemplateDecl>(Template)? 1 :
2096 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2097 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002098 Diag(Template->getLocation(), diag::note_template_decl_here)
2099 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002100 Invalid = true;
2101 }
Mike Stump11289f42009-09-09 15:08:12 +00002102
2103 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002104 // [...] The type and form of each template-argument specified in
2105 // a template-id shall match the type and form specified for the
2106 // corresponding parameter declared by the template in its
2107 // template-parameter-list.
2108 unsigned ArgIdx = 0;
2109 for (TemplateParameterList::iterator Param = Params->begin(),
2110 ParamEnd = Params->end();
2111 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002112 if (ArgIdx > NumArgs && PartialTemplateArgs)
2113 break;
Mike Stump11289f42009-09-09 15:08:12 +00002114
Douglas Gregoreebed722009-11-11 19:41:09 +00002115 // If we have a template parameter pack, check every remaining template
2116 // argument against that template parameter pack.
2117 if ((*Param)->isTemplateParameterPack()) {
2118 Converted.BeginPack();
2119 for (; ArgIdx < NumArgs; ++ArgIdx) {
2120 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2121 TemplateLoc, RAngleLoc, Converted)) {
2122 Invalid = true;
2123 break;
2124 }
2125 }
2126 Converted.EndPack();
2127 continue;
2128 }
2129
Douglas Gregor84d49a22009-11-11 21:54:23 +00002130 if (ArgIdx < NumArgs) {
2131 // Check the template argument we were given.
2132 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2133 TemplateLoc, RAngleLoc, Converted))
2134 return true;
2135
2136 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002137 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002138
Douglas Gregor84d49a22009-11-11 21:54:23 +00002139 // We have a default template argument that we will use.
2140 TemplateArgumentLoc Arg;
2141
2142 // Retrieve the default template argument from the template
2143 // parameter. For each kind of template parameter, we substitute the
2144 // template arguments provided thus far and any "outer" template arguments
2145 // (when the template parameter was part of a nested template) into
2146 // the default argument.
2147 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2148 if (!TTP->hasDefaultArgument()) {
2149 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2150 break;
2151 }
2152
John McCallbcd03502009-12-07 02:54:59 +00002153 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002154 Template,
2155 TemplateLoc,
2156 RAngleLoc,
2157 TTP,
2158 Converted);
2159 if (!ArgType)
2160 return true;
2161
2162 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2163 ArgType);
2164 } else if (NonTypeTemplateParmDecl *NTTP
2165 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2166 if (!NTTP->hasDefaultArgument()) {
2167 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2168 break;
2169 }
2170
2171 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2172 TemplateLoc,
2173 RAngleLoc,
2174 NTTP,
2175 Converted);
2176 if (E.isInvalid())
2177 return true;
2178
2179 Expr *Ex = E.takeAs<Expr>();
2180 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2181 } else {
2182 TemplateTemplateParmDecl *TempParm
2183 = cast<TemplateTemplateParmDecl>(*Param);
2184
2185 if (!TempParm->hasDefaultArgument()) {
2186 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2187 break;
2188 }
2189
2190 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2191 TemplateLoc,
2192 RAngleLoc,
2193 TempParm,
2194 Converted);
2195 if (Name.isNull())
2196 return true;
2197
2198 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2199 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2200 TempParm->getDefaultArgument().getTemplateNameLoc());
2201 }
2202
2203 // Introduce an instantiation record that describes where we are using
2204 // the default template argument.
2205 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2206 Converted.getFlatArguments(),
2207 Converted.flatSize(),
2208 SourceRange(TemplateLoc, RAngleLoc));
2209
2210 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002211 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002212 RAngleLoc, Converted))
2213 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002214 }
2215
2216 return Invalid;
2217}
2218
2219/// \brief Check a template argument against its corresponding
2220/// template type parameter.
2221///
2222/// This routine implements the semantics of C++ [temp.arg.type]. It
2223/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002224bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002225 TypeSourceInfo *ArgInfo) {
2226 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002227 QualType Arg = ArgInfo->getType();
2228
Douglas Gregord32e0282009-02-09 23:23:08 +00002229 // C++ [temp.arg.type]p2:
2230 // A local type, a type with no linkage, an unnamed type or a type
2231 // compounded from any of these types shall not be used as a
2232 // template-argument for a template type-parameter.
2233 //
2234 // FIXME: Perform the recursive and no-linkage type checks.
2235 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002236 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002237 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002238 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002239 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002240 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2241 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2242 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2243 << QualType(Tag, 0) << SR;
2244 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002245 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002246 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2247 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002248 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2249 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002250 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2251 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2252 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002253 }
2254
2255 return false;
2256}
2257
Douglas Gregorccb07762009-02-11 19:52:55 +00002258/// \brief Checks whether the given template argument is the address
2259/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002260bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2261 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002262 bool Invalid = false;
2263
2264 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002265 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002266 Arg = Cast->getSubExpr();
2267
Sebastian Redl576fd422009-05-10 18:38:11 +00002268 // C++0x allows nullptr, and there's no further checking to be done for that.
2269 if (Arg->getType()->isNullPtrType())
2270 return false;
2271
Douglas Gregorccb07762009-02-11 19:52:55 +00002272 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002273 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002274 // A template-argument for a non-type, non-template
2275 // template-parameter shall be one of: [...]
2276 //
2277 // -- the address of an object or function with external
2278 // linkage, including function templates and function
2279 // template-ids but excluding non-static class members,
2280 // expressed as & id-expression where the & is optional if
2281 // the name refers to a function or array, or if the
2282 // corresponding template-parameter is a reference; or
2283 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002284
Douglas Gregorccb07762009-02-11 19:52:55 +00002285 // Ignore (and complain about) any excess parentheses.
2286 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2287 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002288 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002289 diag::err_template_arg_extra_parens)
2290 << Arg->getSourceRange();
2291 Invalid = true;
2292 }
2293
2294 Arg = Parens->getSubExpr();
2295 }
2296
2297 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2298 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2299 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2300 } else
2301 DRE = dyn_cast<DeclRefExpr>(Arg);
2302
2303 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00002304 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002305 diag::err_template_arg_not_object_or_func_form)
2306 << Arg->getSourceRange();
2307
2308 // Cannot refer to non-static data members
2309 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2310 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2311 << Field << Arg->getSourceRange();
2312
2313 // Cannot refer to non-static member functions
2314 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2315 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00002316 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002317 diag::err_template_arg_method)
2318 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002319
Douglas Gregorccb07762009-02-11 19:52:55 +00002320 // Functions must have external linkage.
2321 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregorf73b2822009-11-25 22:24:25 +00002322 if (Func->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump11289f42009-09-09 15:08:12 +00002323 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002324 diag::err_template_arg_function_not_extern)
2325 << Func << Arg->getSourceRange();
2326 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2327 << true;
2328 return true;
2329 }
2330
2331 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002332 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002333 return Invalid;
2334 }
2335
2336 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregorf73b2822009-11-25 22:24:25 +00002337 if (Var->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump11289f42009-09-09 15:08:12 +00002338 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002339 diag::err_template_arg_object_not_extern)
2340 << Var << Arg->getSourceRange();
2341 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2342 << true;
2343 return true;
2344 }
2345
2346 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002347 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00002348 return Invalid;
2349 }
Mike Stump11289f42009-09-09 15:08:12 +00002350
Douglas Gregorccb07762009-02-11 19:52:55 +00002351 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002352 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002353 diag::err_template_arg_not_object_or_func)
2354 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002355 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002356 diag::note_template_arg_refers_here);
2357 return true;
2358}
2359
2360/// \brief Checks whether the given template argument is a pointer to
2361/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002362bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2363 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002364 bool Invalid = false;
2365
2366 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002367 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002368 Arg = Cast->getSubExpr();
2369
Sebastian Redl576fd422009-05-10 18:38:11 +00002370 // C++0x allows nullptr, and there's no further checking to be done for that.
2371 if (Arg->getType()->isNullPtrType())
2372 return false;
2373
Douglas Gregorccb07762009-02-11 19:52:55 +00002374 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002375 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002376 // A template-argument for a non-type, non-template
2377 // template-parameter shall be one of: [...]
2378 //
2379 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002380 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002381
2382 // Ignore (and complain about) any excess parentheses.
2383 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2384 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002385 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002386 diag::err_template_arg_extra_parens)
2387 << Arg->getSourceRange();
2388 Invalid = true;
2389 }
2390
2391 Arg = Parens->getSubExpr();
2392 }
2393
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002394 // A pointer-to-member constant written &Class::member.
2395 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002396 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2397 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2398 if (DRE && !DRE->getQualifier())
2399 DRE = 0;
2400 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002401 }
2402 // A constant of pointer-to-member type.
2403 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2404 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2405 if (VD->getType()->isMemberPointerType()) {
2406 if (isa<NonTypeTemplateParmDecl>(VD) ||
2407 (isa<VarDecl>(VD) &&
2408 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2409 if (Arg->isTypeDependent() || Arg->isValueDependent())
2410 Converted = TemplateArgument(Arg->Retain());
2411 else
2412 Converted = TemplateArgument(VD->getCanonicalDecl());
2413 return Invalid;
2414 }
2415 }
2416 }
2417
2418 DRE = 0;
2419 }
2420
Douglas Gregorccb07762009-02-11 19:52:55 +00002421 if (!DRE)
2422 return Diag(Arg->getSourceRange().getBegin(),
2423 diag::err_template_arg_not_pointer_to_member_form)
2424 << Arg->getSourceRange();
2425
2426 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2427 assert((isa<FieldDecl>(DRE->getDecl()) ||
2428 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2429 "Only non-static member pointers can make it here");
2430
2431 // Okay: this is the address of a non-static member, and therefore
2432 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002433 if (Arg->isTypeDependent() || Arg->isValueDependent())
2434 Converted = TemplateArgument(Arg->Retain());
2435 else
2436 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002437 return Invalid;
2438 }
2439
2440 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002441 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002442 diag::err_template_arg_not_pointer_to_member_form)
2443 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002444 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002445 diag::note_template_arg_refers_here);
2446 return true;
2447}
2448
Douglas Gregord32e0282009-02-09 23:23:08 +00002449/// \brief Check a template argument against its corresponding
2450/// non-type template parameter.
2451///
Douglas Gregor463421d2009-03-03 04:44:36 +00002452/// This routine implements the semantics of C++ [temp.arg.nontype].
2453/// It returns true if an error occurred, and false otherwise. \p
2454/// InstantiatedParamType is the type of the non-type template
2455/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002456///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002457/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002458bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002459 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002460 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002461 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2462
Douglas Gregor86560402009-02-10 23:36:10 +00002463 // If either the parameter has a dependent type or the argument is
2464 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002465 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00002466 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2467 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002468 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002469 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002470 }
Douglas Gregor86560402009-02-10 23:36:10 +00002471
2472 // C++ [temp.arg.nontype]p5:
2473 // The following conversions are performed on each expression used
2474 // as a non-type template-argument. If a non-type
2475 // template-argument cannot be converted to the type of the
2476 // corresponding template-parameter then the program is
2477 // ill-formed.
2478 //
2479 // -- for a non-type template-parameter of integral or
2480 // enumeration type, integral promotions (4.5) and integral
2481 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002482 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002483 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002484 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002485 // C++ [temp.arg.nontype]p1:
2486 // A template-argument for a non-type, non-template
2487 // template-parameter shall be one of:
2488 //
2489 // -- an integral constant-expression of integral or enumeration
2490 // type; or
2491 // -- the name of a non-type template-parameter; or
2492 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002493 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002494 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002495 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002496 diag::err_template_arg_not_integral_or_enumeral)
2497 << ArgType << Arg->getSourceRange();
2498 Diag(Param->getLocation(), diag::note_template_param_here);
2499 return true;
2500 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002501 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002502 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2503 << ArgType << Arg->getSourceRange();
2504 return true;
2505 }
2506
2507 // FIXME: We need some way to more easily get the unqualified form
2508 // of the types without going all the way to the
2509 // canonical type.
2510 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2511 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2512 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2513 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2514
2515 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002516 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002517 // Okay: no conversion necessary
2518 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2519 !ParamType->isEnumeralType()) {
2520 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002521 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002522 } else {
2523 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002524 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002525 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002526 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002527 Diag(Param->getLocation(), diag::note_template_param_here);
2528 return true;
2529 }
2530
Douglas Gregor52aba872009-03-14 00:20:21 +00002531 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002532 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002533 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002534
2535 if (!Arg->isValueDependent()) {
2536 // Check that an unsigned parameter does not receive a negative
2537 // value.
2538 if (IntegerType->isUnsignedIntegerType()
2539 && (Value.isSigned() && Value.isNegative())) {
2540 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2541 << Value.toString(10) << Param->getType()
2542 << Arg->getSourceRange();
2543 Diag(Param->getLocation(), diag::note_template_param_here);
2544 return true;
2545 }
2546
2547 // Check that we don't overflow the template parameter type.
2548 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Eli Friedman38b9ad82009-12-23 18:44:58 +00002549 unsigned RequiredBits;
2550 if (IntegerType->isUnsignedIntegerType())
2551 RequiredBits = Value.getActiveBits();
2552 else if (Value.isUnsigned())
2553 RequiredBits = Value.getActiveBits() + 1;
2554 else
2555 RequiredBits = Value.getMinSignedBits();
2556 if (RequiredBits > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00002557 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00002558 diag::err_template_arg_too_large)
2559 << Value.toString(10) << Param->getType()
2560 << Arg->getSourceRange();
2561 Diag(Param->getLocation(), diag::note_template_param_here);
2562 return true;
2563 }
2564
2565 if (Value.getBitWidth() != AllowedBits)
2566 Value.extOrTrunc(AllowedBits);
2567 Value.setIsSigned(IntegerType->isSignedIntegerType());
2568 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002569
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002570 // Add the value of this argument to the list of converted
2571 // arguments. We use the bitwidth and signedness of the template
2572 // parameter.
2573 if (Arg->isValueDependent()) {
2574 // The argument is value-dependent. Create a new
2575 // TemplateArgument with the converted expression.
2576 Converted = TemplateArgument(Arg);
2577 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002578 }
2579
John McCall0ad16662009-10-29 08:12:44 +00002580 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002581 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002582 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002583 return false;
2584 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002585
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002586 // Handle pointer-to-function, reference-to-function, and
2587 // pointer-to-member-function all in (roughly) the same way.
2588 if (// -- For a non-type template-parameter of type pointer to
2589 // function, only the function-to-pointer conversion (4.3) is
2590 // applied. If the template-argument represents a set of
2591 // overloaded functions (or a pointer to such), the matching
2592 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002593 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002594 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002595 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002596 // -- For a non-type template-parameter of type reference to
2597 // function, no conversions apply. If the template-argument
2598 // represents a set of overloaded functions, the matching
2599 // function is selected from the set (13.4).
2600 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002601 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002602 // -- For a non-type template-parameter of type pointer to
2603 // member function, no conversions apply. If the
2604 // template-argument represents a set of overloaded member
2605 // functions, the matching member function is selected from
2606 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002607 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002608 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002609 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002610 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002611 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002612 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002613 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002614 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2615 ParamType->isMemberPointerType())) {
2616 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002617 if (ParamType->isMemberPointerType())
2618 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2619 else
2620 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002621 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002622 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002623 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002624 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002625 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002626 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2627 return true;
2628
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002629 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002630 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002631 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002632 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002633 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002634 }
2635 }
2636
Mike Stump11289f42009-09-09 15:08:12 +00002637 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002638 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002639 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002640 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002641 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002642 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002643 Diag(Param->getLocation(), diag::note_template_param_here);
2644 return true;
2645 }
Mike Stump11289f42009-09-09 15:08:12 +00002646
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002647 if (ParamType->isMemberPointerType())
2648 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump11289f42009-09-09 15:08:12 +00002649
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002650 NamedDecl *Entity = 0;
2651 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2652 return true;
2653
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002654 if (Entity)
2655 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002656 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002657 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002658 }
2659
Chris Lattner696197c2009-02-20 21:37:53 +00002660 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002661 // -- for a non-type template-parameter of type pointer to
2662 // object, qualification conversions (4.4) and the
2663 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002664 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002665 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002666 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002667
Sebastian Redl576fd422009-05-10 18:38:11 +00002668 if (ArgType->isNullPtrType()) {
2669 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002670 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002671 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002672 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002673 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002674 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002675
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002676 if (IsQualificationConversion(ArgType, ParamType)) {
2677 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002678 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002679 }
Mike Stump11289f42009-09-09 15:08:12 +00002680
Douglas Gregor1515f762009-02-11 18:22:40 +00002681 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002682 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002683 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002684 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002685 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002686 Diag(Param->getLocation(), diag::note_template_param_here);
2687 return true;
2688 }
Mike Stump11289f42009-09-09 15:08:12 +00002689
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002690 NamedDecl *Entity = 0;
2691 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2692 return true;
2693
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002694 if (Entity)
2695 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002696 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002697 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002698 }
Mike Stump11289f42009-09-09 15:08:12 +00002699
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002700 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002701 // -- For a non-type template-parameter of type reference to
2702 // object, no conversions apply. The type referred to by the
2703 // reference may be more cv-qualified than the (otherwise
2704 // identical) type of the template-argument. The
2705 // template-parameter is bound directly to the
2706 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002707 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002708 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002709
Douglas Gregor1515f762009-02-11 18:22:40 +00002710 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002711 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002712 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002713 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002714 << Arg->getSourceRange();
2715 Diag(Param->getLocation(), diag::note_template_param_here);
2716 return true;
2717 }
2718
Mike Stump11289f42009-09-09 15:08:12 +00002719 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002720 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2721 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002722
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002723 if ((ParamQuals | ArgQuals) != ParamQuals) {
2724 Diag(Arg->getSourceRange().getBegin(),
2725 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002726 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002727 << Arg->getSourceRange();
2728 Diag(Param->getLocation(), diag::note_template_param_here);
2729 return true;
2730 }
Mike Stump11289f42009-09-09 15:08:12 +00002731
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002732 NamedDecl *Entity = 0;
2733 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2734 return true;
2735
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002736 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002737 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002738 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002739 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002740
2741 // -- For a non-type template-parameter of type pointer to data
2742 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002743 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002744 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2745
Douglas Gregor1515f762009-02-11 18:22:40 +00002746 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002747 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002748 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002749 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002750 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002751 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002752 } else {
2753 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002754 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002755 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002756 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002757 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002758 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002759 }
2760
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002761 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002762}
2763
2764/// \brief Check a template argument against its corresponding
2765/// template template parameter.
2766///
2767/// This routine implements the semantics of C++ [temp.arg.template].
2768/// It returns true if an error occurred, and false otherwise.
2769bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002770 const TemplateArgumentLoc &Arg) {
2771 TemplateName Name = Arg.getArgument().getAsTemplate();
2772 TemplateDecl *Template = Name.getAsTemplateDecl();
2773 if (!Template) {
2774 // Any dependent template name is fine.
2775 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2776 return false;
2777 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002778
2779 // C++ [temp.arg.template]p1:
2780 // A template-argument for a template template-parameter shall be
2781 // the name of a class template, expressed as id-expression. Only
2782 // primary class templates are considered when matching the
2783 // template template argument with the corresponding parameter;
2784 // partial specializations are not considered even if their
2785 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002786 //
2787 // Note that we also allow template template parameters here, which
2788 // will happen when we are dealing with, e.g., class template
2789 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002790 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002791 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002792 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002793 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002794 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002795 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002796 << Template;
2797 }
2798
2799 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2800 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002801 true,
2802 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002803 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002804}
2805
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002806/// \brief Determine whether the given template parameter lists are
2807/// equivalent.
2808///
Mike Stump11289f42009-09-09 15:08:12 +00002809/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002810/// source code as part of a new template declaration.
2811///
2812/// \param Old The old template parameter list, typically found via
2813/// name lookup of the template declared with this template parameter
2814/// list.
2815///
2816/// \param Complain If true, this routine will produce a diagnostic if
2817/// the template parameter lists are not equivalent.
2818///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002819/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00002820///
2821/// \param TemplateArgLoc If this source location is valid, then we
2822/// are actually checking the template parameter list of a template
2823/// argument (New) against the template parameter list of its
2824/// corresponding template template parameter (Old). We produce
2825/// slightly different diagnostics in this scenario.
2826///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002827/// \returns True if the template parameter lists are equal, false
2828/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002829bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002830Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2831 TemplateParameterList *Old,
2832 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002833 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002834 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002835 if (Old->size() != New->size()) {
2836 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002837 unsigned NextDiag = diag::err_template_param_list_different_arity;
2838 if (TemplateArgLoc.isValid()) {
2839 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2840 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002841 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002842 Diag(New->getTemplateLoc(), NextDiag)
2843 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002844 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002845 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002846 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002847 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002848 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2849 }
2850
2851 return false;
2852 }
2853
2854 for (TemplateParameterList::iterator OldParm = Old->begin(),
2855 OldParmEnd = Old->end(), NewParm = New->begin();
2856 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2857 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002858 if (Complain) {
2859 unsigned NextDiag = diag::err_template_param_different_kind;
2860 if (TemplateArgLoc.isValid()) {
2861 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2862 NextDiag = diag::note_template_param_different_kind;
2863 }
2864 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002865 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00002866 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002867 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00002868 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002869 return false;
2870 }
2871
2872 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2873 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002874 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00002875 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002876 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2877 // The types of non-type template parameters must agree.
2878 NonTypeTemplateParmDecl *NewNTTP
2879 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002880
2881 // If we are matching a template template argument to a template
2882 // template parameter and one of the non-type template parameter types
2883 // is dependent, then we must wait until template instantiation time
2884 // to actually compare the arguments.
2885 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2886 (OldNTTP->getType()->isDependentType() ||
2887 NewNTTP->getType()->isDependentType()))
2888 continue;
2889
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002890 if (Context.getCanonicalType(OldNTTP->getType()) !=
2891 Context.getCanonicalType(NewNTTP->getType())) {
2892 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002893 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2894 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002895 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002896 diag::err_template_arg_template_params_mismatch);
2897 NextDiag = diag::note_template_nontype_parm_different_type;
2898 }
2899 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002900 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002901 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00002902 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002903 diag::note_template_nontype_parm_prev_declaration)
2904 << OldNTTP->getType();
2905 }
2906 return false;
2907 }
2908 } else {
2909 // The template parameter lists of template template
2910 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00002911 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002912 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002913 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002914 = cast<TemplateTemplateParmDecl>(*OldParm);
2915 TemplateTemplateParmDecl *NewTTP
2916 = cast<TemplateTemplateParmDecl>(*NewParm);
2917 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2918 OldTTP->getTemplateParameters(),
2919 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002920 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00002921 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002922 return false;
2923 }
2924 }
2925
2926 return true;
2927}
2928
2929/// \brief Check whether a template can be declared within this scope.
2930///
2931/// If the template declaration is valid in this scope, returns
2932/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002933bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002934Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002935 // Find the nearest enclosing declaration scope.
2936 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2937 (S->getFlags() & Scope::TemplateParamScope) != 0)
2938 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002939
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002940 // C++ [temp]p2:
2941 // A template-declaration can appear only as a namespace scope or
2942 // class scope declaration.
2943 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002944 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2945 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002946 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002947 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002948
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002949 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002950 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002951
2952 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2953 return false;
2954
Mike Stump11289f42009-09-09 15:08:12 +00002955 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002956 diag::err_template_outside_namespace_or_class_scope)
2957 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002958}
Douglas Gregor67a65642009-02-17 23:15:12 +00002959
Douglas Gregor54888652009-10-07 00:13:32 +00002960/// \brief Determine what kind of template specialization the given declaration
2961/// is.
2962static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2963 if (!D)
2964 return TSK_Undeclared;
2965
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002966 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2967 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00002968 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2969 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002970 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2971 return Var->getTemplateSpecializationKind();
2972
Douglas Gregor54888652009-10-07 00:13:32 +00002973 return TSK_Undeclared;
2974}
2975
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002976/// \brief Check whether a specialization is well-formed in the current
2977/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002978///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002979/// This routine determines whether a template specialization can be declared
2980/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00002981///
2982/// \param S the semantic analysis object for which this check is being
2983/// performed.
2984///
2985/// \param Specialized the entity being specialized or instantiated, which
2986/// may be a kind of template (class template, function template, etc.) or
2987/// a member of a class template (member function, static data member,
2988/// member class).
2989///
2990/// \param PrevDecl the previous declaration of this entity, if any.
2991///
2992/// \param Loc the location of the explicit specialization or instantiation of
2993/// this entity.
2994///
2995/// \param IsPartialSpecialization whether this is a partial specialization of
2996/// a class template.
2997///
Douglas Gregor54888652009-10-07 00:13:32 +00002998/// \returns true if there was an error that we cannot recover from, false
2999/// otherwise.
3000static bool CheckTemplateSpecializationScope(Sema &S,
3001 NamedDecl *Specialized,
3002 NamedDecl *PrevDecl,
3003 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003004 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003005 // Keep these "kind" numbers in sync with the %select statements in the
3006 // various diagnostics emitted by this routine.
3007 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003008 bool isTemplateSpecialization = false;
3009 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003010 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003011 isTemplateSpecialization = true;
3012 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003013 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003014 isTemplateSpecialization = true;
3015 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003016 EntityKind = 3;
3017 else if (isa<VarDecl>(Specialized))
3018 EntityKind = 4;
3019 else if (isa<RecordDecl>(Specialized))
3020 EntityKind = 5;
3021 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003022 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3023 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003024 return true;
3025 }
3026
Douglas Gregorf47b9112009-02-25 22:02:03 +00003027 // C++ [temp.expl.spec]p2:
3028 // An explicit specialization shall be declared in the namespace
3029 // of which the template is a member, or, for member templates, in
3030 // the namespace of which the enclosing class or enclosing class
3031 // template is a member. An explicit specialization of a member
3032 // function, member class or static data member of a class
3033 // template shall be declared in the namespace of which the class
3034 // template is a member. Such a declaration may also be a
3035 // definition. If the declaration is not a definition, the
3036 // specialization may be defined later in the name- space in which
3037 // the explicit specialization was declared, or in a namespace
3038 // that encloses the one in which the explicit specialization was
3039 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003040 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3041 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003042 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003043 return true;
3044 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003045
Douglas Gregor40fb7442009-10-07 17:30:37 +00003046 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3047 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003048 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003049 return true;
3050 }
3051
Douglas Gregore4b05162009-10-07 17:21:34 +00003052 // C++ [temp.class.spec]p6:
3053 // A class template partial specialization may be declared or redeclared
3054 // in any namespace scope in which its definition may be defined (14.5.1
3055 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003056 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003057 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003058 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003059 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003060 if ((!PrevDecl ||
3061 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3062 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3063 // There is no prior declaration of this entity, so this
3064 // specialization must be in the same context as the template
3065 // itself.
3066 if (!DC->Equals(SpecializedContext)) {
3067 if (isa<TranslationUnitDecl>(SpecializedContext))
3068 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3069 << EntityKind << Specialized;
3070 else if (isa<NamespaceDecl>(SpecializedContext))
3071 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3072 << EntityKind << Specialized
3073 << cast<NamedDecl>(SpecializedContext);
3074
3075 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3076 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003077 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003078 }
Douglas Gregor54888652009-10-07 00:13:32 +00003079
3080 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003081 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003082 // Note that HandleDeclarator() performs this check for explicit
3083 // specializations of function templates, static data members, and member
3084 // functions, so we skip the check here for those kinds of entities.
3085 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003086 // Should we refactor that check, so that it occurs later?
3087 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003088 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3089 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003090 if (isa<TranslationUnitDecl>(SpecializedContext))
3091 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3092 << EntityKind << Specialized;
3093 else if (isa<NamespaceDecl>(SpecializedContext))
3094 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3095 << EntityKind << Specialized
3096 << cast<NamedDecl>(SpecializedContext);
3097
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003098 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003099 }
Douglas Gregor54888652009-10-07 00:13:32 +00003100
3101 // FIXME: check for specialization-after-instantiation errors and such.
3102
Douglas Gregorf47b9112009-02-25 22:02:03 +00003103 return false;
3104}
Douglas Gregor54888652009-10-07 00:13:32 +00003105
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003106/// \brief Check the non-type template arguments of a class template
3107/// partial specialization according to C++ [temp.class.spec]p9.
3108///
Douglas Gregor09a30232009-06-12 22:08:06 +00003109/// \param TemplateParams the template parameters of the primary class
3110/// template.
3111///
3112/// \param TemplateArg the template arguments of the class template
3113/// partial specialization.
3114///
3115/// \param MirrorsPrimaryTemplate will be set true if the class
3116/// template partial specialization arguments are identical to the
3117/// implicit template arguments of the primary template. This is not
3118/// necessarily an error (C++0x), and it is left to the caller to diagnose
3119/// this condition when it is an error.
3120///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003121/// \returns true if there was an error, false otherwise.
3122bool Sema::CheckClassTemplatePartialSpecializationArgs(
3123 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003124 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003125 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003126 // FIXME: the interface to this function will have to change to
3127 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003128 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003129
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003130 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003131
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003132 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003133 // Determine whether the template argument list of the partial
3134 // specialization is identical to the implicit argument list of
3135 // the primary template. The caller may need to diagnostic this as
3136 // an error per C++ [temp.class.spec]p9b3.
3137 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003138 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003139 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3140 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003141 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003142 MirrorsPrimaryTemplate = false;
3143 } else if (TemplateTemplateParmDecl *TTP
3144 = dyn_cast<TemplateTemplateParmDecl>(
3145 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003146 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003147 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003148 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003149 if (!ArgDecl ||
3150 ArgDecl->getIndex() != TTP->getIndex() ||
3151 ArgDecl->getDepth() != TTP->getDepth())
3152 MirrorsPrimaryTemplate = false;
3153 }
3154 }
3155
Mike Stump11289f42009-09-09 15:08:12 +00003156 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003157 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003158 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003159 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003160 }
3161
Anders Carlsson40c1d492009-06-13 18:20:51 +00003162 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003163 if (!ArgExpr) {
3164 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003165 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003166 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003167
3168 // C++ [temp.class.spec]p8:
3169 // A non-type argument is non-specialized if it is the name of a
3170 // non-type parameter. All other non-type arguments are
3171 // specialized.
3172 //
3173 // Below, we check the two conditions that only apply to
3174 // specialized non-type arguments, so skip any non-specialized
3175 // arguments.
3176 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003177 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003178 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003179 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003180 (Param->getIndex() != NTTP->getIndex() ||
3181 Param->getDepth() != NTTP->getDepth()))
3182 MirrorsPrimaryTemplate = false;
3183
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003184 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003185 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003186
3187 // C++ [temp.class.spec]p9:
3188 // Within the argument list of a class template partial
3189 // specialization, the following restrictions apply:
3190 // -- A partially specialized non-type argument expression
3191 // shall not involve a template parameter of the partial
3192 // specialization except when the argument expression is a
3193 // simple identifier.
3194 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003195 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003196 diag::err_dependent_non_type_arg_in_partial_spec)
3197 << ArgExpr->getSourceRange();
3198 return true;
3199 }
3200
3201 // -- The type of a template parameter corresponding to a
3202 // specialized non-type argument shall not be dependent on a
3203 // parameter of the specialization.
3204 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003205 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003206 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3207 << Param->getType()
3208 << ArgExpr->getSourceRange();
3209 Diag(Param->getLocation(), diag::note_template_param_here);
3210 return true;
3211 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003212
3213 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003214 }
3215
3216 return false;
3217}
3218
Douglas Gregorc08f4892009-03-25 00:13:59 +00003219Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003220Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3221 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003222 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00003223 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003224 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003225 SourceLocation TemplateNameLoc,
3226 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003227 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003228 SourceLocation RAngleLoc,
3229 AttributeList *Attr,
3230 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003231 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003232
Douglas Gregor67a65642009-02-17 23:15:12 +00003233 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003234 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003235 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003236 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3237
3238 if (!ClassTemplate) {
3239 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3240 << (Name.getAsTemplateDecl() &&
3241 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3242 return true;
3243 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003244
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003245 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003246 bool isPartialSpecialization = false;
3247
Douglas Gregorf47b9112009-02-25 22:02:03 +00003248 // Check the validity of the template headers that introduce this
3249 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003250 // FIXME: We probably shouldn't complain about these headers for
3251 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003252 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003253 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3254 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003255 TemplateParameterLists.size(),
3256 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003257 if (TemplateParams && TemplateParams->size() > 0) {
3258 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003259
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003260 // C++ [temp.class.spec]p10:
3261 // The template parameter list of a specialization shall not
3262 // contain default template argument values.
3263 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3264 Decl *Param = TemplateParams->getParam(I);
3265 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3266 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003267 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003268 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003269 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003270 }
3271 } else if (NonTypeTemplateParmDecl *NTTP
3272 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3273 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003274 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003275 diag::err_default_arg_in_partial_spec)
3276 << DefArg->getSourceRange();
3277 NTTP->setDefaultArgument(0);
3278 DefArg->Destroy(Context);
3279 }
3280 } else {
3281 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003282 if (TTP->hasDefaultArgument()) {
3283 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003284 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003285 << TTP->getDefaultArgument().getSourceRange();
3286 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003287 }
3288 }
3289 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003290 } else if (TemplateParams) {
3291 if (TUK == TUK_Friend)
3292 Diag(KWLoc, diag::err_template_spec_friend)
3293 << CodeModificationHint::CreateRemoval(
3294 SourceRange(TemplateParams->getTemplateLoc(),
3295 TemplateParams->getRAngleLoc()))
3296 << SourceRange(LAngleLoc, RAngleLoc);
3297 else
3298 isExplicitSpecialization = true;
3299 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003300 Diag(KWLoc, diag::err_template_spec_needs_header)
3301 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003302 isExplicitSpecialization = true;
3303 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003304
Douglas Gregor67a65642009-02-17 23:15:12 +00003305 // Check that the specialization uses the same tag kind as the
3306 // original template.
3307 TagDecl::TagKind Kind;
3308 switch (TagSpec) {
3309 default: assert(0 && "Unknown tag type!");
3310 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3311 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3312 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3313 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003314 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003315 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003316 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003317 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003318 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003319 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003320 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003321 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003322 diag::note_previous_use);
3323 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3324 }
3325
Douglas Gregorc40290e2009-03-09 23:48:35 +00003326 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003327 TemplateArgumentListInfo TemplateArgs;
3328 TemplateArgs.setLAngleLoc(LAngleLoc);
3329 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003330 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003331
Douglas Gregor67a65642009-02-17 23:15:12 +00003332 // Check that the template argument list is well-formed for this
3333 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003334 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3335 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003336 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3337 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003338 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003339
Mike Stump11289f42009-09-09 15:08:12 +00003340 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003341 ClassTemplate->getTemplateParameters()->size()) &&
3342 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003343
Douglas Gregor2373c592009-05-31 09:31:02 +00003344 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003345 // corresponds to these arguments.
3346 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003347 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003348 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003349 if (CheckClassTemplatePartialSpecializationArgs(
3350 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003351 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003352 return true;
3353
Douglas Gregor09a30232009-06-12 22:08:06 +00003354 if (MirrorsPrimaryTemplate) {
3355 // C++ [temp.class.spec]p9b3:
3356 //
Mike Stump11289f42009-09-09 15:08:12 +00003357 // -- The argument list of the specialization shall not be identical
3358 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003359 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003360 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00003361 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00003362 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003363 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003364 ClassTemplate->getIdentifier(),
3365 TemplateNameLoc,
3366 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003367 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003368 AS_none);
3369 }
3370
Douglas Gregor2208a292009-09-26 20:57:03 +00003371 // FIXME: Diagnose friend partial specializations
3372
Douglas Gregor2373c592009-05-31 09:31:02 +00003373 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00003374 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003375 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003376 Converted.flatSize(),
3377 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003378 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003379 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003380 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003381 Converted.flatSize(),
3382 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003383 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003384 ClassTemplateSpecializationDecl *PrevDecl = 0;
3385
3386 if (isPartialSpecialization)
3387 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003388 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003389 InsertPos);
3390 else
3391 PrevDecl
3392 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003393
3394 ClassTemplateSpecializationDecl *Specialization = 0;
3395
Douglas Gregorf47b9112009-02-25 22:02:03 +00003396 // Check whether we can declare a class template specialization in
3397 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003398 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003399 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003400 TemplateNameLoc,
3401 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003402 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003403
Douglas Gregor15301382009-07-30 17:40:51 +00003404 // The canonical type
3405 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003406 if (PrevDecl &&
3407 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3408 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003409 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003410 // arguments was referenced but not declared, or we're only
3411 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003412 // declaration node as our own, updating its source location to
3413 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003414 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003415 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003416 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003417 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003418 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003419 // Build the canonical type that describes the converted template
3420 // arguments of the class template partial specialization.
3421 CanonType = Context.getTemplateSpecializationType(
3422 TemplateName(ClassTemplate),
3423 Converted.getFlatArguments(),
3424 Converted.flatSize());
3425
Douglas Gregor2373c592009-05-31 09:31:02 +00003426 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003427 ClassTemplatePartialSpecializationDecl *PrevPartial
3428 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003429 ClassTemplatePartialSpecializationDecl *Partial
3430 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003431 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003432 TemplateNameLoc,
3433 TemplateParams,
3434 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003435 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003436 TemplateArgs,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003437 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00003438
3439 if (PrevPartial) {
3440 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3441 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3442 } else {
3443 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3444 }
3445 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003446
Douglas Gregor21610382009-10-29 00:04:11 +00003447 // If we are providing an explicit specialization of a member class
3448 // template specialization, make a note of that.
3449 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3450 PrevPartial->setMemberSpecialization();
3451
Douglas Gregor91772d12009-06-13 00:26:55 +00003452 // Check that all of the template parameters of the class template
3453 // partial specialization are deducible from the template
3454 // arguments. If not, this class template partial specialization
3455 // will never be used.
3456 llvm::SmallVector<bool, 8> DeducibleParams;
3457 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003458 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003459 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003460 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003461 unsigned NumNonDeducible = 0;
3462 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3463 if (!DeducibleParams[I])
3464 ++NumNonDeducible;
3465
3466 if (NumNonDeducible) {
3467 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3468 << (NumNonDeducible > 1)
3469 << SourceRange(TemplateNameLoc, RAngleLoc);
3470 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3471 if (!DeducibleParams[I]) {
3472 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3473 if (Param->getDeclName())
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 << Param->getDeclName();
3477 else
Mike Stump11289f42009-09-09 15:08:12 +00003478 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003479 diag::note_partial_spec_unused_parameter)
3480 << std::string("<anonymous>");
3481 }
3482 }
3483 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003484 } else {
3485 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003486 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003487 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003488 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003489 ClassTemplate->getDeclContext(),
3490 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003491 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003492 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003493 PrevDecl);
3494
3495 if (PrevDecl) {
3496 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3497 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3498 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003499 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003500 InsertPos);
3501 }
Douglas Gregor15301382009-07-30 17:40:51 +00003502
3503 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003504 }
3505
Douglas Gregor06db9f52009-10-12 20:18:28 +00003506 // C++ [temp.expl.spec]p6:
3507 // If a template, a member template or the member of a class template is
3508 // explicitly specialized then that specialization shall be declared
3509 // before the first use of that specialization that would cause an implicit
3510 // instantiation to take place, in every translation unit in which such a
3511 // use occurs; no diagnostic is required.
3512 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3513 SourceRange Range(TemplateNameLoc, RAngleLoc);
3514 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3515 << Context.getTypeDeclType(Specialization) << Range;
3516
3517 Diag(PrevDecl->getPointOfInstantiation(),
3518 diag::note_instantiation_required_here)
3519 << (PrevDecl->getTemplateSpecializationKind()
3520 != TSK_ImplicitInstantiation);
3521 return true;
3522 }
3523
Douglas Gregor2208a292009-09-26 20:57:03 +00003524 // If this is not a friend, note that this is an explicit specialization.
3525 if (TUK != TUK_Friend)
3526 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003527
3528 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003529 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003530 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003531 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003532 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003533 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003534 Diag(Def->getLocation(), diag::note_previous_definition);
3535 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003536 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003537 }
3538 }
3539
Douglas Gregord56a91e2009-02-26 22:19:44 +00003540 // Build the fully-sugared type for this class template
3541 // specialization as the user wrote in the specialization
3542 // itself. This means that we'll pretty-print the type retrieved
3543 // from the specialization's declaration the way that the user
3544 // actually wrote the specialization, rather than formatting the
3545 // name based on the "canonical" representation used to store the
3546 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003547 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00003548 = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003549 if (TUK != TUK_Friend)
3550 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003551 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003552
Douglas Gregor1e249f82009-02-25 22:18:32 +00003553 // C++ [temp.expl.spec]p9:
3554 // A template explicit specialization is in the scope of the
3555 // namespace in which the template was defined.
3556 //
3557 // We actually implement this paragraph where we set the semantic
3558 // context (in the creation of the ClassTemplateSpecializationDecl),
3559 // but we also maintain the lexical context where the actual
3560 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003561 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003562
Douglas Gregor67a65642009-02-17 23:15:12 +00003563 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003564 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003565 Specialization->startDefinition();
3566
Douglas Gregor2208a292009-09-26 20:57:03 +00003567 if (TUK == TUK_Friend) {
3568 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3569 TemplateNameLoc,
3570 WrittenTy.getTypePtr(),
3571 /*FIXME:*/KWLoc);
3572 Friend->setAccess(AS_public);
3573 CurContext->addDecl(Friend);
3574 } else {
3575 // Add the specialization into its lexical context, so that it can
3576 // be seen when iterating through the list of declarations in that
3577 // context. However, specializations are not found by name lookup.
3578 CurContext->addDecl(Specialization);
3579 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003580 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003581}
Douglas Gregor333489b2009-03-27 23:10:48 +00003582
Mike Stump11289f42009-09-09 15:08:12 +00003583Sema::DeclPtrTy
3584Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003585 MultiTemplateParamsArg TemplateParameterLists,
3586 Declarator &D) {
3587 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3588}
3589
Mike Stump11289f42009-09-09 15:08:12 +00003590Sema::DeclPtrTy
3591Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003592 MultiTemplateParamsArg TemplateParameterLists,
3593 Declarator &D) {
3594 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3595 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3596 "Not a function declarator!");
3597 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003598
Douglas Gregor17a7c122009-06-24 00:54:41 +00003599 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003600 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003601 }
Mike Stump11289f42009-09-09 15:08:12 +00003602
Douglas Gregor17a7c122009-06-24 00:54:41 +00003603 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003604
3605 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003606 move(TemplateParameterLists),
3607 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003608 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003609 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003610 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003611 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003612 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3613 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003614 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003615}
3616
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003617/// \brief Diagnose cases where we have an explicit template specialization
3618/// before/after an explicit template instantiation, producing diagnostics
3619/// for those cases where they are required and determining whether the
3620/// new specialization/instantiation will have any effect.
3621///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003622/// \param NewLoc the location of the new explicit specialization or
3623/// instantiation.
3624///
3625/// \param NewTSK the kind of the new explicit specialization or instantiation.
3626///
3627/// \param PrevDecl the previous declaration of the entity.
3628///
3629/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3630///
3631/// \param PrevPointOfInstantiation if valid, indicates where the previus
3632/// declaration was instantiated (either implicitly or explicitly).
3633///
3634/// \param SuppressNew will be set to true to indicate that the new
3635/// specialization or instantiation has no effect and should be ignored.
3636///
3637/// \returns true if there was an error that should prevent the introduction of
3638/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003639bool
3640Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3641 TemplateSpecializationKind NewTSK,
3642 NamedDecl *PrevDecl,
3643 TemplateSpecializationKind PrevTSK,
3644 SourceLocation PrevPointOfInstantiation,
3645 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003646 SuppressNew = false;
3647
3648 switch (NewTSK) {
3649 case TSK_Undeclared:
3650 case TSK_ImplicitInstantiation:
3651 assert(false && "Don't check implicit instantiations here");
3652 return false;
3653
3654 case TSK_ExplicitSpecialization:
3655 switch (PrevTSK) {
3656 case TSK_Undeclared:
3657 case TSK_ExplicitSpecialization:
3658 // Okay, we're just specializing something that is either already
3659 // explicitly specialized or has merely been mentioned without any
3660 // instantiation.
3661 return false;
3662
3663 case TSK_ImplicitInstantiation:
3664 if (PrevPointOfInstantiation.isInvalid()) {
3665 // The declaration itself has not actually been instantiated, so it is
3666 // still okay to specialize it.
3667 return false;
3668 }
3669 // Fall through
3670
3671 case TSK_ExplicitInstantiationDeclaration:
3672 case TSK_ExplicitInstantiationDefinition:
3673 assert((PrevTSK == TSK_ImplicitInstantiation ||
3674 PrevPointOfInstantiation.isValid()) &&
3675 "Explicit instantiation without point of instantiation?");
3676
3677 // C++ [temp.expl.spec]p6:
3678 // If a template, a member template or the member of a class template
3679 // is explicitly specialized then that specialization shall be declared
3680 // before the first use of that specialization that would cause an
3681 // implicit instantiation to take place, in every translation unit in
3682 // which such a use occurs; no diagnostic is required.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003683 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003684 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003685 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003686 << (PrevTSK != TSK_ImplicitInstantiation);
3687
3688 return true;
3689 }
3690 break;
3691
3692 case TSK_ExplicitInstantiationDeclaration:
3693 switch (PrevTSK) {
3694 case TSK_ExplicitInstantiationDeclaration:
3695 // This explicit instantiation declaration is redundant (that's okay).
3696 SuppressNew = true;
3697 return false;
3698
3699 case TSK_Undeclared:
3700 case TSK_ImplicitInstantiation:
3701 // We're explicitly instantiating something that may have already been
3702 // implicitly instantiated; that's fine.
3703 return false;
3704
3705 case TSK_ExplicitSpecialization:
3706 // C++0x [temp.explicit]p4:
3707 // For a given set of template parameters, if an explicit instantiation
3708 // of a template appears after a declaration of an explicit
3709 // specialization for that template, the explicit instantiation has no
3710 // effect.
3711 return false;
3712
3713 case TSK_ExplicitInstantiationDefinition:
3714 // C++0x [temp.explicit]p10:
3715 // If an entity is the subject of both an explicit instantiation
3716 // declaration and an explicit instantiation definition in the same
3717 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003718 Diag(NewLoc,
3719 diag::err_explicit_instantiation_declaration_after_definition);
3720 Diag(PrevPointOfInstantiation,
3721 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003722 assert(PrevPointOfInstantiation.isValid() &&
3723 "Explicit instantiation without point of instantiation?");
3724 SuppressNew = true;
3725 return false;
3726 }
3727 break;
3728
3729 case TSK_ExplicitInstantiationDefinition:
3730 switch (PrevTSK) {
3731 case TSK_Undeclared:
3732 case TSK_ImplicitInstantiation:
3733 // We're explicitly instantiating something that may have already been
3734 // implicitly instantiated; that's fine.
3735 return false;
3736
3737 case TSK_ExplicitSpecialization:
3738 // C++ DR 259, C++0x [temp.explicit]p4:
3739 // For a given set of template parameters, if an explicit
3740 // instantiation of a template appears after a declaration of
3741 // an explicit specialization for that template, the explicit
3742 // instantiation has no effect.
3743 //
3744 // In C++98/03 mode, we only give an extension warning here, because it
3745 // is not not harmful to try to explicitly instantiate something that
3746 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003747 if (!getLangOptions().CPlusPlus0x) {
3748 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003749 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003750 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003751 diag::note_previous_template_specialization);
3752 }
3753 SuppressNew = true;
3754 return false;
3755
3756 case TSK_ExplicitInstantiationDeclaration:
3757 // We're explicity instantiating a definition for something for which we
3758 // were previously asked to suppress instantiations. That's fine.
3759 return false;
3760
3761 case TSK_ExplicitInstantiationDefinition:
3762 // C++0x [temp.spec]p5:
3763 // For a given template and a given set of template-arguments,
3764 // - an explicit instantiation definition shall appear at most once
3765 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003766 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003767 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003768 Diag(PrevPointOfInstantiation,
3769 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003770 SuppressNew = true;
3771 return false;
3772 }
3773 break;
3774 }
3775
3776 assert(false && "Missing specialization/instantiation case?");
3777
3778 return false;
3779}
3780
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003781/// \brief Perform semantic analysis for the given function template
3782/// specialization.
3783///
3784/// This routine performs all of the semantic analysis required for an
3785/// explicit function template specialization. On successful completion,
3786/// the function declaration \p FD will become a function template
3787/// specialization.
3788///
3789/// \param FD the function declaration, which will be updated to become a
3790/// function template specialization.
3791///
3792/// \param HasExplicitTemplateArgs whether any template arguments were
3793/// explicitly provided.
3794///
3795/// \param LAngleLoc the location of the left angle bracket ('<'), if
3796/// template arguments were explicitly provided.
3797///
3798/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3799/// if any.
3800///
3801/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3802/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3803/// true as in, e.g., \c void sort<>(char*, char*);
3804///
3805/// \param RAngleLoc the location of the right angle bracket ('>'), if
3806/// template arguments were explicitly provided.
3807///
3808/// \param PrevDecl the set of declarations that
3809bool
3810Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00003811 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00003812 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003813 // The set of function template specializations that could match this
3814 // explicit function template specialization.
3815 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3816 CandidateSet Candidates;
3817
3818 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00003819 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3820 I != E; ++I) {
3821 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3822 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003823 // Only consider templates found within the same semantic lookup scope as
3824 // FD.
3825 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3826 continue;
3827
3828 // C++ [temp.expl.spec]p11:
3829 // A trailing template-argument can be left unspecified in the
3830 // template-id naming an explicit function template specialization
3831 // provided it can be deduced from the function argument type.
3832 // Perform template argument deduction to determine whether we may be
3833 // specializing this template.
3834 // FIXME: It is somewhat wasteful to build
3835 TemplateDeductionInfo Info(Context);
3836 FunctionDecl *Specialization = 0;
3837 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00003838 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003839 FD->getType(),
3840 Specialization,
3841 Info)) {
3842 // FIXME: Template argument deduction failed; record why it failed, so
3843 // that we can provide nifty diagnostics.
3844 (void)TDK;
3845 continue;
3846 }
3847
3848 // Record this candidate.
3849 Candidates.push_back(Specialization);
3850 }
3851 }
3852
Douglas Gregor5de279c2009-09-26 03:41:46 +00003853 // Find the most specialized function template.
3854 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3855 Candidates.size(),
3856 TPOC_Other,
3857 FD->getLocation(),
3858 PartialDiagnostic(diag::err_function_template_spec_no_match)
3859 << FD->getDeclName(),
3860 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00003861 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor5de279c2009-09-26 03:41:46 +00003862 PartialDiagnostic(diag::note_function_template_spec_matched));
3863 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003864 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003865
3866 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003867 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003868
Douglas Gregor54888652009-10-07 00:13:32 +00003869 // Check the scope of this explicit specialization.
3870 if (CheckTemplateSpecializationScope(*this,
3871 Specialization->getPrimaryTemplate(),
3872 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003873 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003874 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003875
3876 // C++ [temp.expl.spec]p6:
3877 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003878 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003879 // before the first use of that specialization that would cause an implicit
3880 // instantiation to take place, in every translation unit in which such a
3881 // use occurs; no diagnostic is required.
3882 FunctionTemplateSpecializationInfo *SpecInfo
3883 = Specialization->getTemplateSpecializationInfo();
3884 assert(SpecInfo && "Function template specialization info missing?");
3885 if (SpecInfo->getPointOfInstantiation().isValid()) {
3886 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3887 << FD;
3888 Diag(SpecInfo->getPointOfInstantiation(),
3889 diag::note_instantiation_required_here)
3890 << (Specialization->getTemplateSpecializationKind()
3891 != TSK_ImplicitInstantiation);
3892 return true;
3893 }
Douglas Gregor54888652009-10-07 00:13:32 +00003894
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003895 // Mark the prior declaration as an explicit specialization, so that later
3896 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003897 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003898
3899 // Turn the given function declaration into a function template
3900 // specialization, with the template arguments from the previous
3901 // specialization.
3902 FD->setFunctionTemplateSpecialization(Context,
3903 Specialization->getPrimaryTemplate(),
3904 new (Context) TemplateArgumentList(
3905 *Specialization->getTemplateSpecializationArgs()),
3906 /*InsertPos=*/0,
3907 TSK_ExplicitSpecialization);
3908
3909 // The "previous declaration" for this function template specialization is
3910 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00003911 Previous.clear();
3912 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003913 return false;
3914}
3915
Douglas Gregor86d142a2009-10-08 07:24:58 +00003916/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003917/// specialization.
3918///
3919/// This routine performs all of the semantic analysis required for an
3920/// explicit member function specialization. On successful completion,
3921/// the function declaration \p FD will become a member function
3922/// specialization.
3923///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003924/// \param Member the member declaration, which will be updated to become a
3925/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003926///
John McCall1f82f242009-11-18 22:49:29 +00003927/// \param Previous the set of declarations, one of which may be specialized
3928/// by this function specialization; the set will be modified to contain the
3929/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003930bool
John McCall1f82f242009-11-18 22:49:29 +00003931Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003932 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3933
3934 // Try to find the member we are instantiating.
3935 NamedDecl *Instantiation = 0;
3936 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003937 MemberSpecializationInfo *MSInfo = 0;
3938
John McCall1f82f242009-11-18 22:49:29 +00003939 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003940 // Nowhere to look anyway.
3941 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003942 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3943 I != E; ++I) {
3944 NamedDecl *D = (*I)->getUnderlyingDecl();
3945 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003946 if (Context.hasSameType(Function->getType(), Method->getType())) {
3947 Instantiation = Method;
3948 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003949 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003950 break;
3951 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003952 }
3953 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003954 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003955 VarDecl *PrevVar;
3956 if (Previous.isSingleResult() &&
3957 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00003958 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00003959 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003960 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003961 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003962 }
3963 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003964 CXXRecordDecl *PrevRecord;
3965 if (Previous.isSingleResult() &&
3966 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
3967 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003968 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003969 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003970 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003971 }
3972
3973 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003974 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003975 // specializations are always out-of-line, the caller will complain about
3976 // this mismatch later.
3977 return false;
3978 }
3979
Douglas Gregor86d142a2009-10-08 07:24:58 +00003980 // Make sure that this is a specialization of a member.
3981 if (!InstantiatedFrom) {
3982 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3983 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003984 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3985 return true;
3986 }
3987
Douglas Gregor06db9f52009-10-12 20:18:28 +00003988 // C++ [temp.expl.spec]p6:
3989 // If a template, a member template or the member of a class template is
3990 // explicitly specialized then that spe- cialization shall be declared
3991 // before the first use of that specialization that would cause an implicit
3992 // instantiation to take place, in every translation unit in which such a
3993 // use occurs; no diagnostic is required.
3994 assert(MSInfo && "Member specialization info missing?");
3995 if (MSInfo->getPointOfInstantiation().isValid()) {
3996 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3997 << Member;
3998 Diag(MSInfo->getPointOfInstantiation(),
3999 diag::note_instantiation_required_here)
4000 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
4001 return true;
4002 }
4003
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004004 // Check the scope of this explicit specialization.
4005 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004006 InstantiatedFrom,
4007 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004008 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004009 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004010
Douglas Gregor86d142a2009-10-08 07:24:58 +00004011 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004012 // the original declaration to note that it is an explicit specialization
4013 // (if it was previously an implicit instantiation). This latter step
4014 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004015 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004016 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4017 if (InstantiationFunction->getTemplateSpecializationKind() ==
4018 TSK_ImplicitInstantiation) {
4019 InstantiationFunction->setTemplateSpecializationKind(
4020 TSK_ExplicitSpecialization);
4021 InstantiationFunction->setLocation(Member->getLocation());
4022 }
4023
Douglas Gregor86d142a2009-10-08 07:24:58 +00004024 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4025 cast<CXXMethodDecl>(InstantiatedFrom),
4026 TSK_ExplicitSpecialization);
4027 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004028 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4029 if (InstantiationVar->getTemplateSpecializationKind() ==
4030 TSK_ImplicitInstantiation) {
4031 InstantiationVar->setTemplateSpecializationKind(
4032 TSK_ExplicitSpecialization);
4033 InstantiationVar->setLocation(Member->getLocation());
4034 }
4035
Douglas Gregor86d142a2009-10-08 07:24:58 +00004036 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4037 cast<VarDecl>(InstantiatedFrom),
4038 TSK_ExplicitSpecialization);
4039 } else {
4040 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004041 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4042 if (InstantiationClass->getTemplateSpecializationKind() ==
4043 TSK_ImplicitInstantiation) {
4044 InstantiationClass->setTemplateSpecializationKind(
4045 TSK_ExplicitSpecialization);
4046 InstantiationClass->setLocation(Member->getLocation());
4047 }
4048
Douglas Gregor86d142a2009-10-08 07:24:58 +00004049 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004050 cast<CXXRecordDecl>(InstantiatedFrom),
4051 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004052 }
4053
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004054 // Save the caller the trouble of having to figure out which declaration
4055 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004056 Previous.clear();
4057 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004058 return false;
4059}
4060
Douglas Gregore47f5a72009-10-14 23:41:34 +00004061/// \brief Check the scope of an explicit instantiation.
4062static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4063 SourceLocation InstLoc,
4064 bool WasQualifiedName) {
4065 DeclContext *ExpectedContext
4066 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4067 DeclContext *CurContext = S.CurContext->getLookupContext();
4068
4069 // C++0x [temp.explicit]p2:
4070 // An explicit instantiation shall appear in an enclosing namespace of its
4071 // template.
4072 //
4073 // This is DR275, which we do not retroactively apply to C++98/03.
4074 if (S.getLangOptions().CPlusPlus0x &&
4075 !CurContext->Encloses(ExpectedContext)) {
4076 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4077 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4078 << D << NS;
4079 else
4080 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4081 << D;
4082 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4083 return;
4084 }
4085
4086 // C++0x [temp.explicit]p2:
4087 // If the name declared in the explicit instantiation is an unqualified
4088 // name, the explicit instantiation shall appear in the namespace where
4089 // its template is declared or, if that namespace is inline (7.3.1), any
4090 // namespace from its enclosing namespace set.
4091 if (WasQualifiedName)
4092 return;
4093
4094 if (CurContext->Equals(ExpectedContext))
4095 return;
4096
4097 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4098 << D << ExpectedContext;
4099 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4100}
4101
4102/// \brief Determine whether the given scope specifier has a template-id in it.
4103static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4104 if (!SS.isSet())
4105 return false;
4106
4107 // C++0x [temp.explicit]p2:
4108 // If the explicit instantiation is for a member function, a member class
4109 // or a static data member of a class template specialization, the name of
4110 // the class template specialization in the qualified-id for the member
4111 // name shall be a simple-template-id.
4112 //
4113 // C++98 has the same restriction, just worded differently.
4114 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4115 NNS; NNS = NNS->getPrefix())
4116 if (Type *T = NNS->getAsType())
4117 if (isa<TemplateSpecializationType>(T))
4118 return true;
4119
4120 return false;
4121}
4122
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004123// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00004124// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00004125Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004126Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004127 SourceLocation ExternLoc,
4128 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004129 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004130 SourceLocation KWLoc,
4131 const CXXScopeSpec &SS,
4132 TemplateTy TemplateD,
4133 SourceLocation TemplateNameLoc,
4134 SourceLocation LAngleLoc,
4135 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004136 SourceLocation RAngleLoc,
4137 AttributeList *Attr) {
4138 // Find the class template we're specializing
4139 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004140 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004141 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4142
4143 // Check that the specialization uses the same tag kind as the
4144 // original template.
4145 TagDecl::TagKind Kind;
4146 switch (TagSpec) {
4147 default: assert(0 && "Unknown tag type!");
4148 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4149 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4150 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4151 }
Douglas Gregord9034f02009-05-14 16:41:31 +00004152 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004153 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004154 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004155 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004156 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00004157 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004158 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004159 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004160 diag::note_previous_use);
4161 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4162 }
4163
Douglas Gregore47f5a72009-10-14 23:41:34 +00004164 // C++0x [temp.explicit]p2:
4165 // There are two forms of explicit instantiation: an explicit instantiation
4166 // definition and an explicit instantiation declaration. An explicit
4167 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004168 TemplateSpecializationKind TSK
4169 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4170 : TSK_ExplicitInstantiationDeclaration;
4171
Douglas Gregora1f49972009-05-13 00:25:59 +00004172 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004173 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004174 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004175
4176 // Check that the template argument list is well-formed for this
4177 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004178 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4179 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004180 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4181 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004182 return true;
4183
Mike Stump11289f42009-09-09 15:08:12 +00004184 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004185 ClassTemplate->getTemplateParameters()->size()) &&
4186 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004187
Douglas Gregora1f49972009-05-13 00:25:59 +00004188 // Find the class template specialization declaration that
4189 // corresponds to these arguments.
4190 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004191 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004192 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004193 Converted.flatSize(),
4194 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004195 void *InsertPos = 0;
4196 ClassTemplateSpecializationDecl *PrevDecl
4197 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4198
Douglas Gregor54888652009-10-07 00:13:32 +00004199 // C++0x [temp.explicit]p2:
4200 // [...] An explicit instantiation shall appear in an enclosing
4201 // namespace of its template. [...]
4202 //
4203 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004204 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4205 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004206
Douglas Gregora1f49972009-05-13 00:25:59 +00004207 ClassTemplateSpecializationDecl *Specialization = 0;
4208
Douglas Gregor0681a352009-11-25 06:01:46 +00004209 bool ReusedDecl = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004210 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00004211 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004212 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004213 PrevDecl,
4214 PrevDecl->getSpecializationKind(),
4215 PrevDecl->getPointOfInstantiation(),
4216 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00004217 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004218
Douglas Gregor12e49d32009-10-15 22:53:21 +00004219 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004220 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00004221
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004222 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4223 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4224 // Since the only prior class template specialization with these
4225 // arguments was referenced but not declared, reuse that
4226 // declaration node as our own, updating its source location to
4227 // reflect our new declaration.
4228 Specialization = PrevDecl;
4229 Specialization->setLocation(TemplateNameLoc);
4230 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004231 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004232 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004233 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004234
4235 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004236 // Create a new class template specialization declaration node for
4237 // this explicit specialization.
4238 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00004239 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00004240 ClassTemplate->getDeclContext(),
4241 TemplateNameLoc,
4242 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004243 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004244
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004245 if (PrevDecl) {
4246 // Remove the previous declaration from the folding set, since we want
4247 // to introduce a new declaration.
4248 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4249 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4250 }
4251
4252 // Insert the new specialization.
4253 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004254 }
4255
4256 // Build the fully-sugared type for this explicit instantiation as
4257 // the user wrote in the explicit instantiation itself. This means
4258 // that we'll pretty-print the type retrieved from the
4259 // specialization's declaration the way that the user actually wrote
4260 // the explicit instantiation, rather than formatting the name based
4261 // on the "canonical" representation used to store the template
4262 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004263 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00004264 = Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004265 Context.getTypeDeclType(Specialization));
4266 Specialization->setTypeAsWritten(WrittenTy);
4267 TemplateArgsIn.release();
4268
Douglas Gregor0681a352009-11-25 06:01:46 +00004269 if (!ReusedDecl) {
4270 // Add the explicit instantiation into its lexical context. However,
4271 // since explicit instantiations are never found by name lookup, we
4272 // just put it into the declaration context directly.
4273 Specialization->setLexicalDeclContext(CurContext);
4274 CurContext->addDecl(Specialization);
4275 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004276
4277 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004278 // A definition of a class template or class member template
4279 // shall be in scope at the point of the explicit instantiation of
4280 // the class template or class member template.
4281 //
4282 // This check comes when we actually try to perform the
4283 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004284 ClassTemplateSpecializationDecl *Def
4285 = cast_or_null<ClassTemplateSpecializationDecl>(
4286 Specialization->getDefinition(Context));
4287 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004288 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00004289
4290 // Instantiate the members of this class template specialization.
4291 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4292 Specialization->getDefinition(Context));
4293 if (Def)
Douglas Gregor12e49d32009-10-15 22:53:21 +00004294 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00004295
4296 return DeclPtrTy::make(Specialization);
4297}
4298
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004299// Explicit instantiation of a member class of a class template.
4300Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004301Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004302 SourceLocation ExternLoc,
4303 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004304 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004305 SourceLocation KWLoc,
4306 const CXXScopeSpec &SS,
4307 IdentifierInfo *Name,
4308 SourceLocation NameLoc,
4309 AttributeList *Attr) {
4310
Douglas Gregord6ab8742009-05-28 23:31:59 +00004311 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004312 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004313 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004314 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004315 MultiTemplateParamsArg(*this, 0, 0),
4316 Owned, IsDependent);
4317 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4318
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004319 if (!TagD)
4320 return true;
4321
4322 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4323 if (Tag->isEnum()) {
4324 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4325 << Context.getTypeDeclType(Tag);
4326 return true;
4327 }
4328
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004329 if (Tag->isInvalidDecl())
4330 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004331
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004332 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4333 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4334 if (!Pattern) {
4335 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4336 << Context.getTypeDeclType(Record);
4337 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4338 return true;
4339 }
4340
Douglas Gregore47f5a72009-10-14 23:41:34 +00004341 // C++0x [temp.explicit]p2:
4342 // If the explicit instantiation is for a class or member class, the
4343 // elaborated-type-specifier in the declaration shall include a
4344 // simple-template-id.
4345 //
4346 // C++98 has the same restriction, just worded differently.
4347 if (!ScopeSpecifierHasTemplateId(SS))
4348 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4349 << Record << SS.getRange();
4350
4351 // C++0x [temp.explicit]p2:
4352 // There are two forms of explicit instantiation: an explicit instantiation
4353 // definition and an explicit instantiation declaration. An explicit
4354 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004355 TemplateSpecializationKind TSK
4356 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4357 : TSK_ExplicitInstantiationDeclaration;
4358
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004359 // C++0x [temp.explicit]p2:
4360 // [...] An explicit instantiation shall appear in an enclosing
4361 // namespace of its template. [...]
4362 //
4363 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004364 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004365
4366 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004367 CXXRecordDecl *PrevDecl
4368 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4369 if (!PrevDecl && Record->getDefinition(Context))
4370 PrevDecl = Record;
4371 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004372 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4373 bool SuppressNew = false;
4374 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004375 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004376 PrevDecl,
4377 MSInfo->getTemplateSpecializationKind(),
4378 MSInfo->getPointOfInstantiation(),
4379 SuppressNew))
4380 return true;
4381 if (SuppressNew)
4382 return TagD;
4383 }
4384
Douglas Gregor12e49d32009-10-15 22:53:21 +00004385 CXXRecordDecl *RecordDef
4386 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4387 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004388 // C++ [temp.explicit]p3:
4389 // A definition of a member class of a class template shall be in scope
4390 // at the point of an explicit instantiation of the member class.
4391 CXXRecordDecl *Def
4392 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4393 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004394 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4395 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004396 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4397 << Pattern;
4398 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004399 } else {
4400 if (InstantiateClass(NameLoc, Record, Def,
4401 getTemplateInstantiationArgs(Record),
4402 TSK))
4403 return true;
4404
4405 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4406 if (!RecordDef)
4407 return true;
4408 }
4409 }
4410
4411 // Instantiate all of the members of the class.
4412 InstantiateClassMembers(NameLoc, RecordDef,
4413 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004414
Mike Stump87c57ac2009-05-16 07:39:55 +00004415 // FIXME: We don't have any representation for explicit instantiations of
4416 // member classes. Such a representation is not needed for compilation, but it
4417 // should be available for clients that want to see all of the declarations in
4418 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004419 return TagD;
4420}
4421
Douglas Gregor450f00842009-09-25 18:43:00 +00004422Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4423 SourceLocation ExternLoc,
4424 SourceLocation TemplateLoc,
4425 Declarator &D) {
4426 // Explicit instantiations always require a name.
4427 DeclarationName Name = GetNameForDeclarator(D);
4428 if (!Name) {
4429 if (!D.isInvalidType())
4430 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4431 diag::err_explicit_instantiation_requires_name)
4432 << D.getDeclSpec().getSourceRange()
4433 << D.getSourceRange();
4434
4435 return true;
4436 }
4437
4438 // The scope passed in may not be a decl scope. Zip up the scope tree until
4439 // we find one that is.
4440 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4441 (S->getFlags() & Scope::TemplateParamScope) != 0)
4442 S = S->getParent();
4443
4444 // Determine the type of the declaration.
4445 QualType R = GetTypeForDeclarator(D, S, 0);
4446 if (R.isNull())
4447 return true;
4448
4449 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4450 // Cannot explicitly instantiate a typedef.
4451 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4452 << Name;
4453 return true;
4454 }
4455
Douglas Gregor3c74d412009-10-14 20:14:33 +00004456 // C++0x [temp.explicit]p1:
4457 // [...] An explicit instantiation of a function template shall not use the
4458 // inline or constexpr specifiers.
4459 // Presumably, this also applies to member functions of class templates as
4460 // well.
4461 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4462 Diag(D.getDeclSpec().getInlineSpecLoc(),
4463 diag::err_explicit_instantiation_inline)
Chris Lattner3c7b86f2009-12-06 17:36:05 +00004464 <<CodeModificationHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004465
4466 // FIXME: check for constexpr specifier.
4467
Douglas Gregore47f5a72009-10-14 23:41:34 +00004468 // C++0x [temp.explicit]p2:
4469 // There are two forms of explicit instantiation: an explicit instantiation
4470 // definition and an explicit instantiation declaration. An explicit
4471 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004472 TemplateSpecializationKind TSK
4473 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4474 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004475
John McCall27b18f82009-11-17 02:14:36 +00004476 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4477 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004478
4479 if (!R->isFunctionType()) {
4480 // C++ [temp.explicit]p1:
4481 // A [...] static data member of a class template can be explicitly
4482 // instantiated from the member definition associated with its class
4483 // template.
John McCall27b18f82009-11-17 02:14:36 +00004484 if (Previous.isAmbiguous())
4485 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00004486
John McCall67c00872009-12-02 08:25:40 +00004487 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00004488 if (!Prev || !Prev->isStaticDataMember()) {
4489 // We expect to see a data data member here.
4490 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4491 << Name;
4492 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4493 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004494 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004495 return true;
4496 }
4497
4498 if (!Prev->getInstantiatedFromStaticDataMember()) {
4499 // FIXME: Check for explicit specialization?
4500 Diag(D.getIdentifierLoc(),
4501 diag::err_explicit_instantiation_data_member_not_instantiated)
4502 << Prev;
4503 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4504 // FIXME: Can we provide a note showing where this was declared?
4505 return true;
4506 }
4507
Douglas Gregore47f5a72009-10-14 23:41:34 +00004508 // C++0x [temp.explicit]p2:
4509 // If the explicit instantiation is for a member function, a member class
4510 // or a static data member of a class template specialization, the name of
4511 // the class template specialization in the qualified-id for the member
4512 // name shall be a simple-template-id.
4513 //
4514 // C++98 has the same restriction, just worded differently.
4515 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4516 Diag(D.getIdentifierLoc(),
4517 diag::err_explicit_instantiation_without_qualified_id)
4518 << Prev << D.getCXXScopeSpec().getRange();
4519
4520 // Check the scope of this explicit instantiation.
4521 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4522
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004523 // Verify that it is okay to explicitly instantiate here.
4524 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4525 assert(MSInfo && "Missing static data member specialization info?");
4526 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004527 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004528 MSInfo->getTemplateSpecializationKind(),
4529 MSInfo->getPointOfInstantiation(),
4530 SuppressNew))
4531 return true;
4532 if (SuppressNew)
4533 return DeclPtrTy();
4534
Douglas Gregor450f00842009-09-25 18:43:00 +00004535 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004536 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004537 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004538 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4539 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004540
4541 // FIXME: Create an ExplicitInstantiation node?
4542 return DeclPtrTy();
4543 }
4544
Douglas Gregor0e876e02009-09-25 23:53:26 +00004545 // If the declarator is a template-id, translate the parser's template
4546 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004547 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004548 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004549 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4550 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00004551 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4552 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00004553 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4554 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004555 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00004556 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00004557 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004558 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004559 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004560
Douglas Gregor450f00842009-09-25 18:43:00 +00004561 // C++ [temp.explicit]p1:
4562 // A [...] function [...] can be explicitly instantiated from its template.
4563 // A member function [...] of a class template can be explicitly
4564 // instantiated from the member definition associated with its class
4565 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00004566 llvm::SmallVector<FunctionDecl *, 8> Matches;
4567 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4568 P != PEnd; ++P) {
4569 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004570 if (!HasExplicitTemplateArgs) {
4571 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4572 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4573 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004574
Douglas Gregord90fd522009-09-25 21:45:23 +00004575 Matches.push_back(Method);
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004576 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
4577 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00004578 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004579 }
4580 }
4581
4582 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4583 if (!FunTmpl)
4584 continue;
4585
4586 TemplateDeductionInfo Info(Context);
4587 FunctionDecl *Specialization = 0;
4588 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004589 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00004590 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004591 R, Specialization, Info)) {
4592 // FIXME: Keep track of almost-matches?
4593 (void)TDK;
4594 continue;
4595 }
4596
4597 Matches.push_back(Specialization);
4598 }
4599
4600 // Find the most specialized function template specialization.
4601 FunctionDecl *Specialization
4602 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4603 D.getIdentifierLoc(),
4604 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4605 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4606 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4607
4608 if (!Specialization)
4609 return true;
4610
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004611 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004612 Diag(D.getIdentifierLoc(),
4613 diag::err_explicit_instantiation_member_function_not_instantiated)
4614 << Specialization
4615 << (Specialization->getTemplateSpecializationKind() ==
4616 TSK_ExplicitSpecialization);
4617 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4618 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004619 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004620
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004621 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004622 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4623 PrevDecl = Specialization;
4624
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004625 if (PrevDecl) {
4626 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004627 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004628 PrevDecl,
4629 PrevDecl->getTemplateSpecializationKind(),
4630 PrevDecl->getPointOfInstantiation(),
4631 SuppressNew))
4632 return true;
4633
4634 // FIXME: We may still want to build some representation of this
4635 // explicit specialization.
4636 if (SuppressNew)
4637 return DeclPtrTy();
4638 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00004639
4640 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004641
4642 if (TSK == TSK_ExplicitInstantiationDefinition)
4643 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4644 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004645
Douglas Gregore47f5a72009-10-14 23:41:34 +00004646 // C++0x [temp.explicit]p2:
4647 // If the explicit instantiation is for a member function, a member class
4648 // or a static data member of a class template specialization, the name of
4649 // the class template specialization in the qualified-id for the member
4650 // name shall be a simple-template-id.
4651 //
4652 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004653 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00004654 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00004655 D.getCXXScopeSpec().isSet() &&
4656 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4657 Diag(D.getIdentifierLoc(),
4658 diag::err_explicit_instantiation_without_qualified_id)
4659 << Specialization << D.getCXXScopeSpec().getRange();
4660
4661 CheckExplicitInstantiationScope(*this,
4662 FunTmpl? (NamedDecl *)FunTmpl
4663 : Specialization->getInstantiatedFromMemberFunction(),
4664 D.getIdentifierLoc(),
4665 D.getCXXScopeSpec().isSet());
4666
Douglas Gregor450f00842009-09-25 18:43:00 +00004667 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4668 return DeclPtrTy();
4669}
4670
Douglas Gregor333489b2009-03-27 23:10:48 +00004671Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004672Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4673 const CXXScopeSpec &SS, IdentifierInfo *Name,
4674 SourceLocation TagLoc, SourceLocation NameLoc) {
4675 // This has to hold, because SS is expected to be defined.
4676 assert(Name && "Expected a name in a dependent tag");
4677
4678 NestedNameSpecifier *NNS
4679 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4680 if (!NNS)
4681 return true;
4682
4683 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4684 if (T.isNull())
4685 return true;
4686
4687 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4688 QualType ElabType = Context.getElaboratedType(T, TagKind);
4689
4690 return ElabType.getAsOpaquePtr();
4691}
4692
4693Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004694Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4695 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004696 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004697 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4698 if (!NNS)
4699 return true;
4700
4701 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004702 if (T.isNull())
4703 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004704 return T.getAsOpaquePtr();
4705}
4706
Douglas Gregordce2b622009-04-01 00:28:59 +00004707Sema::TypeResult
4708Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4709 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004710 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004711 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004712 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004713 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004714 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004715 assert(TemplateId && "Expected a template specialization type");
4716
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004717 if (computeDeclContext(SS, false)) {
4718 // If we can compute a declaration context, then the "typename"
4719 // keyword was superfluous. Just build a QualifiedNameType to keep
4720 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004721
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004722 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4723 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4724 }
Mike Stump11289f42009-09-09 15:08:12 +00004725
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004726 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004727}
4728
Douglas Gregor333489b2009-03-27 23:10:48 +00004729/// \brief Build the type that describes a C++ typename specifier,
4730/// e.g., "typename T::type".
4731QualType
4732Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4733 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004734 CXXRecordDecl *CurrentInstantiation = 0;
4735 if (NNS->isDependent()) {
4736 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004737
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004738 // If the nested-name-specifier does not refer to the current
4739 // instantiation, then build a typename type.
4740 if (!CurrentInstantiation)
4741 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004742
Douglas Gregorc707da62009-09-02 13:12:51 +00004743 // The nested-name-specifier refers to the current instantiation, so the
4744 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004745 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004746 // extraneous "typename" keywords, and we retroactively apply this DR to
4747 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004748 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004749
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004750 DeclContext *Ctx = 0;
4751
4752 if (CurrentInstantiation)
4753 Ctx = CurrentInstantiation;
4754 else {
4755 CXXScopeSpec SS;
4756 SS.setScopeRep(NNS);
4757 SS.setRange(Range);
4758 if (RequireCompleteDeclContext(SS))
4759 return QualType();
4760
4761 Ctx = computeDeclContext(SS);
4762 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004763 assert(Ctx && "No declaration context?");
4764
4765 DeclarationName Name(&II);
John McCall27b18f82009-11-17 02:14:36 +00004766 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4767 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00004768 unsigned DiagID = 0;
4769 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00004770 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004771 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004772 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004773 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00004774
4775 case LookupResult::NotFoundInCurrentInstantiation:
4776 // Okay, it's a member of an unknown instantiation.
4777 return Context.getTypenameType(NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00004778
4779 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004780 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004781 // We found a type. Build a QualifiedNameType, since the
4782 // typename-specifier was just sugar. FIXME: Tell
4783 // QualifiedNameType that it has a "typename" prefix.
4784 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4785 }
4786
4787 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004788 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004789 break;
4790
John McCalle61f2ba2009-11-18 02:36:19 +00004791 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004792 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00004793 return QualType();
4794
Douglas Gregor333489b2009-03-27 23:10:48 +00004795 case LookupResult::FoundOverloaded:
4796 DiagID = diag::err_typename_nested_not_type;
4797 Referenced = *Result.begin();
4798 break;
4799
John McCall6538c932009-10-10 05:48:19 +00004800 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004801 return QualType();
4802 }
4803
4804 // If we get here, it's because name lookup did not find a
4805 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004806 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004807 if (Referenced)
4808 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4809 << Name;
4810 return QualType();
4811}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004812
4813namespace {
4814 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00004815 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00004816 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004817 SourceLocation Loc;
4818 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004819
Douglas Gregor15acfb92009-08-06 16:20:37 +00004820 public:
Mike Stump11289f42009-09-09 15:08:12 +00004821 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004822 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004823 DeclarationName Entity)
4824 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004825 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004826
4827 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004828 /// transformed.
4829 ///
4830 /// For the purposes of type reconstruction, a type has already been
4831 /// transformed if it is NULL or if it is not dependent.
4832 bool AlreadyTransformed(QualType T) {
4833 return T.isNull() || !T->isDependentType();
4834 }
Mike Stump11289f42009-09-09 15:08:12 +00004835
4836 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004837 /// rebuilt.
4838 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004839
Douglas Gregor15acfb92009-08-06 16:20:37 +00004840 /// \brief Returns the name of the entity whose type is being rebuilt.
4841 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004842
Douglas Gregoref6ab412009-10-27 06:26:26 +00004843 /// \brief Sets the "base" location and entity when that
4844 /// information is known based on another transformation.
4845 void setBase(SourceLocation Loc, DeclarationName Entity) {
4846 this->Loc = Loc;
4847 this->Entity = Entity;
4848 }
4849
Douglas Gregor15acfb92009-08-06 16:20:37 +00004850 /// \brief Transforms an expression by returning the expression itself
4851 /// (an identity function).
4852 ///
4853 /// FIXME: This is completely unsafe; we will need to actually clone the
4854 /// expressions.
4855 Sema::OwningExprResult TransformExpr(Expr *E) {
4856 return getSema().Owned(E);
4857 }
Mike Stump11289f42009-09-09 15:08:12 +00004858
Douglas Gregor15acfb92009-08-06 16:20:37 +00004859 /// \brief Transforms a typename type by determining whether the type now
4860 /// refers to a member of the current instantiation, and then
4861 /// type-checking and building a QualifiedNameType (when possible).
John McCall550e0c22009-10-21 00:40:46 +00004862 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004863 };
4864}
4865
Mike Stump11289f42009-09-09 15:08:12 +00004866QualType
John McCall550e0c22009-10-21 00:40:46 +00004867CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4868 TypenameTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00004869 TypenameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00004870
Douglas Gregor15acfb92009-08-06 16:20:37 +00004871 NestedNameSpecifier *NNS
4872 = TransformNestedNameSpecifier(T->getQualifier(),
4873 /*FIXME:*/SourceRange(getBaseLocation()));
4874 if (!NNS)
4875 return QualType();
4876
4877 // If the nested-name-specifier did not change, and we cannot compute the
4878 // context corresponding to the nested-name-specifier, then this
4879 // typename type will not change; exit early.
4880 CXXScopeSpec SS;
4881 SS.setRange(SourceRange(getBaseLocation()));
4882 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00004883
4884 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004885 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00004886 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004887
4888 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004889 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00004890 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004891 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004892 = TransformType(QualType(TemplateId, 0));
4893 if (NewTemplateId.isNull())
4894 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004895
Douglas Gregor15acfb92009-08-06 16:20:37 +00004896 if (NNS == T->getQualifier() &&
4897 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00004898 Result = QualType(T, 0);
4899 else
4900 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4901 } else
4902 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4903 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00004904
John McCall0ad16662009-10-29 08:12:44 +00004905 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4906 NewTL.setNameLoc(TL.getNameLoc());
4907 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004908}
4909
4910/// \brief Rebuilds a type within the context of the current instantiation.
4911///
Mike Stump11289f42009-09-09 15:08:12 +00004912/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00004913/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00004914/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00004915/// partial specialization thereof). This routine will rebuild that type now
4916/// that we have entered the declarator's scope, which may produce different
4917/// canonical types, e.g.,
4918///
4919/// \code
4920/// template<typename T>
4921/// struct X {
4922/// typedef T* pointer;
4923/// pointer data();
4924/// };
4925///
4926/// template<typename T>
4927/// typename X<T>::pointer X<T>::data() { ... }
4928/// \endcode
4929///
4930/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4931/// since we do not know that we can look into X<T> when we parsed the type.
4932/// This function will rebuild the type, performing the lookup of "pointer"
4933/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4934/// as the canonical type of T*, allowing the return types of the out-of-line
4935/// definition and the declaration to match.
4936QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4937 DeclarationName Name) {
4938 if (T.isNull() || !T->isDependentType())
4939 return T;
Mike Stump11289f42009-09-09 15:08:12 +00004940
Douglas Gregor15acfb92009-08-06 16:20:37 +00004941 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4942 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00004943}
Douglas Gregorbe999392009-09-15 16:23:51 +00004944
4945/// \brief Produces a formatted string that describes the binding of
4946/// template parameters to template arguments.
4947std::string
4948Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4949 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004950 // FIXME: For variadic templates, we'll need to get the structured list.
4951 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4952 Args.flat_size());
4953}
4954
4955std::string
4956Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4957 const TemplateArgument *Args,
4958 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004959 std::string Result;
4960
Douglas Gregore62e6a02009-11-11 19:13:48 +00004961 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00004962 return Result;
4963
4964 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004965 if (I >= NumArgs)
4966 break;
4967
Douglas Gregorbe999392009-09-15 16:23:51 +00004968 if (I == 0)
4969 Result += "[with ";
4970 else
4971 Result += ", ";
4972
4973 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4974 Result += Id->getName();
4975 } else {
4976 Result += '$';
4977 Result += llvm::utostr(I);
4978 }
4979
4980 Result += " = ";
4981
4982 switch (Args[I].getKind()) {
4983 case TemplateArgument::Null:
4984 Result += "<no value>";
4985 break;
4986
4987 case TemplateArgument::Type: {
4988 std::string TypeStr;
4989 Args[I].getAsType().getAsStringInternal(TypeStr,
4990 Context.PrintingPolicy);
4991 Result += TypeStr;
4992 break;
4993 }
4994
4995 case TemplateArgument::Declaration: {
4996 bool Unnamed = true;
4997 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4998 if (ND->getDeclName()) {
4999 Unnamed = false;
5000 Result += ND->getNameAsString();
5001 }
5002 }
5003
5004 if (Unnamed) {
5005 Result += "<anonymous>";
5006 }
5007 break;
5008 }
5009
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005010 case TemplateArgument::Template: {
5011 std::string Str;
5012 llvm::raw_string_ostream OS(Str);
5013 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5014 Result += OS.str();
5015 break;
5016 }
5017
Douglas Gregorbe999392009-09-15 16:23:51 +00005018 case TemplateArgument::Integral: {
5019 Result += Args[I].getAsIntegral()->toString(10);
5020 break;
5021 }
5022
5023 case TemplateArgument::Expression: {
5024 assert(false && "No expressions in deduced template arguments!");
5025 Result += "<expression>";
5026 break;
5027 }
5028
5029 case TemplateArgument::Pack:
5030 // FIXME: Format template argument packs
5031 Result += "<template argument pack>";
5032 break;
5033 }
5034 }
5035
5036 Result += ']';
5037 return Result;
5038}