blob: c4da5a7f09ebc0c2dbad8305688ff330ba55f9a8 [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
146void Sema::LookupTemplateName(LookupResult &Found,
147 Scope *S, const CXXScopeSpec &SS,
148 QualType ObjectType,
149 bool EnteringContext) {
150 // Determine where to perform name lookup
151 DeclContext *LookupCtx = 0;
152 bool isDependent = false;
153 if (!ObjectType.isNull()) {
154 // This nested-name-specifier occurs in a member access expression, e.g.,
155 // x->B::f, and we are looking into the type of the object.
156 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
157 LookupCtx = computeDeclContext(ObjectType);
158 isDependent = ObjectType->isDependentType();
159 assert((isDependent || !ObjectType->isIncompleteType()) &&
160 "Caller should have completed object type");
161 } else if (SS.isSet()) {
162 // This nested-name-specifier occurs after another nested-name-specifier,
163 // so long into the context associated with the prior nested-name-specifier.
164 LookupCtx = computeDeclContext(SS, EnteringContext);
165 isDependent = isDependentScopeSpecifier(SS);
166
167 // The declaration context must be complete.
168 if (LookupCtx && RequireCompleteDeclContext(SS))
169 return;
170 }
171
172 bool ObjectTypeSearchedInScope = false;
173 if (LookupCtx) {
174 // Perform "qualified" name lookup into the declaration context we
175 // computed, which is either the type of the base of a member access
176 // expression or the declaration context associated with a prior
177 // nested-name-specifier.
178 LookupQualifiedName(Found, LookupCtx);
179
180 if (!ObjectType.isNull() && Found.empty()) {
181 // C++ [basic.lookup.classref]p1:
182 // In a class member access expression (5.2.5), if the . or -> token is
183 // immediately followed by an identifier followed by a <, the
184 // identifier must be looked up to determine whether the < is the
185 // beginning of a template argument list (14.2) or a less-than operator.
186 // The identifier is first looked up in the class of the object
187 // expression. If the identifier is not found, it is then looked up in
188 // the context of the entire postfix-expression and shall name a class
189 // or function template.
190 //
191 // FIXME: When we're instantiating a template, do we actually have to
192 // look in the scope of the template? Seems fishy...
193 if (S) LookupName(Found, S);
194 ObjectTypeSearchedInScope = true;
195 }
196 } else if (isDependent) {
197 // We cannot look into a dependent object type or
198 return;
199 } else {
200 // Perform unqualified name lookup in the current scope.
201 LookupName(Found, S);
202 }
203
204 // FIXME: Cope with ambiguous name-lookup results.
205 assert(!Found.isAmbiguous() &&
206 "Cannot handle template name-lookup ambiguities");
207
Douglas Gregorff18cc12009-12-31 08:11:17 +0000208 if (Found.empty()) {
209 // If we did not find any names, attempt to correct any typos.
210 DeclarationName Name = Found.getLookupName();
211 if (CorrectTypo(Found, S, &SS, LookupCtx)) {
212 FilterAcceptableTemplateNames(Context, Found);
213 if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
214 if (LookupCtx)
215 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
216 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
217 << CodeModificationHint::CreateReplacement(Found.getNameLoc(),
218 Found.getLookupName().getAsString());
219 else
220 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
221 << Name << Found.getLookupName()
222 << CodeModificationHint::CreateReplacement(Found.getNameLoc(),
223 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000224 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
225 Diag(Template->getLocation(), diag::note_previous_decl)
226 << Template->getDeclName();
Douglas Gregorff18cc12009-12-31 08:11:17 +0000227 } else
228 Found.clear();
229 } else {
230 Found.clear();
231 }
232 }
233
John McCalle66edc12009-11-24 19:00:30 +0000234 FilterAcceptableTemplateNames(Context, Found);
235 if (Found.empty())
236 return;
237
238 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
239 // C++ [basic.lookup.classref]p1:
240 // [...] If the lookup in the class of the object expression finds a
241 // template, the name is also looked up in the context of the entire
242 // postfix-expression and [...]
243 //
244 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
245 LookupOrdinaryName);
246 LookupName(FoundOuter, S);
247 FilterAcceptableTemplateNames(Context, FoundOuter);
248 // FIXME: Handle ambiguities in this lookup better
249
250 if (FoundOuter.empty()) {
251 // - if the name is not found, the name found in the class of the
252 // object expression is used, otherwise
253 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
254 // - if the name is found in the context of the entire
255 // postfix-expression and does not name a class template, the name
256 // found in the class of the object expression is used, otherwise
257 } else {
258 // - if the name found is a class template, it must refer to the same
259 // entity as the one found in the class of the object expression,
260 // otherwise the program is ill-formed.
261 if (!Found.isSingleResult() ||
262 Found.getFoundDecl()->getCanonicalDecl()
263 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
264 Diag(Found.getNameLoc(),
265 diag::err_nested_name_member_ref_lookup_ambiguous)
266 << Found.getLookupName();
267 Diag(Found.getRepresentativeDecl()->getLocation(),
268 diag::note_ambig_member_ref_object_type)
269 << ObjectType;
270 Diag(FoundOuter.getFoundDecl()->getLocation(),
271 diag::note_ambig_member_ref_scope);
272
273 // Recover by taking the template that we found in the object
274 // expression's type.
275 }
276 }
277 }
278}
279
John McCallcd4b4772009-12-02 03:53:29 +0000280/// ActOnDependentIdExpression - Handle a dependent id-expression that
281/// was just parsed. This is only possible with an explicit scope
282/// specifier naming a dependent type.
John McCalle66edc12009-11-24 19:00:30 +0000283Sema::OwningExprResult
284Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
285 DeclarationName Name,
286 SourceLocation NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +0000287 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000288 const TemplateArgumentListInfo *TemplateArgs) {
289 NestedNameSpecifier *Qualifier
290 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
291
John McCallcd4b4772009-12-02 03:53:29 +0000292 if (!isAddressOfOperand &&
293 isa<CXXMethodDecl>(CurContext) &&
294 cast<CXXMethodDecl>(CurContext)->isInstance()) {
295 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
296
John McCalle66edc12009-11-24 19:00:30 +0000297 // Since the 'this' expression is synthesized, we don't need to
298 // perform the double-lookup check.
299 NamedDecl *FirstQualifierInScope = 0;
300
John McCall2d74de92009-12-01 22:10:20 +0000301 return Owned(CXXDependentScopeMemberExpr::Create(Context,
302 /*This*/ 0, ThisType,
303 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000304 /*Op*/ SourceLocation(),
305 Qualifier, SS.getRange(),
306 FirstQualifierInScope,
307 Name, NameLoc,
308 TemplateArgs));
309 }
310
311 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
312}
313
314Sema::OwningExprResult
315Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
316 DeclarationName Name,
317 SourceLocation NameLoc,
318 const TemplateArgumentListInfo *TemplateArgs) {
319 return Owned(DependentScopeDeclRefExpr::Create(Context,
320 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
321 SS.getRange(),
322 Name, NameLoc,
323 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000324}
325
Douglas Gregor5101c242008-12-05 18:15:24 +0000326/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
327/// that the template parameter 'PrevDecl' is being shadowed by a new
328/// declaration at location Loc. Returns true to indicate that this is
329/// an error, and false otherwise.
330bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000331 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000332
333 // Microsoft Visual C++ permits template parameters to be shadowed.
334 if (getLangOptions().Microsoft)
335 return false;
336
337 // C++ [temp.local]p4:
338 // A template-parameter shall not be redeclared within its
339 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000340 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000341 << cast<NamedDecl>(PrevDecl)->getDeclName();
342 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
343 return true;
344}
345
Douglas Gregor463421d2009-03-03 04:44:36 +0000346/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000347/// the parameter D to reference the templated declaration and return a pointer
348/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000349TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000350 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000351 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000352 return Temp;
353 }
354 return 0;
355}
356
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000357static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
358 const ParsedTemplateArgument &Arg) {
359
360 switch (Arg.getKind()) {
361 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000362 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000363 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
364 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000365 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000366 return TemplateArgumentLoc(TemplateArgument(T), DI);
367 }
368
369 case ParsedTemplateArgument::NonType: {
370 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
371 return TemplateArgumentLoc(TemplateArgument(E), E);
372 }
373
374 case ParsedTemplateArgument::Template: {
375 TemplateName Template
376 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
377 return TemplateArgumentLoc(TemplateArgument(Template),
378 Arg.getScopeSpec().getRange(),
379 Arg.getLocation());
380 }
381 }
382
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000383 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000384 return TemplateArgumentLoc();
385}
386
387/// \brief Translates template arguments as provided by the parser
388/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000389void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
390 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000391 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000392 TemplateArgs.addArgument(translateTemplateArgument(*this,
393 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000394}
395
Douglas Gregor5101c242008-12-05 18:15:24 +0000396/// ActOnTypeParameter - Called when a C++ template type parameter
397/// (e.g., "typename T") has been parsed. Typename specifies whether
398/// the keyword "typename" was used to declare the type parameter
399/// (otherwise, "class" was used), and KeyLoc is the location of the
400/// "class" or "typename" keyword. ParamName is the name of the
401/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000402/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000403/// If the type parameter has a default argument, it will be added
404/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000405Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000406 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000407 SourceLocation KeyLoc,
408 IdentifierInfo *ParamName,
409 SourceLocation ParamNameLoc,
410 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000411 assert(S->isTemplateParamScope() &&
412 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000413 bool Invalid = false;
414
415 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000416 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000417 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000418 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000419 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000420 }
421
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000422 SourceLocation Loc = ParamNameLoc;
423 if (!ParamName)
424 Loc = KeyLoc;
425
Douglas Gregor5101c242008-12-05 18:15:24 +0000426 TemplateTypeParmDecl *Param
Mike Stump11289f42009-09-09 15:08:12 +0000427 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
428 Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000429 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000430 if (Invalid)
431 Param->setInvalidDecl();
432
433 if (ParamName) {
434 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000435 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000436 IdResolver.AddDecl(Param);
437 }
438
Chris Lattner83f095c2009-03-28 19:18:32 +0000439 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000440}
441
Douglas Gregordba32632009-02-10 19:49:53 +0000442/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000443/// Default) to the given template type parameter (TypeParam).
444void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000445 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000446 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000447 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000448 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000449 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000450
John McCallbcd03502009-12-07 02:54:59 +0000451 TypeSourceInfo *DefaultTInfo;
452 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall0ad16662009-10-29 08:12:44 +0000453
John McCallbcd03502009-12-07 02:54:59 +0000454 assert(DefaultTInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000455
Anders Carlssond3824352009-06-12 22:30:13 +0000456 // C++0x [temp.param]p9:
457 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000458 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000459 if (Parm->isParameterPack()) {
460 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000461 return;
462 }
Mike Stump11289f42009-09-09 15:08:12 +0000463
Douglas Gregordba32632009-02-10 19:49:53 +0000464 // C++ [temp.param]p14:
465 // A template-parameter shall not be used in its own default argument.
466 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000467
Douglas Gregordba32632009-02-10 19:49:53 +0000468 // Check the template argument itself.
John McCallbcd03502009-12-07 02:54:59 +0000469 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000470 Parm->setInvalidDecl();
471 return;
472 }
473
John McCallbcd03502009-12-07 02:54:59 +0000474 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000475}
476
Douglas Gregor463421d2009-03-03 04:44:36 +0000477/// \brief Check that the type of a non-type template parameter is
478/// well-formed.
479///
480/// \returns the (possibly-promoted) parameter type if valid;
481/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000482QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000483Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
484 // C++ [temp.param]p4:
485 //
486 // A non-type template-parameter shall have one of the following
487 // (optionally cv-qualified) types:
488 //
489 // -- integral or enumeration type,
490 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000491 // -- pointer to object or pointer to function,
492 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000493 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
494 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000495 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000496 T->isReferenceType() ||
497 // -- pointer to member.
498 T->isMemberPointerType() ||
499 // If T is a dependent type, we can't do the check now, so we
500 // assume that it is well-formed.
501 T->isDependentType())
502 return T;
503 // C++ [temp.param]p8:
504 //
505 // A non-type template-parameter of type "array of T" or
506 // "function returning T" is adjusted to be of type "pointer to
507 // T" or "pointer to function returning T", respectively.
508 else if (T->isArrayType())
509 // FIXME: Keep the type prior to promotion?
510 return Context.getArrayDecayedType(T);
511 else if (T->isFunctionType())
512 // FIXME: Keep the type prior to promotion?
513 return Context.getPointerType(T);
514
515 Diag(Loc, diag::err_template_nontype_parm_bad_type)
516 << T;
517
518 return QualType();
519}
520
Douglas Gregor5101c242008-12-05 18:15:24 +0000521/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
522/// template parameter (e.g., "int Size" in "template<int Size>
523/// class Array") has been parsed. S is the current scope and D is
524/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000525Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000526 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000527 unsigned Position) {
John McCallbcd03502009-12-07 02:54:59 +0000528 TypeSourceInfo *TInfo = 0;
529 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000530
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000531 assert(S->isTemplateParamScope() &&
532 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000533 bool Invalid = false;
534
535 IdentifierInfo *ParamName = D.getIdentifier();
536 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000537 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000538 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000539 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000540 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000541 }
542
Douglas Gregor463421d2009-03-03 04:44:36 +0000543 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000544 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000545 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000546 Invalid = true;
547 }
Douglas Gregor81338792009-02-10 17:43:50 +0000548
Douglas Gregor5101c242008-12-05 18:15:24 +0000549 NonTypeTemplateParmDecl *Param
550 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000551 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000552 if (Invalid)
553 Param->setInvalidDecl();
554
555 if (D.getIdentifier()) {
556 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000557 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000558 IdResolver.AddDecl(Param);
559 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000560 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000561}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000562
Douglas Gregordba32632009-02-10 19:49:53 +0000563/// \brief Adds a default argument to the given non-type template
564/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000565void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000566 SourceLocation EqualLoc,
567 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000568 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000569 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000570 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000571
Douglas Gregordba32632009-02-10 19:49:53 +0000572 // C++ [temp.param]p14:
573 // A template-parameter shall not be used in its own default argument.
574 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000575
Douglas Gregordba32632009-02-10 19:49:53 +0000576 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000577 TemplateArgument Converted;
578 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
579 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000580 TemplateParm->setInvalidDecl();
581 return;
582 }
583
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000584 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000585}
586
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000587
588/// ActOnTemplateTemplateParameter - Called when a C++ template template
589/// parameter (e.g. T in template <template <typename> class T> class array)
590/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000591Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
592 SourceLocation TmpLoc,
593 TemplateParamsTy *Params,
594 IdentifierInfo *Name,
595 SourceLocation NameLoc,
596 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000597 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000598 assert(S->isTemplateParamScope() &&
599 "Template template parameter not in template parameter scope!");
600
601 // Construct the parameter object.
602 TemplateTemplateParmDecl *Param =
603 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
604 Position, Name,
605 (TemplateParameterList*)Params);
606
607 // Make sure the parameter is valid.
608 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
609 // do anything yet. However, if the template parameter list or (eventual)
610 // default value is ever invalidated, that will propagate here.
611 bool Invalid = false;
612 if (Invalid) {
613 Param->setInvalidDecl();
614 }
615
616 // If the tt-param has a name, then link the identifier into the scope
617 // and lookup mechanisms.
618 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000619 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000620 IdResolver.AddDecl(Param);
621 }
622
Chris Lattner83f095c2009-03-28 19:18:32 +0000623 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000624}
625
Douglas Gregordba32632009-02-10 19:49:53 +0000626/// \brief Adds a default argument to the given template template
627/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000628void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000629 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000630 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000631 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000632 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000633
Douglas Gregordba32632009-02-10 19:49:53 +0000634 // C++ [temp.param]p14:
635 // A template-parameter shall not be used in its own default argument.
636 // FIXME: Implement this check! Needs a recursive walk over the types.
637
Douglas Gregore62e6a02009-11-11 19:13:48 +0000638 // Check only that we have a template template argument. We don't want to
639 // try to check well-formedness now, because our template template parameter
640 // might have dependent types in its template parameters, which we wouldn't
641 // be able to match now.
642 //
643 // If none of the template template parameter's template arguments mention
644 // other template parameters, we could actually perform more checking here.
645 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000646 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000647 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
648 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
649 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000650 return;
651 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000652
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000653 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000654}
655
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000656/// ActOnTemplateParameterList - Builds a TemplateParameterList that
657/// contains the template parameters in Params/NumParams.
658Sema::TemplateParamsTy *
659Sema::ActOnTemplateParameterList(unsigned Depth,
660 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000661 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000662 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000663 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000664 SourceLocation RAngleLoc) {
665 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000666 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000667
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000668 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000669 (NamedDecl**)Params, NumParams,
670 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000671}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000672
Douglas Gregorc08f4892009-03-25 00:13:59 +0000673Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000674Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000675 SourceLocation KWLoc, const CXXScopeSpec &SS,
676 IdentifierInfo *Name, SourceLocation NameLoc,
677 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000678 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000679 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000680 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000681 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000682 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000683 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000684
685 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000686 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000687 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000688
John McCall27b5c252009-09-14 21:59:20 +0000689 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
690 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000691
692 // There is no such thing as an unnamed class template.
693 if (!Name) {
694 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000695 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000696 }
697
698 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000699 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000700 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000701 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000702 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000703 if (RequireCompleteDeclContext(SS))
704 return true;
705
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000706 SemanticContext = computeDeclContext(SS, true);
707 if (!SemanticContext) {
708 // FIXME: Produce a reasonable diagnostic here
709 return true;
710 }
Mike Stump11289f42009-09-09 15:08:12 +0000711
John McCall27b18f82009-11-17 02:14:36 +0000712 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000713 } else {
714 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000715 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000716 }
Mike Stump11289f42009-09-09 15:08:12 +0000717
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000718 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
719 NamedDecl *PrevDecl = 0;
720 if (Previous.begin() != Previous.end())
721 PrevDecl = *Previous.begin();
722
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000723 // If there is a previous declaration with the same name, check
724 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000725 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000726 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000727
728 // We may have found the injected-class-name of a class template,
729 // class template partial specialization, or class template specialization.
730 // In these cases, grab the template that is being defined or specialized.
731 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
732 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
733 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
734 PrevClassTemplate
735 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
736 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
737 PrevClassTemplate
738 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
739 ->getSpecializedTemplate();
740 }
741 }
742
John McCalld43784f2009-12-18 11:25:59 +0000743 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000744 // C++ [namespace.memdef]p3:
745 // [...] When looking for a prior declaration of a class or a function
746 // declared as a friend, and when the name of the friend class or
747 // function is neither a qualified name nor a template-id, scopes outside
748 // the innermost enclosing namespace scope are not considered.
749 DeclContext *OutermostContext = CurContext;
750 while (!OutermostContext->isFileContext())
751 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000752
753 if (PrevDecl &&
754 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
755 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
John McCall90d3bb92009-12-17 23:21:11 +0000756 SemanticContext = PrevDecl->getDeclContext();
757 } else {
758 // Declarations in outer scopes don't matter. However, the outermost
759 // context we computed is the semantic context for our new
760 // declaration.
761 PrevDecl = PrevClassTemplate = 0;
762 SemanticContext = OutermostContext;
763 }
764
765 if (CurContext->isDependentContext()) {
766 // If this is a dependent context, we don't want to link the friend
767 // class template to the template in scope, because that would perform
768 // checking of the template parameter lists that can't be performed
769 // until the outer context is instantiated.
770 PrevDecl = PrevClassTemplate = 0;
771 }
772 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
773 PrevDecl = PrevClassTemplate = 0;
774
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000775 if (PrevClassTemplate) {
776 // Ensure that the template parameter lists are compatible.
777 if (!TemplateParameterListsAreEqual(TemplateParams,
778 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000779 /*Complain=*/true,
780 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000781 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000782
783 // C++ [temp.class]p4:
784 // In a redeclaration, partial specialization, explicit
785 // specialization or explicit instantiation of a class template,
786 // the class-key shall agree in kind with the original class
787 // template declaration (7.1.5.3).
788 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000789 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000790 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000791 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000792 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000793 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000794 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000795 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000796 }
797
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000798 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000799 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000800 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
801 Diag(NameLoc, diag::err_redefinition) << Name;
802 Diag(Def->getLocation(), diag::note_previous_definition);
803 // FIXME: Would it make sense to try to "forget" the previous
804 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000805 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000806 }
807 }
808 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
809 // Maybe we will complain about the shadowed template parameter.
810 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
811 // Just pretend that we didn't see the previous declaration.
812 PrevDecl = 0;
813 } else if (PrevDecl) {
814 // C++ [temp]p5:
815 // A class template shall not have the same name as any other
816 // template, class, function, object, enumeration, enumerator,
817 // namespace, or type in the same scope (3.3), except as specified
818 // in (14.5.4).
819 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
820 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000821 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000822 }
823
Douglas Gregordba32632009-02-10 19:49:53 +0000824 // Check the template parameter list of this declaration, possibly
825 // merging in the template parameter list from the previous class
826 // template declaration.
827 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000828 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
829 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000830 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000831
Douglas Gregore362cea2009-05-10 22:57:19 +0000832 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000833 // declaration!
834
Mike Stump11289f42009-09-09 15:08:12 +0000835 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000836 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000837 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000838 PrevClassTemplate->getTemplatedDecl() : 0,
839 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000840
841 ClassTemplateDecl *NewTemplate
842 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
843 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000844 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000845 NewClass->setDescribedClassTemplate(NewTemplate);
846
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000847 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000848 QualType T =
849 Context.getTypeDeclType(NewClass,
850 PrevClassTemplate?
851 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000852 assert(T->isDependentType() && "Class template type is not dependent?");
853 (void)T;
854
Douglas Gregorcf915552009-10-13 16:30:37 +0000855 // If we are providing an explicit specialization of a member that is a
856 // class template, make a note of that.
857 if (PrevClassTemplate &&
858 PrevClassTemplate->getInstantiatedFromMemberTemplate())
859 PrevClassTemplate->setMemberSpecialization();
860
Anders Carlsson137108d2009-03-26 01:24:28 +0000861 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000862 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000863 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000864
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000865 // Set the lexical context of these templates
866 NewClass->setLexicalDeclContext(CurContext);
867 NewTemplate->setLexicalDeclContext(CurContext);
868
John McCall9bb74a52009-07-31 02:45:11 +0000869 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000870 NewClass->startDefinition();
871
872 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000873 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000874
John McCall27b5c252009-09-14 21:59:20 +0000875 if (TUK != TUK_Friend)
876 PushOnScopeChains(NewTemplate, S);
877 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000878 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000879 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000880 NewClass->setAccess(PrevClassTemplate->getAccess());
881 }
John McCall27b5c252009-09-14 21:59:20 +0000882
Douglas Gregor3dad8422009-09-26 06:47:28 +0000883 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
884 PrevClassTemplate != NULL);
885
John McCall27b5c252009-09-14 21:59:20 +0000886 // Friend templates are visible in fairly strange ways.
887 if (!CurContext->isDependentContext()) {
888 DeclContext *DC = SemanticContext->getLookupContext();
889 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
890 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
891 PushOnScopeChains(NewTemplate, EnclosingScope,
892 /* AddToContext = */ false);
893 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000894
895 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
896 NewClass->getLocation(),
897 NewTemplate,
898 /*FIXME:*/NewClass->getLocation());
899 Friend->setAccess(AS_public);
900 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000901 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000902
Douglas Gregordba32632009-02-10 19:49:53 +0000903 if (Invalid) {
904 NewTemplate->setInvalidDecl();
905 NewClass->setInvalidDecl();
906 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000907 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000908}
909
Douglas Gregored5731f2009-11-25 17:50:39 +0000910/// \brief Diagnose the presence of a default template argument on a
911/// template parameter, which is ill-formed in certain contexts.
912///
913/// \returns true if the default template argument should be dropped.
914static bool DiagnoseDefaultTemplateArgument(Sema &S,
915 Sema::TemplateParamListContext TPC,
916 SourceLocation ParamLoc,
917 SourceRange DefArgRange) {
918 switch (TPC) {
919 case Sema::TPC_ClassTemplate:
920 return false;
921
922 case Sema::TPC_FunctionTemplate:
923 // C++ [temp.param]p9:
924 // A default template-argument shall not be specified in a
925 // function template declaration or a function template
926 // definition [...]
927 // (This sentence is not in C++0x, per DR226).
928 if (!S.getLangOptions().CPlusPlus0x)
929 S.Diag(ParamLoc,
930 diag::err_template_parameter_default_in_function_template)
931 << DefArgRange;
932 return false;
933
934 case Sema::TPC_ClassTemplateMember:
935 // C++0x [temp.param]p9:
936 // A default template-argument shall not be specified in the
937 // template-parameter-lists of the definition of a member of a
938 // class template that appears outside of the member's class.
939 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
940 << DefArgRange;
941 return true;
942
943 case Sema::TPC_FriendFunctionTemplate:
944 // C++ [temp.param]p9:
945 // A default template-argument shall not be specified in a
946 // friend template declaration.
947 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
948 << DefArgRange;
949 return true;
950
951 // FIXME: C++0x [temp.param]p9 allows default template-arguments
952 // for friend function templates if there is only a single
953 // declaration (and it is a definition). Strange!
954 }
955
956 return false;
957}
958
Douglas Gregordba32632009-02-10 19:49:53 +0000959/// \brief Checks the validity of a template parameter list, possibly
960/// considering the template parameter list from a previous
961/// declaration.
962///
963/// If an "old" template parameter list is provided, it must be
964/// equivalent (per TemplateParameterListsAreEqual) to the "new"
965/// template parameter list.
966///
967/// \param NewParams Template parameter list for a new template
968/// declaration. This template parameter list will be updated with any
969/// default arguments that are carried through from the previous
970/// template parameter list.
971///
972/// \param OldParams If provided, template parameter list from a
973/// previous declaration of the same template. Default template
974/// arguments will be merged from the old template parameter list to
975/// the new template parameter list.
976///
Douglas Gregored5731f2009-11-25 17:50:39 +0000977/// \param TPC Describes the context in which we are checking the given
978/// template parameter list.
979///
Douglas Gregordba32632009-02-10 19:49:53 +0000980/// \returns true if an error occurred, false otherwise.
981bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000982 TemplateParameterList *OldParams,
983 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +0000984 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +0000985
Douglas Gregordba32632009-02-10 19:49:53 +0000986 // C++ [temp.param]p10:
987 // The set of default template-arguments available for use with a
988 // template declaration or definition is obtained by merging the
989 // default arguments from the definition (if in scope) and all
990 // declarations in scope in the same way default function
991 // arguments are (8.3.6).
992 bool SawDefaultArgument = false;
993 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +0000994
Anders Carlsson327865d2009-06-12 23:20:15 +0000995 bool SawParameterPack = false;
996 SourceLocation ParameterPackLoc;
997
Mike Stumpc89c8e32009-02-11 23:03:27 +0000998 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +0000999 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001000 if (OldParams)
1001 OldParam = OldParams->begin();
1002
1003 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1004 NewParamEnd = NewParams->end();
1005 NewParam != NewParamEnd; ++NewParam) {
1006 // Variables used to diagnose redundant default arguments
1007 bool RedundantDefaultArg = false;
1008 SourceLocation OldDefaultLoc;
1009 SourceLocation NewDefaultLoc;
1010
1011 // Variables used to diagnose missing default arguments
1012 bool MissingDefaultArg = false;
1013
Anders Carlsson327865d2009-06-12 23:20:15 +00001014 // C++0x [temp.param]p11:
1015 // If a template parameter of a class template is a template parameter pack,
1016 // it must be the last template parameter.
1017 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001018 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001019 diag::err_template_param_pack_must_be_last_template_parameter);
1020 Invalid = true;
1021 }
1022
Douglas Gregordba32632009-02-10 19:49:53 +00001023 if (TemplateTypeParmDecl *NewTypeParm
1024 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001025 // Check the presence of a default argument here.
1026 if (NewTypeParm->hasDefaultArgument() &&
1027 DiagnoseDefaultTemplateArgument(*this, TPC,
1028 NewTypeParm->getLocation(),
1029 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1030 .getFullSourceRange()))
1031 NewTypeParm->removeDefaultArgument();
1032
1033 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001034 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001035 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001036
Anders Carlsson327865d2009-06-12 23:20:15 +00001037 if (NewTypeParm->isParameterPack()) {
1038 assert(!NewTypeParm->hasDefaultArgument() &&
1039 "Parameter packs can't have a default argument!");
1040 SawParameterPack = true;
1041 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001042 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001043 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001044 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1045 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1046 SawDefaultArgument = true;
1047 RedundantDefaultArg = true;
1048 PreviousDefaultArgLoc = NewDefaultLoc;
1049 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1050 // Merge the default argument from the old declaration to the
1051 // new declaration.
1052 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001053 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001054 true);
1055 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1056 } else if (NewTypeParm->hasDefaultArgument()) {
1057 SawDefaultArgument = true;
1058 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1059 } else if (SawDefaultArgument)
1060 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001061 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001062 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001063 // Check the presence of a default argument here.
1064 if (NewNonTypeParm->hasDefaultArgument() &&
1065 DiagnoseDefaultTemplateArgument(*this, TPC,
1066 NewNonTypeParm->getLocation(),
1067 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1068 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1069 NewNonTypeParm->setDefaultArgument(0);
1070 }
1071
Mike Stump12b8ce12009-08-04 21:02:39 +00001072 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001073 NonTypeTemplateParmDecl *OldNonTypeParm
1074 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001075 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001076 NewNonTypeParm->hasDefaultArgument()) {
1077 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1078 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1079 SawDefaultArgument = true;
1080 RedundantDefaultArg = true;
1081 PreviousDefaultArgLoc = NewDefaultLoc;
1082 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1083 // Merge the default argument from the old declaration to the
1084 // new declaration.
1085 SawDefaultArgument = true;
1086 // FIXME: We need to create a new kind of "default argument"
1087 // expression that points to a previous template template
1088 // parameter.
1089 NewNonTypeParm->setDefaultArgument(
1090 OldNonTypeParm->getDefaultArgument());
1091 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1092 } else if (NewNonTypeParm->hasDefaultArgument()) {
1093 SawDefaultArgument = true;
1094 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1095 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001096 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001097 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001098 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001099 TemplateTemplateParmDecl *NewTemplateParm
1100 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001101 if (NewTemplateParm->hasDefaultArgument() &&
1102 DiagnoseDefaultTemplateArgument(*this, TPC,
1103 NewTemplateParm->getLocation(),
1104 NewTemplateParm->getDefaultArgument().getSourceRange()))
1105 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1106
1107 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001108 TemplateTemplateParmDecl *OldTemplateParm
1109 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001110 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001111 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001112 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1113 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001114 SawDefaultArgument = true;
1115 RedundantDefaultArg = true;
1116 PreviousDefaultArgLoc = NewDefaultLoc;
1117 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1118 // Merge the default argument from the old declaration to the
1119 // new declaration.
1120 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001121 // FIXME: We need to create a new kind of "default argument" expression
1122 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001123 NewTemplateParm->setDefaultArgument(
1124 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001125 PreviousDefaultArgLoc
1126 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001127 } else if (NewTemplateParm->hasDefaultArgument()) {
1128 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001129 PreviousDefaultArgLoc
1130 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001131 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001132 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001133 }
1134
1135 if (RedundantDefaultArg) {
1136 // C++ [temp.param]p12:
1137 // A template-parameter shall not be given default arguments
1138 // by two different declarations in the same scope.
1139 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1140 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1141 Invalid = true;
1142 } else if (MissingDefaultArg) {
1143 // C++ [temp.param]p11:
1144 // If a template-parameter has a default template-argument,
1145 // all subsequent template-parameters shall have a default
1146 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001147 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001148 diag::err_template_param_default_arg_missing);
1149 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1150 Invalid = true;
1151 }
1152
1153 // If we have an old template parameter list that we're merging
1154 // in, move on to the next parameter.
1155 if (OldParams)
1156 ++OldParam;
1157 }
1158
1159 return Invalid;
1160}
Douglas Gregord32e0282009-02-09 23:23:08 +00001161
Mike Stump11289f42009-09-09 15:08:12 +00001162/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001163/// specifier, returning the template parameter list that applies to the
1164/// name.
1165///
1166/// \param DeclStartLoc the start of the declaration that has a scope
1167/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001168///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001169/// \param SS the scope specifier that will be matched to the given template
1170/// parameter lists. This scope specifier precedes a qualified name that is
1171/// being declared.
1172///
1173/// \param ParamLists the template parameter lists, from the outermost to the
1174/// innermost template parameter lists.
1175///
1176/// \param NumParamLists the number of template parameter lists in ParamLists.
1177///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001178/// \param IsExplicitSpecialization will be set true if the entity being
1179/// declared is an explicit specialization, false otherwise.
1180///
Mike Stump11289f42009-09-09 15:08:12 +00001181/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001182/// name that is preceded by the scope specifier @p SS. This template
1183/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001184/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001185/// template specialization), or may be NULL (if we were's declaring isn't
1186/// itself a template).
1187TemplateParameterList *
1188Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1189 const CXXScopeSpec &SS,
1190 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001191 unsigned NumParamLists,
1192 bool &IsExplicitSpecialization) {
1193 IsExplicitSpecialization = false;
1194
Douglas Gregord8d297c2009-07-21 23:53:31 +00001195 // Find the template-ids that occur within the nested-name-specifier. These
1196 // template-ids will match up with the template parameter lists.
1197 llvm::SmallVector<const TemplateSpecializationType *, 4>
1198 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001199 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1200 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001201 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1202 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001203 const Type *T = NNS->getAsType();
1204 if (!T) break;
1205
1206 // C++0x [temp.expl.spec]p17:
1207 // A member or a member template may be nested within many
1208 // enclosing class templates. In an explicit specialization for
1209 // such a member, the member declaration shall be preceded by a
1210 // template<> for each enclosing class template that is
1211 // explicitly specialized.
1212 // We interpret this as forbidding typedefs of template
1213 // specializations in the scope specifiers of out-of-line decls.
1214 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) {
1215 const Type *UnderlyingT = TT->LookThroughTypedefs().getTypePtr();
1216 if (isa<TemplateSpecializationType>(UnderlyingT))
1217 // FIXME: better source location information.
1218 Diag(DeclStartLoc, diag::err_typedef_in_def_scope) << QualType(T,0);
1219 T = UnderlyingT;
1220 }
1221
Mike Stump11289f42009-09-09 15:08:12 +00001222 if (const TemplateSpecializationType *SpecType
John McCall90034062009-12-15 02:19:47 +00001223 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001224 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1225 if (!Template)
1226 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001227
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001228 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001229 ClassTemplateSpecializationDecl *SpecDecl
1230 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1231 // If the nested name specifier refers to an explicit specialization,
1232 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001233 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1234 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001235 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001236 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001237 }
Mike Stump11289f42009-09-09 15:08:12 +00001238
Douglas Gregord8d297c2009-07-21 23:53:31 +00001239 TemplateIdsInSpecifier.push_back(SpecType);
1240 }
1241 }
Mike Stump11289f42009-09-09 15:08:12 +00001242
Douglas Gregord8d297c2009-07-21 23:53:31 +00001243 // Reverse the list of template-ids in the scope specifier, so that we can
1244 // more easily match up the template-ids and the template parameter lists.
1245 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001246
Douglas Gregord8d297c2009-07-21 23:53:31 +00001247 SourceLocation FirstTemplateLoc = DeclStartLoc;
1248 if (NumParamLists)
1249 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001250
Douglas Gregord8d297c2009-07-21 23:53:31 +00001251 // Match the template-ids found in the specifier to the template parameter
1252 // lists.
1253 unsigned Idx = 0;
1254 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1255 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001256 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1257 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001258 if (Idx >= NumParamLists) {
1259 // We have a template-id without a corresponding template parameter
1260 // list.
1261 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001262 // FIXME: the location information here isn't great.
1263 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001264 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001265 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001266 << SS.getRange();
1267 } else {
1268 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1269 << SS.getRange()
1270 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1271 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001272 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001273 }
1274 return 0;
1275 }
Mike Stump11289f42009-09-09 15:08:12 +00001276
Douglas Gregord8d297c2009-07-21 23:53:31 +00001277 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001278 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001279 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001280 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1281
Mike Stump11289f42009-09-09 15:08:12 +00001282 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001283 = dyn_cast<ClassTemplateDecl>(Template)) {
1284 TemplateParameterList *ExpectedTemplateParams = 0;
1285 // Is this template-id naming the primary template?
1286 if (Context.hasSameType(TemplateId,
1287 ClassTemplate->getInjectedClassNameType(Context)))
1288 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1289 // ... or a partial specialization?
1290 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1291 = ClassTemplate->findPartialSpecialization(TemplateId))
1292 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1293
1294 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001295 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001296 ExpectedTemplateParams,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001297 true, TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00001298 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001299
1300 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001301 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001302 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001303 diag::err_template_param_list_matches_nontemplate)
1304 << TemplateId
1305 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001306 else
1307 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001308 }
Mike Stump11289f42009-09-09 15:08:12 +00001309
Douglas Gregord8d297c2009-07-21 23:53:31 +00001310 // If there were at least as many template-ids as there were template
1311 // parameter lists, then there are no template parameter lists remaining for
1312 // the declaration itself.
1313 if (Idx >= NumParamLists)
1314 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001315
Douglas Gregord8d297c2009-07-21 23:53:31 +00001316 // If there were too many template parameter lists, complain about that now.
1317 if (Idx != NumParamLists - 1) {
1318 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001319 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001320 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001321 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1322 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001323 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1324 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001325
1326 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1327 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1328 diag::note_explicit_template_spec_does_not_need_header)
1329 << ExplicitSpecializationsInSpecifier.back();
1330 ExplicitSpecializationsInSpecifier.pop_back();
1331 }
1332
Douglas Gregord8d297c2009-07-21 23:53:31 +00001333 ++Idx;
1334 }
1335 }
Mike Stump11289f42009-09-09 15:08:12 +00001336
Douglas Gregord8d297c2009-07-21 23:53:31 +00001337 // Return the last template parameter list, which corresponds to the
1338 // entity being declared.
1339 return ParamLists[NumParamLists - 1];
1340}
1341
Douglas Gregordc572a32009-03-30 22:58:21 +00001342QualType Sema::CheckTemplateIdType(TemplateName Name,
1343 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001344 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001345 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001346 if (!Template) {
1347 // The template name does not resolve to a template, so we just
1348 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001349 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001350 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001351
Douglas Gregorc40290e2009-03-09 23:48:35 +00001352 // Check that the template argument list is well-formed for this
1353 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001354 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001355 TemplateArgs.size());
1356 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001357 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001358 return QualType();
1359
Mike Stump11289f42009-09-09 15:08:12 +00001360 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001361 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001362 "Converted template argument list is too short!");
1363
1364 QualType CanonType;
1365
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001366 if (Name.isDependent() ||
1367 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001368 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001369 // This class template specialization is a dependent
1370 // type. Therefore, its canonical type is another class template
1371 // specialization type that contains all of the converted
1372 // arguments in canonical form. This ensures that, e.g., A<T> and
1373 // A<T, T> have identical types when A is declared as:
1374 //
1375 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001376 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001377 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001378 Converted.getFlatArguments(),
1379 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001380
Douglas Gregora8e02e72009-07-28 23:00:59 +00001381 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001382 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001383 // In the future, we need to teach getTemplateSpecializationType to only
1384 // build the canonical type and return that to us.
1385 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001386 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001387 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001388 // Find the class template specialization declaration that
1389 // corresponds to these arguments.
1390 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001391 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001392 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001393 Converted.flatSize(),
1394 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001395 void *InsertPos = 0;
1396 ClassTemplateSpecializationDecl *Decl
1397 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1398 if (!Decl) {
1399 // This is the first time we have referenced this class template
1400 // specialization. Create the canonical declaration and add it to
1401 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001402 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001403 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001404 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001405 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001406 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001407 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1408 Decl->setLexicalDeclContext(CurContext);
1409 }
1410
1411 CanonType = Context.getTypeDeclType(Decl);
1412 }
Mike Stump11289f42009-09-09 15:08:12 +00001413
Douglas Gregorc40290e2009-03-09 23:48:35 +00001414 // Build the fully-sugared type for this class template
1415 // specialization, which refers back to the class template
1416 // specialization we created or found.
John McCall6b51f282009-11-23 01:53:49 +00001417 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001418}
1419
Douglas Gregor67a65642009-02-17 23:15:12 +00001420Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001421Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001422 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001423 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001424 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001425 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001426
Douglas Gregorc40290e2009-03-09 23:48:35 +00001427 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001428 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001429 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001430
John McCall6b51f282009-11-23 01:53:49 +00001431 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001432 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001433
1434 if (Result.isNull())
1435 return true;
1436
John McCallbcd03502009-12-07 02:54:59 +00001437 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001438 TemplateSpecializationTypeLoc TL
1439 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1440 TL.setTemplateNameLoc(TemplateLoc);
1441 TL.setLAngleLoc(LAngleLoc);
1442 TL.setRAngleLoc(RAngleLoc);
1443 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1444 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1445
1446 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001447}
John McCall06f6fe8d2009-09-04 01:14:41 +00001448
John McCalld8fe9af2009-09-08 17:47:29 +00001449Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1450 TagUseKind TUK,
1451 DeclSpec::TST TagSpec,
1452 SourceLocation TagLoc) {
1453 if (TypeResult.isInvalid())
1454 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001455
John McCall0ad16662009-10-29 08:12:44 +00001456 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001457 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001458 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001459
John McCalld8fe9af2009-09-08 17:47:29 +00001460 // Verify the tag specifier.
1461 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001462
John McCalld8fe9af2009-09-08 17:47:29 +00001463 if (const RecordType *RT = Type->getAs<RecordType>()) {
1464 RecordDecl *D = RT->getDecl();
1465
1466 IdentifierInfo *Id = D->getIdentifier();
1467 assert(Id && "templated class must have an identifier");
1468
1469 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1470 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001471 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001472 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1473 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001474 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001475 }
1476 }
1477
John McCalld8fe9af2009-09-08 17:47:29 +00001478 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1479
1480 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001481}
1482
John McCalle66edc12009-11-24 19:00:30 +00001483Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1484 LookupResult &R,
1485 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001486 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001487 // FIXME: Can we do any checking at this point? I guess we could check the
1488 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001489 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001490 // though.
John McCalle66edc12009-11-24 19:00:30 +00001491
1492 // These should be filtered out by our callers.
1493 assert(!R.empty() && "empty lookup results when building templateid");
1494 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1495
1496 NestedNameSpecifier *Qualifier = 0;
1497 SourceRange QualifierRange;
1498 if (SS.isSet()) {
1499 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1500 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001501 }
1502
John McCalle66edc12009-11-24 19:00:30 +00001503 bool Dependent
1504 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1505 &TemplateArgs);
1506 UnresolvedLookupExpr *ULE
1507 = UnresolvedLookupExpr::Create(Context, Dependent,
1508 Qualifier, QualifierRange,
1509 R.getLookupName(), R.getNameLoc(),
1510 RequiresADL, TemplateArgs);
1511 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1512 ULE->addDecl(*I);
1513
1514 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001515}
1516
John McCalle66edc12009-11-24 19:00:30 +00001517// We actually only call this from template instantiation.
1518Sema::OwningExprResult
1519Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1520 DeclarationName Name,
1521 SourceLocation NameLoc,
1522 const TemplateArgumentListInfo &TemplateArgs) {
1523 DeclContext *DC;
1524 if (!(DC = computeDeclContext(SS, false)) ||
1525 DC->isDependentContext() ||
1526 RequireCompleteDeclContext(SS))
1527 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001528
John McCalle66edc12009-11-24 19:00:30 +00001529 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1530 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00001531
John McCalle66edc12009-11-24 19:00:30 +00001532 if (R.isAmbiguous())
1533 return ExprError();
1534
1535 if (R.empty()) {
1536 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1537 << Name << SS.getRange();
1538 return ExprError();
1539 }
1540
1541 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1542 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1543 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1544 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1545 return ExprError();
1546 }
1547
1548 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001549}
1550
Douglas Gregorb67535d2009-03-31 00:43:58 +00001551/// \brief Form a dependent template name.
1552///
1553/// This action forms a dependent template name given the template
1554/// name and its (presumably dependent) scope specifier. For
1555/// example, given "MetaFun::template apply", the scope specifier \p
1556/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1557/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001558Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001559Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001560 const CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001561 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001562 TypeTy *ObjectType,
1563 bool EnteringContext) {
Mike Stump11289f42009-09-09 15:08:12 +00001564 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001565 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001566 (SS.isSet() && computeDeclContext(SS, EnteringContext))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001567 // C++0x [temp.names]p5:
1568 // If a name prefixed by the keyword template is not the name of
1569 // a template, the program is ill-formed. [Note: the keyword
1570 // template may not be applied to non-template members of class
1571 // templates. -end note ] [ Note: as is the case with the
1572 // typename prefix, the template prefix is allowed in cases
1573 // where it is not strictly necessary; i.e., when the
1574 // nested-name-specifier or the expression on the left of the ->
1575 // or . is not dependent on a template-parameter, or the use
1576 // does not appear in the scope of a template. -end note]
1577 //
1578 // Note: C++03 was more strict here, because it banned the use of
1579 // the "template" keyword prior to a template-name that was not a
1580 // dependent name. C++ DR468 relaxed this requirement (the
1581 // "template" keyword is now permitted). We follow the C++0x
1582 // rules, even in C++03 mode, retroactively applying the DR.
1583 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001584 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001585 EnteringContext, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001586 if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001587 Diag(Name.getSourceRange().getBegin(),
1588 diag::err_template_kw_refers_to_non_template)
1589 << GetNameFromUnqualifiedId(Name)
1590 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001591 return TemplateTy();
1592 }
1593
1594 return Template;
1595 }
1596
Mike Stump11289f42009-09-09 15:08:12 +00001597 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001598 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001599
1600 switch (Name.getKind()) {
1601 case UnqualifiedId::IK_Identifier:
1602 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1603 Name.Identifier));
1604
Douglas Gregor71395fa2009-11-04 00:56:37 +00001605 case UnqualifiedId::IK_OperatorFunctionId:
1606 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1607 Name.OperatorFunctionId.Operator));
Alexis Hunted0530f2009-11-28 08:58:14 +00001608
1609 case UnqualifiedId::IK_LiteralOperatorId:
1610 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1611
Douglas Gregor3cf81312009-11-03 23:16:33 +00001612 default:
1613 break;
1614 }
1615
1616 Diag(Name.getSourceRange().getBegin(),
1617 diag::err_template_kw_refers_to_non_template)
1618 << GetNameFromUnqualifiedId(Name)
1619 << Name.getSourceRange();
1620 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001621}
1622
Mike Stump11289f42009-09-09 15:08:12 +00001623bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001624 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001625 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001626 const TemplateArgument &Arg = AL.getArgument();
1627
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001628 // Check template type parameter.
1629 if (Arg.getKind() != TemplateArgument::Type) {
1630 // C++ [temp.arg.type]p1:
1631 // A template-argument for a template-parameter which is a
1632 // type shall be a type-id.
1633
1634 // We have a template type parameter but the template argument
1635 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001636 SourceRange SR = AL.getSourceRange();
1637 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001638 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001639
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001640 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001641 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001642
John McCallbcd03502009-12-07 02:54:59 +00001643 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001644 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001645
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001646 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001647 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001648 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001649 return false;
1650}
1651
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001652/// \brief Substitute template arguments into the default template argument for
1653/// the given template type parameter.
1654///
1655/// \param SemaRef the semantic analysis object for which we are performing
1656/// the substitution.
1657///
1658/// \param Template the template that we are synthesizing template arguments
1659/// for.
1660///
1661/// \param TemplateLoc the location of the template name that started the
1662/// template-id we are checking.
1663///
1664/// \param RAngleLoc the location of the right angle bracket ('>') that
1665/// terminates the template-id.
1666///
1667/// \param Param the template template parameter whose default we are
1668/// substituting into.
1669///
1670/// \param Converted the list of template arguments provided for template
1671/// parameters that precede \p Param in the template parameter list.
1672///
1673/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001674static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001675SubstDefaultTemplateArgument(Sema &SemaRef,
1676 TemplateDecl *Template,
1677 SourceLocation TemplateLoc,
1678 SourceLocation RAngleLoc,
1679 TemplateTypeParmDecl *Param,
1680 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001681 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001682
1683 // If the argument type is dependent, instantiate it now based
1684 // on the previously-computed template arguments.
1685 if (ArgType->getType()->isDependentType()) {
1686 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1687 /*TakeArgs=*/false);
1688
1689 MultiLevelTemplateArgumentList AllTemplateArgs
1690 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1691
1692 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1693 Template, Converted.getFlatArguments(),
1694 Converted.flatSize(),
1695 SourceRange(TemplateLoc, RAngleLoc));
1696
1697 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1698 Param->getDefaultArgumentLoc(),
1699 Param->getDeclName());
1700 }
1701
1702 return ArgType;
1703}
1704
1705/// \brief Substitute template arguments into the default template argument for
1706/// the given non-type template parameter.
1707///
1708/// \param SemaRef the semantic analysis object for which we are performing
1709/// the substitution.
1710///
1711/// \param Template the template that we are synthesizing template arguments
1712/// for.
1713///
1714/// \param TemplateLoc the location of the template name that started the
1715/// template-id we are checking.
1716///
1717/// \param RAngleLoc the location of the right angle bracket ('>') that
1718/// terminates the template-id.
1719///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001720/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001721/// substituting into.
1722///
1723/// \param Converted the list of template arguments provided for template
1724/// parameters that precede \p Param in the template parameter list.
1725///
1726/// \returns the substituted template argument, or NULL if an error occurred.
1727static Sema::OwningExprResult
1728SubstDefaultTemplateArgument(Sema &SemaRef,
1729 TemplateDecl *Template,
1730 SourceLocation TemplateLoc,
1731 SourceLocation RAngleLoc,
1732 NonTypeTemplateParmDecl *Param,
1733 TemplateArgumentListBuilder &Converted) {
1734 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1735 /*TakeArgs=*/false);
1736
1737 MultiLevelTemplateArgumentList AllTemplateArgs
1738 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1739
1740 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1741 Template, Converted.getFlatArguments(),
1742 Converted.flatSize(),
1743 SourceRange(TemplateLoc, RAngleLoc));
1744
1745 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1746}
1747
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001748/// \brief Substitute template arguments into the default template argument for
1749/// the given template template parameter.
1750///
1751/// \param SemaRef the semantic analysis object for which we are performing
1752/// the substitution.
1753///
1754/// \param Template the template that we are synthesizing template arguments
1755/// for.
1756///
1757/// \param TemplateLoc the location of the template name that started the
1758/// template-id we are checking.
1759///
1760/// \param RAngleLoc the location of the right angle bracket ('>') that
1761/// terminates the template-id.
1762///
1763/// \param Param the template template parameter whose default we are
1764/// substituting into.
1765///
1766/// \param Converted the list of template arguments provided for template
1767/// parameters that precede \p Param in the template parameter list.
1768///
1769/// \returns the substituted template argument, or NULL if an error occurred.
1770static TemplateName
1771SubstDefaultTemplateArgument(Sema &SemaRef,
1772 TemplateDecl *Template,
1773 SourceLocation TemplateLoc,
1774 SourceLocation RAngleLoc,
1775 TemplateTemplateParmDecl *Param,
1776 TemplateArgumentListBuilder &Converted) {
1777 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1778 /*TakeArgs=*/false);
1779
1780 MultiLevelTemplateArgumentList AllTemplateArgs
1781 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1782
1783 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1784 Template, Converted.getFlatArguments(),
1785 Converted.flatSize(),
1786 SourceRange(TemplateLoc, RAngleLoc));
1787
1788 return SemaRef.SubstTemplateName(
1789 Param->getDefaultArgument().getArgument().getAsTemplate(),
1790 Param->getDefaultArgument().getTemplateNameLoc(),
1791 AllTemplateArgs);
1792}
1793
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001794/// \brief If the given template parameter has a default template
1795/// argument, substitute into that default template argument and
1796/// return the corresponding template argument.
1797TemplateArgumentLoc
1798Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1799 SourceLocation TemplateLoc,
1800 SourceLocation RAngleLoc,
1801 Decl *Param,
1802 TemplateArgumentListBuilder &Converted) {
1803 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1804 if (!TypeParm->hasDefaultArgument())
1805 return TemplateArgumentLoc();
1806
John McCallbcd03502009-12-07 02:54:59 +00001807 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001808 TemplateLoc,
1809 RAngleLoc,
1810 TypeParm,
1811 Converted);
1812 if (DI)
1813 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1814
1815 return TemplateArgumentLoc();
1816 }
1817
1818 if (NonTypeTemplateParmDecl *NonTypeParm
1819 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1820 if (!NonTypeParm->hasDefaultArgument())
1821 return TemplateArgumentLoc();
1822
1823 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1824 TemplateLoc,
1825 RAngleLoc,
1826 NonTypeParm,
1827 Converted);
1828 if (Arg.isInvalid())
1829 return TemplateArgumentLoc();
1830
1831 Expr *ArgE = Arg.takeAs<Expr>();
1832 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1833 }
1834
1835 TemplateTemplateParmDecl *TempTempParm
1836 = cast<TemplateTemplateParmDecl>(Param);
1837 if (!TempTempParm->hasDefaultArgument())
1838 return TemplateArgumentLoc();
1839
1840 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1841 TemplateLoc,
1842 RAngleLoc,
1843 TempTempParm,
1844 Converted);
1845 if (TName.isNull())
1846 return TemplateArgumentLoc();
1847
1848 return TemplateArgumentLoc(TemplateArgument(TName),
1849 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1850 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1851}
1852
Douglas Gregorda0fb532009-11-11 19:31:23 +00001853/// \brief Check that the given template argument corresponds to the given
1854/// template parameter.
1855bool Sema::CheckTemplateArgument(NamedDecl *Param,
1856 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001857 TemplateDecl *Template,
1858 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001859 SourceLocation RAngleLoc,
1860 TemplateArgumentListBuilder &Converted) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001861 // Check template type parameters.
1862 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001863 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001864
Douglas Gregoreebed722009-11-11 19:41:09 +00001865 // Check non-type template parameters.
1866 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001867 // Do substitution on the type of the non-type template parameter
1868 // with the template arguments we've seen thus far.
1869 QualType NTTPType = NTTP->getType();
1870 if (NTTPType->isDependentType()) {
1871 // Do substitution on the type of the non-type template parameter.
1872 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1873 NTTP, Converted.getFlatArguments(),
1874 Converted.flatSize(),
1875 SourceRange(TemplateLoc, RAngleLoc));
1876
1877 TemplateArgumentList TemplateArgs(Context, Converted,
1878 /*TakeArgs=*/false);
1879 NTTPType = SubstType(NTTPType,
1880 MultiLevelTemplateArgumentList(TemplateArgs),
1881 NTTP->getLocation(),
1882 NTTP->getDeclName());
1883 // If that worked, check the non-type template parameter type
1884 // for validity.
1885 if (!NTTPType.isNull())
1886 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1887 NTTP->getLocation());
1888 if (NTTPType.isNull())
1889 return true;
1890 }
1891
1892 switch (Arg.getArgument().getKind()) {
1893 case TemplateArgument::Null:
1894 assert(false && "Should never see a NULL template argument here");
1895 return true;
1896
1897 case TemplateArgument::Expression: {
1898 Expr *E = Arg.getArgument().getAsExpr();
1899 TemplateArgument Result;
1900 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1901 return true;
1902
1903 Converted.Append(Result);
1904 break;
1905 }
1906
1907 case TemplateArgument::Declaration:
1908 case TemplateArgument::Integral:
1909 // We've already checked this template argument, so just copy
1910 // it to the list of converted arguments.
1911 Converted.Append(Arg.getArgument());
1912 break;
1913
1914 case TemplateArgument::Template:
1915 // We were given a template template argument. It may not be ill-formed;
1916 // see below.
1917 if (DependentTemplateName *DTN
1918 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1919 // We have a template argument such as \c T::template X, which we
1920 // parsed as a template template argument. However, since we now
1921 // know that we need a non-type template argument, convert this
1922 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00001923 Expr *E = DependentScopeDeclRefExpr::Create(Context,
1924 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00001925 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00001926 DTN->getIdentifier(),
1927 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00001928
1929 TemplateArgument Result;
1930 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1931 return true;
1932
1933 Converted.Append(Result);
1934 break;
1935 }
1936
1937 // We have a template argument that actually does refer to a class
1938 // template, template alias, or template template parameter, and
1939 // therefore cannot be a non-type template argument.
1940 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1941 << Arg.getSourceRange();
1942
1943 Diag(Param->getLocation(), diag::note_template_param_here);
1944 return true;
1945
1946 case TemplateArgument::Type: {
1947 // We have a non-type template parameter but the template
1948 // argument is a type.
1949
1950 // C++ [temp.arg]p2:
1951 // In a template-argument, an ambiguity between a type-id and
1952 // an expression is resolved to a type-id, regardless of the
1953 // form of the corresponding template-parameter.
1954 //
1955 // We warn specifically about this case, since it can be rather
1956 // confusing for users.
1957 QualType T = Arg.getArgument().getAsType();
1958 SourceRange SR = Arg.getSourceRange();
1959 if (T->isFunctionType())
1960 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1961 else
1962 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1963 Diag(Param->getLocation(), diag::note_template_param_here);
1964 return true;
1965 }
1966
1967 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001968 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00001969 break;
1970 }
1971
1972 return false;
1973 }
1974
1975
1976 // Check template template parameters.
1977 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
1978
1979 // Substitute into the template parameter list of the template
1980 // template parameter, since previously-supplied template arguments
1981 // may appear within the template template parameter.
1982 {
1983 // Set up a template instantiation context.
1984 LocalInstantiationScope Scope(*this);
1985 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1986 TempParm, Converted.getFlatArguments(),
1987 Converted.flatSize(),
1988 SourceRange(TemplateLoc, RAngleLoc));
1989
1990 TemplateArgumentList TemplateArgs(Context, Converted,
1991 /*TakeArgs=*/false);
1992 TempParm = cast_or_null<TemplateTemplateParmDecl>(
1993 SubstDecl(TempParm, CurContext,
1994 MultiLevelTemplateArgumentList(TemplateArgs)));
1995 if (!TempParm)
1996 return true;
1997
1998 // FIXME: TempParam is leaked.
1999 }
2000
2001 switch (Arg.getArgument().getKind()) {
2002 case TemplateArgument::Null:
2003 assert(false && "Should never see a NULL template argument here");
2004 return true;
2005
2006 case TemplateArgument::Template:
2007 if (CheckTemplateArgument(TempParm, Arg))
2008 return true;
2009
2010 Converted.Append(Arg.getArgument());
2011 break;
2012
2013 case TemplateArgument::Expression:
2014 case TemplateArgument::Type:
2015 // We have a template template parameter but the template
2016 // argument does not refer to a template.
2017 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2018 return true;
2019
2020 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002021 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002022 "Declaration argument with template template parameter");
2023 break;
2024 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002025 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002026 "Integral argument with template template parameter");
2027 break;
2028
2029 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002030 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002031 break;
2032 }
2033
2034 return false;
2035}
2036
Douglas Gregord32e0282009-02-09 23:23:08 +00002037/// \brief Check that the given template argument list is well-formed
2038/// for specializing the given template.
2039bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2040 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002041 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002042 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002043 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002044 TemplateParameterList *Params = Template->getTemplateParameters();
2045 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002046 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002047 bool Invalid = false;
2048
John McCall6b51f282009-11-23 01:53:49 +00002049 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2050
Mike Stump11289f42009-09-09 15:08:12 +00002051 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002052 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002053
Anders Carlsson15201f12009-06-13 02:08:00 +00002054 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002055 (NumArgs < Params->getMinRequiredArguments() &&
2056 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002057 // FIXME: point at either the first arg beyond what we can handle,
2058 // or the '>', depending on whether we have too many or too few
2059 // arguments.
2060 SourceRange Range;
2061 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002062 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002063 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2064 << (NumArgs > NumParams)
2065 << (isa<ClassTemplateDecl>(Template)? 0 :
2066 isa<FunctionTemplateDecl>(Template)? 1 :
2067 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2068 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002069 Diag(Template->getLocation(), diag::note_template_decl_here)
2070 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002071 Invalid = true;
2072 }
Mike Stump11289f42009-09-09 15:08:12 +00002073
2074 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002075 // [...] The type and form of each template-argument specified in
2076 // a template-id shall match the type and form specified for the
2077 // corresponding parameter declared by the template in its
2078 // template-parameter-list.
2079 unsigned ArgIdx = 0;
2080 for (TemplateParameterList::iterator Param = Params->begin(),
2081 ParamEnd = Params->end();
2082 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002083 if (ArgIdx > NumArgs && PartialTemplateArgs)
2084 break;
Mike Stump11289f42009-09-09 15:08:12 +00002085
Douglas Gregoreebed722009-11-11 19:41:09 +00002086 // If we have a template parameter pack, check every remaining template
2087 // argument against that template parameter pack.
2088 if ((*Param)->isTemplateParameterPack()) {
2089 Converted.BeginPack();
2090 for (; ArgIdx < NumArgs; ++ArgIdx) {
2091 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2092 TemplateLoc, RAngleLoc, Converted)) {
2093 Invalid = true;
2094 break;
2095 }
2096 }
2097 Converted.EndPack();
2098 continue;
2099 }
2100
Douglas Gregor84d49a22009-11-11 21:54:23 +00002101 if (ArgIdx < NumArgs) {
2102 // Check the template argument we were given.
2103 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2104 TemplateLoc, RAngleLoc, Converted))
2105 return true;
2106
2107 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002108 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002109
Douglas Gregor84d49a22009-11-11 21:54:23 +00002110 // We have a default template argument that we will use.
2111 TemplateArgumentLoc Arg;
2112
2113 // Retrieve the default template argument from the template
2114 // parameter. For each kind of template parameter, we substitute the
2115 // template arguments provided thus far and any "outer" template arguments
2116 // (when the template parameter was part of a nested template) into
2117 // the default argument.
2118 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2119 if (!TTP->hasDefaultArgument()) {
2120 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2121 break;
2122 }
2123
John McCallbcd03502009-12-07 02:54:59 +00002124 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002125 Template,
2126 TemplateLoc,
2127 RAngleLoc,
2128 TTP,
2129 Converted);
2130 if (!ArgType)
2131 return true;
2132
2133 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2134 ArgType);
2135 } else if (NonTypeTemplateParmDecl *NTTP
2136 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2137 if (!NTTP->hasDefaultArgument()) {
2138 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2139 break;
2140 }
2141
2142 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2143 TemplateLoc,
2144 RAngleLoc,
2145 NTTP,
2146 Converted);
2147 if (E.isInvalid())
2148 return true;
2149
2150 Expr *Ex = E.takeAs<Expr>();
2151 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2152 } else {
2153 TemplateTemplateParmDecl *TempParm
2154 = cast<TemplateTemplateParmDecl>(*Param);
2155
2156 if (!TempParm->hasDefaultArgument()) {
2157 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2158 break;
2159 }
2160
2161 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2162 TemplateLoc,
2163 RAngleLoc,
2164 TempParm,
2165 Converted);
2166 if (Name.isNull())
2167 return true;
2168
2169 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2170 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2171 TempParm->getDefaultArgument().getTemplateNameLoc());
2172 }
2173
2174 // Introduce an instantiation record that describes where we are using
2175 // the default template argument.
2176 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2177 Converted.getFlatArguments(),
2178 Converted.flatSize(),
2179 SourceRange(TemplateLoc, RAngleLoc));
2180
2181 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002182 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002183 RAngleLoc, Converted))
2184 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002185 }
2186
2187 return Invalid;
2188}
2189
2190/// \brief Check a template argument against its corresponding
2191/// template type parameter.
2192///
2193/// This routine implements the semantics of C++ [temp.arg.type]. It
2194/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002195bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002196 TypeSourceInfo *ArgInfo) {
2197 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002198 QualType Arg = ArgInfo->getType();
2199
Douglas Gregord32e0282009-02-09 23:23:08 +00002200 // C++ [temp.arg.type]p2:
2201 // A local type, a type with no linkage, an unnamed type or a type
2202 // compounded from any of these types shall not be used as a
2203 // template-argument for a template type-parameter.
2204 //
2205 // FIXME: Perform the recursive and no-linkage type checks.
2206 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002207 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002208 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002209 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002210 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002211 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2212 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2213 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2214 << QualType(Tag, 0) << SR;
2215 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002216 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002217 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2218 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002219 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2220 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002221 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2222 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2223 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002224 }
2225
2226 return false;
2227}
2228
Douglas Gregorccb07762009-02-11 19:52:55 +00002229/// \brief Checks whether the given template argument is the address
2230/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002231bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2232 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002233 bool Invalid = false;
2234
2235 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002236 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002237 Arg = Cast->getSubExpr();
2238
Sebastian Redl576fd422009-05-10 18:38:11 +00002239 // C++0x allows nullptr, and there's no further checking to be done for that.
2240 if (Arg->getType()->isNullPtrType())
2241 return false;
2242
Douglas Gregorccb07762009-02-11 19:52:55 +00002243 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002244 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002245 // A template-argument for a non-type, non-template
2246 // template-parameter shall be one of: [...]
2247 //
2248 // -- the address of an object or function with external
2249 // linkage, including function templates and function
2250 // template-ids but excluding non-static class members,
2251 // expressed as & id-expression where the & is optional if
2252 // the name refers to a function or array, or if the
2253 // corresponding template-parameter is a reference; or
2254 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002255
Douglas Gregorccb07762009-02-11 19:52:55 +00002256 // Ignore (and complain about) any excess parentheses.
2257 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2258 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002259 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002260 diag::err_template_arg_extra_parens)
2261 << Arg->getSourceRange();
2262 Invalid = true;
2263 }
2264
2265 Arg = Parens->getSubExpr();
2266 }
2267
2268 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2269 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2270 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2271 } else
2272 DRE = dyn_cast<DeclRefExpr>(Arg);
2273
2274 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00002275 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002276 diag::err_template_arg_not_object_or_func_form)
2277 << Arg->getSourceRange();
2278
2279 // Cannot refer to non-static data members
2280 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2281 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2282 << Field << Arg->getSourceRange();
2283
2284 // Cannot refer to non-static member functions
2285 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2286 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00002287 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002288 diag::err_template_arg_method)
2289 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002290
Douglas Gregorccb07762009-02-11 19:52:55 +00002291 // Functions must have external linkage.
2292 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregorf73b2822009-11-25 22:24:25 +00002293 if (Func->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump11289f42009-09-09 15:08:12 +00002294 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002295 diag::err_template_arg_function_not_extern)
2296 << Func << Arg->getSourceRange();
2297 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2298 << true;
2299 return true;
2300 }
2301
2302 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002303 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002304 return Invalid;
2305 }
2306
2307 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregorf73b2822009-11-25 22:24:25 +00002308 if (Var->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump11289f42009-09-09 15:08:12 +00002309 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002310 diag::err_template_arg_object_not_extern)
2311 << Var << Arg->getSourceRange();
2312 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2313 << true;
2314 return true;
2315 }
2316
2317 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002318 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00002319 return Invalid;
2320 }
Mike Stump11289f42009-09-09 15:08:12 +00002321
Douglas Gregorccb07762009-02-11 19:52:55 +00002322 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002323 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002324 diag::err_template_arg_not_object_or_func)
2325 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002326 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002327 diag::note_template_arg_refers_here);
2328 return true;
2329}
2330
2331/// \brief Checks whether the given template argument is a pointer to
2332/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002333bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2334 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002335 bool Invalid = false;
2336
2337 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002338 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002339 Arg = Cast->getSubExpr();
2340
Sebastian Redl576fd422009-05-10 18:38:11 +00002341 // C++0x allows nullptr, and there's no further checking to be done for that.
2342 if (Arg->getType()->isNullPtrType())
2343 return false;
2344
Douglas Gregorccb07762009-02-11 19:52:55 +00002345 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002346 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002347 // A template-argument for a non-type, non-template
2348 // template-parameter shall be one of: [...]
2349 //
2350 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002351 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002352
2353 // Ignore (and complain about) any excess parentheses.
2354 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2355 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002356 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002357 diag::err_template_arg_extra_parens)
2358 << Arg->getSourceRange();
2359 Invalid = true;
2360 }
2361
2362 Arg = Parens->getSubExpr();
2363 }
2364
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002365 // A pointer-to-member constant written &Class::member.
2366 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002367 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2368 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2369 if (DRE && !DRE->getQualifier())
2370 DRE = 0;
2371 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002372 }
2373 // A constant of pointer-to-member type.
2374 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2375 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2376 if (VD->getType()->isMemberPointerType()) {
2377 if (isa<NonTypeTemplateParmDecl>(VD) ||
2378 (isa<VarDecl>(VD) &&
2379 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2380 if (Arg->isTypeDependent() || Arg->isValueDependent())
2381 Converted = TemplateArgument(Arg->Retain());
2382 else
2383 Converted = TemplateArgument(VD->getCanonicalDecl());
2384 return Invalid;
2385 }
2386 }
2387 }
2388
2389 DRE = 0;
2390 }
2391
Douglas Gregorccb07762009-02-11 19:52:55 +00002392 if (!DRE)
2393 return Diag(Arg->getSourceRange().getBegin(),
2394 diag::err_template_arg_not_pointer_to_member_form)
2395 << Arg->getSourceRange();
2396
2397 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2398 assert((isa<FieldDecl>(DRE->getDecl()) ||
2399 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2400 "Only non-static member pointers can make it here");
2401
2402 // Okay: this is the address of a non-static member, and therefore
2403 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002404 if (Arg->isTypeDependent() || Arg->isValueDependent())
2405 Converted = TemplateArgument(Arg->Retain());
2406 else
2407 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002408 return Invalid;
2409 }
2410
2411 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002412 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002413 diag::err_template_arg_not_pointer_to_member_form)
2414 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002415 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002416 diag::note_template_arg_refers_here);
2417 return true;
2418}
2419
Douglas Gregord32e0282009-02-09 23:23:08 +00002420/// \brief Check a template argument against its corresponding
2421/// non-type template parameter.
2422///
Douglas Gregor463421d2009-03-03 04:44:36 +00002423/// This routine implements the semantics of C++ [temp.arg.nontype].
2424/// It returns true if an error occurred, and false otherwise. \p
2425/// InstantiatedParamType is the type of the non-type template
2426/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002427///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002428/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002429bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002430 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002431 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002432 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2433
Douglas Gregor86560402009-02-10 23:36:10 +00002434 // If either the parameter has a dependent type or the argument is
2435 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002436 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00002437 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2438 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002439 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002440 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002441 }
Douglas Gregor86560402009-02-10 23:36:10 +00002442
2443 // C++ [temp.arg.nontype]p5:
2444 // The following conversions are performed on each expression used
2445 // as a non-type template-argument. If a non-type
2446 // template-argument cannot be converted to the type of the
2447 // corresponding template-parameter then the program is
2448 // ill-formed.
2449 //
2450 // -- for a non-type template-parameter of integral or
2451 // enumeration type, integral promotions (4.5) and integral
2452 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002453 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002454 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002455 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002456 // C++ [temp.arg.nontype]p1:
2457 // A template-argument for a non-type, non-template
2458 // template-parameter shall be one of:
2459 //
2460 // -- an integral constant-expression of integral or enumeration
2461 // type; or
2462 // -- the name of a non-type template-parameter; or
2463 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002464 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002465 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002466 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002467 diag::err_template_arg_not_integral_or_enumeral)
2468 << ArgType << Arg->getSourceRange();
2469 Diag(Param->getLocation(), diag::note_template_param_here);
2470 return true;
2471 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002472 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002473 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2474 << ArgType << Arg->getSourceRange();
2475 return true;
2476 }
2477
2478 // FIXME: We need some way to more easily get the unqualified form
2479 // of the types without going all the way to the
2480 // canonical type.
2481 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2482 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2483 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2484 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2485
2486 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002487 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002488 // Okay: no conversion necessary
2489 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2490 !ParamType->isEnumeralType()) {
2491 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002492 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002493 } else {
2494 // We can't perform this conversion.
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_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002497 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002498 Diag(Param->getLocation(), diag::note_template_param_here);
2499 return true;
2500 }
2501
Douglas Gregor52aba872009-03-14 00:20:21 +00002502 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002503 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002504 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002505
2506 if (!Arg->isValueDependent()) {
2507 // Check that an unsigned parameter does not receive a negative
2508 // value.
2509 if (IntegerType->isUnsignedIntegerType()
2510 && (Value.isSigned() && Value.isNegative())) {
2511 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2512 << Value.toString(10) << Param->getType()
2513 << Arg->getSourceRange();
2514 Diag(Param->getLocation(), diag::note_template_param_here);
2515 return true;
2516 }
2517
2518 // Check that we don't overflow the template parameter type.
2519 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Eli Friedman38b9ad82009-12-23 18:44:58 +00002520 unsigned RequiredBits;
2521 if (IntegerType->isUnsignedIntegerType())
2522 RequiredBits = Value.getActiveBits();
2523 else if (Value.isUnsigned())
2524 RequiredBits = Value.getActiveBits() + 1;
2525 else
2526 RequiredBits = Value.getMinSignedBits();
2527 if (RequiredBits > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00002528 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00002529 diag::err_template_arg_too_large)
2530 << Value.toString(10) << Param->getType()
2531 << Arg->getSourceRange();
2532 Diag(Param->getLocation(), diag::note_template_param_here);
2533 return true;
2534 }
2535
2536 if (Value.getBitWidth() != AllowedBits)
2537 Value.extOrTrunc(AllowedBits);
2538 Value.setIsSigned(IntegerType->isSignedIntegerType());
2539 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002540
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002541 // Add the value of this argument to the list of converted
2542 // arguments. We use the bitwidth and signedness of the template
2543 // parameter.
2544 if (Arg->isValueDependent()) {
2545 // The argument is value-dependent. Create a new
2546 // TemplateArgument with the converted expression.
2547 Converted = TemplateArgument(Arg);
2548 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002549 }
2550
John McCall0ad16662009-10-29 08:12:44 +00002551 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002552 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002553 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002554 return false;
2555 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002556
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002557 // Handle pointer-to-function, reference-to-function, and
2558 // pointer-to-member-function all in (roughly) the same way.
2559 if (// -- For a non-type template-parameter of type pointer to
2560 // function, only the function-to-pointer conversion (4.3) is
2561 // applied. If the template-argument represents a set of
2562 // overloaded functions (or a pointer to such), the matching
2563 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002564 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002565 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002566 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002567 // -- For a non-type template-parameter of type reference to
2568 // function, no conversions apply. If the template-argument
2569 // represents a set of overloaded functions, the matching
2570 // function is selected from the set (13.4).
2571 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002572 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002573 // -- For a non-type template-parameter of type pointer to
2574 // member function, no conversions apply. If the
2575 // template-argument represents a set of overloaded member
2576 // functions, the matching member function is selected from
2577 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002578 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002579 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002580 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002581 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002582 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002583 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002584 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002585 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2586 ParamType->isMemberPointerType())) {
2587 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002588 if (ParamType->isMemberPointerType())
2589 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2590 else
2591 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002592 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002593 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002594 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002595 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002596 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002597 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2598 return true;
2599
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002600 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002601 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002602 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002603 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002604 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002605 }
2606 }
2607
Mike Stump11289f42009-09-09 15:08:12 +00002608 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002609 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002610 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002611 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002612 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002613 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002614 Diag(Param->getLocation(), diag::note_template_param_here);
2615 return true;
2616 }
Mike Stump11289f42009-09-09 15:08:12 +00002617
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002618 if (ParamType->isMemberPointerType())
2619 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump11289f42009-09-09 15:08:12 +00002620
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002621 NamedDecl *Entity = 0;
2622 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2623 return true;
2624
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002625 if (Entity)
2626 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002627 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002628 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002629 }
2630
Chris Lattner696197c2009-02-20 21:37:53 +00002631 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002632 // -- for a non-type template-parameter of type pointer to
2633 // object, qualification conversions (4.4) and the
2634 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002635 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002636 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002637 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002638
Sebastian Redl576fd422009-05-10 18:38:11 +00002639 if (ArgType->isNullPtrType()) {
2640 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002641 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002642 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002643 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002644 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002645 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002646
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002647 if (IsQualificationConversion(ArgType, ParamType)) {
2648 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002649 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002650 }
Mike Stump11289f42009-09-09 15:08:12 +00002651
Douglas Gregor1515f762009-02-11 18:22:40 +00002652 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002653 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002654 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002655 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002656 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002657 Diag(Param->getLocation(), diag::note_template_param_here);
2658 return true;
2659 }
Mike Stump11289f42009-09-09 15:08:12 +00002660
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002661 NamedDecl *Entity = 0;
2662 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2663 return true;
2664
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002665 if (Entity)
2666 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002667 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002668 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002669 }
Mike Stump11289f42009-09-09 15:08:12 +00002670
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002671 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002672 // -- For a non-type template-parameter of type reference to
2673 // object, no conversions apply. The type referred to by the
2674 // reference may be more cv-qualified than the (otherwise
2675 // identical) type of the template-argument. The
2676 // template-parameter is bound directly to the
2677 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002678 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002679 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002680
Douglas Gregor1515f762009-02-11 18:22:40 +00002681 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002682 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002683 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002684 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002685 << Arg->getSourceRange();
2686 Diag(Param->getLocation(), diag::note_template_param_here);
2687 return true;
2688 }
2689
Mike Stump11289f42009-09-09 15:08:12 +00002690 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002691 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2692 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002693
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002694 if ((ParamQuals | ArgQuals) != ParamQuals) {
2695 Diag(Arg->getSourceRange().getBegin(),
2696 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002697 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002698 << Arg->getSourceRange();
2699 Diag(Param->getLocation(), diag::note_template_param_here);
2700 return true;
2701 }
Mike Stump11289f42009-09-09 15:08:12 +00002702
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002703 NamedDecl *Entity = 0;
2704 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2705 return true;
2706
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002707 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002708 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002709 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002710 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002711
2712 // -- For a non-type template-parameter of type pointer to data
2713 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002714 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002715 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2716
Douglas Gregor1515f762009-02-11 18:22:40 +00002717 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002718 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002719 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002720 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002721 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002722 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002723 } else {
2724 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002725 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002726 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002727 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002728 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002729 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002730 }
2731
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002732 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002733}
2734
2735/// \brief Check a template argument against its corresponding
2736/// template template parameter.
2737///
2738/// This routine implements the semantics of C++ [temp.arg.template].
2739/// It returns true if an error occurred, and false otherwise.
2740bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002741 const TemplateArgumentLoc &Arg) {
2742 TemplateName Name = Arg.getArgument().getAsTemplate();
2743 TemplateDecl *Template = Name.getAsTemplateDecl();
2744 if (!Template) {
2745 // Any dependent template name is fine.
2746 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2747 return false;
2748 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002749
2750 // C++ [temp.arg.template]p1:
2751 // A template-argument for a template template-parameter shall be
2752 // the name of a class template, expressed as id-expression. Only
2753 // primary class templates are considered when matching the
2754 // template template argument with the corresponding parameter;
2755 // partial specializations are not considered even if their
2756 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002757 //
2758 // Note that we also allow template template parameters here, which
2759 // will happen when we are dealing with, e.g., class template
2760 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002761 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002762 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002763 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002764 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002765 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002766 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002767 << Template;
2768 }
2769
2770 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2771 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002772 true,
2773 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002774 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002775}
2776
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002777/// \brief Determine whether the given template parameter lists are
2778/// equivalent.
2779///
Mike Stump11289f42009-09-09 15:08:12 +00002780/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002781/// source code as part of a new template declaration.
2782///
2783/// \param Old The old template parameter list, typically found via
2784/// name lookup of the template declared with this template parameter
2785/// list.
2786///
2787/// \param Complain If true, this routine will produce a diagnostic if
2788/// the template parameter lists are not equivalent.
2789///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002790/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00002791///
2792/// \param TemplateArgLoc If this source location is valid, then we
2793/// are actually checking the template parameter list of a template
2794/// argument (New) against the template parameter list of its
2795/// corresponding template template parameter (Old). We produce
2796/// slightly different diagnostics in this scenario.
2797///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002798/// \returns True if the template parameter lists are equal, false
2799/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002800bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002801Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2802 TemplateParameterList *Old,
2803 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002804 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002805 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002806 if (Old->size() != New->size()) {
2807 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002808 unsigned NextDiag = diag::err_template_param_list_different_arity;
2809 if (TemplateArgLoc.isValid()) {
2810 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2811 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002812 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002813 Diag(New->getTemplateLoc(), NextDiag)
2814 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002815 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002816 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002817 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002818 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002819 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2820 }
2821
2822 return false;
2823 }
2824
2825 for (TemplateParameterList::iterator OldParm = Old->begin(),
2826 OldParmEnd = Old->end(), NewParm = New->begin();
2827 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2828 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002829 if (Complain) {
2830 unsigned NextDiag = diag::err_template_param_different_kind;
2831 if (TemplateArgLoc.isValid()) {
2832 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2833 NextDiag = diag::note_template_param_different_kind;
2834 }
2835 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002836 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00002837 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002838 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00002839 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002840 return false;
2841 }
2842
2843 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2844 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002845 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00002846 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002847 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2848 // The types of non-type template parameters must agree.
2849 NonTypeTemplateParmDecl *NewNTTP
2850 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002851
2852 // If we are matching a template template argument to a template
2853 // template parameter and one of the non-type template parameter types
2854 // is dependent, then we must wait until template instantiation time
2855 // to actually compare the arguments.
2856 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2857 (OldNTTP->getType()->isDependentType() ||
2858 NewNTTP->getType()->isDependentType()))
2859 continue;
2860
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002861 if (Context.getCanonicalType(OldNTTP->getType()) !=
2862 Context.getCanonicalType(NewNTTP->getType())) {
2863 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002864 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2865 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002866 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002867 diag::err_template_arg_template_params_mismatch);
2868 NextDiag = diag::note_template_nontype_parm_different_type;
2869 }
2870 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002871 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002872 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00002873 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002874 diag::note_template_nontype_parm_prev_declaration)
2875 << OldNTTP->getType();
2876 }
2877 return false;
2878 }
2879 } else {
2880 // The template parameter lists of template template
2881 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00002882 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002883 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002884 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002885 = cast<TemplateTemplateParmDecl>(*OldParm);
2886 TemplateTemplateParmDecl *NewTTP
2887 = cast<TemplateTemplateParmDecl>(*NewParm);
2888 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2889 OldTTP->getTemplateParameters(),
2890 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002891 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00002892 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002893 return false;
2894 }
2895 }
2896
2897 return true;
2898}
2899
2900/// \brief Check whether a template can be declared within this scope.
2901///
2902/// If the template declaration is valid in this scope, returns
2903/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002904bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002905Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002906 // Find the nearest enclosing declaration scope.
2907 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2908 (S->getFlags() & Scope::TemplateParamScope) != 0)
2909 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002910
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002911 // C++ [temp]p2:
2912 // A template-declaration can appear only as a namespace scope or
2913 // class scope declaration.
2914 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002915 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2916 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002917 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002918 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002919
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002920 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002921 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002922
2923 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2924 return false;
2925
Mike Stump11289f42009-09-09 15:08:12 +00002926 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002927 diag::err_template_outside_namespace_or_class_scope)
2928 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002929}
Douglas Gregor67a65642009-02-17 23:15:12 +00002930
Douglas Gregor54888652009-10-07 00:13:32 +00002931/// \brief Determine what kind of template specialization the given declaration
2932/// is.
2933static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2934 if (!D)
2935 return TSK_Undeclared;
2936
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002937 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2938 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00002939 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2940 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002941 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2942 return Var->getTemplateSpecializationKind();
2943
Douglas Gregor54888652009-10-07 00:13:32 +00002944 return TSK_Undeclared;
2945}
2946
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002947/// \brief Check whether a specialization is well-formed in the current
2948/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002949///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002950/// This routine determines whether a template specialization can be declared
2951/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00002952///
2953/// \param S the semantic analysis object for which this check is being
2954/// performed.
2955///
2956/// \param Specialized the entity being specialized or instantiated, which
2957/// may be a kind of template (class template, function template, etc.) or
2958/// a member of a class template (member function, static data member,
2959/// member class).
2960///
2961/// \param PrevDecl the previous declaration of this entity, if any.
2962///
2963/// \param Loc the location of the explicit specialization or instantiation of
2964/// this entity.
2965///
2966/// \param IsPartialSpecialization whether this is a partial specialization of
2967/// a class template.
2968///
Douglas Gregor54888652009-10-07 00:13:32 +00002969/// \returns true if there was an error that we cannot recover from, false
2970/// otherwise.
2971static bool CheckTemplateSpecializationScope(Sema &S,
2972 NamedDecl *Specialized,
2973 NamedDecl *PrevDecl,
2974 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002975 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00002976 // Keep these "kind" numbers in sync with the %select statements in the
2977 // various diagnostics emitted by this routine.
2978 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002979 bool isTemplateSpecialization = false;
2980 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002981 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002982 isTemplateSpecialization = true;
2983 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002984 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002985 isTemplateSpecialization = true;
2986 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00002987 EntityKind = 3;
2988 else if (isa<VarDecl>(Specialized))
2989 EntityKind = 4;
2990 else if (isa<RecordDecl>(Specialized))
2991 EntityKind = 5;
2992 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002993 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2994 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00002995 return true;
2996 }
2997
Douglas Gregorf47b9112009-02-25 22:02:03 +00002998 // C++ [temp.expl.spec]p2:
2999 // An explicit specialization shall be declared in the namespace
3000 // of which the template is a member, or, for member templates, in
3001 // the namespace of which the enclosing class or enclosing class
3002 // template is a member. An explicit specialization of a member
3003 // function, member class or static data member of a class
3004 // template shall be declared in the namespace of which the class
3005 // template is a member. Such a declaration may also be a
3006 // definition. If the declaration is not a definition, the
3007 // specialization may be defined later in the name- space in which
3008 // the explicit specialization was declared, or in a namespace
3009 // that encloses the one in which the explicit specialization was
3010 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003011 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3012 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003013 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003014 return true;
3015 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003016
Douglas Gregor40fb7442009-10-07 17:30:37 +00003017 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3018 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003019 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003020 return true;
3021 }
3022
Douglas Gregore4b05162009-10-07 17:21:34 +00003023 // C++ [temp.class.spec]p6:
3024 // A class template partial specialization may be declared or redeclared
3025 // in any namespace scope in which its definition may be defined (14.5.1
3026 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003027 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003028 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003029 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003030 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003031 if ((!PrevDecl ||
3032 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3033 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3034 // There is no prior declaration of this entity, so this
3035 // specialization must be in the same context as the template
3036 // itself.
3037 if (!DC->Equals(SpecializedContext)) {
3038 if (isa<TranslationUnitDecl>(SpecializedContext))
3039 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3040 << EntityKind << Specialized;
3041 else if (isa<NamespaceDecl>(SpecializedContext))
3042 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3043 << EntityKind << Specialized
3044 << cast<NamedDecl>(SpecializedContext);
3045
3046 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3047 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003048 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003049 }
Douglas Gregor54888652009-10-07 00:13:32 +00003050
3051 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003052 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003053 // Note that HandleDeclarator() performs this check for explicit
3054 // specializations of function templates, static data members, and member
3055 // functions, so we skip the check here for those kinds of entities.
3056 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003057 // Should we refactor that check, so that it occurs later?
3058 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003059 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3060 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003061 if (isa<TranslationUnitDecl>(SpecializedContext))
3062 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3063 << EntityKind << Specialized;
3064 else if (isa<NamespaceDecl>(SpecializedContext))
3065 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3066 << EntityKind << Specialized
3067 << cast<NamedDecl>(SpecializedContext);
3068
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003069 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003070 }
Douglas Gregor54888652009-10-07 00:13:32 +00003071
3072 // FIXME: check for specialization-after-instantiation errors and such.
3073
Douglas Gregorf47b9112009-02-25 22:02:03 +00003074 return false;
3075}
Douglas Gregor54888652009-10-07 00:13:32 +00003076
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003077/// \brief Check the non-type template arguments of a class template
3078/// partial specialization according to C++ [temp.class.spec]p9.
3079///
Douglas Gregor09a30232009-06-12 22:08:06 +00003080/// \param TemplateParams the template parameters of the primary class
3081/// template.
3082///
3083/// \param TemplateArg the template arguments of the class template
3084/// partial specialization.
3085///
3086/// \param MirrorsPrimaryTemplate will be set true if the class
3087/// template partial specialization arguments are identical to the
3088/// implicit template arguments of the primary template. This is not
3089/// necessarily an error (C++0x), and it is left to the caller to diagnose
3090/// this condition when it is an error.
3091///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003092/// \returns true if there was an error, false otherwise.
3093bool Sema::CheckClassTemplatePartialSpecializationArgs(
3094 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003095 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003096 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003097 // FIXME: the interface to this function will have to change to
3098 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003099 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003100
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003101 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003102
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003103 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003104 // Determine whether the template argument list of the partial
3105 // specialization is identical to the implicit argument list of
3106 // the primary template. The caller may need to diagnostic this as
3107 // an error per C++ [temp.class.spec]p9b3.
3108 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003109 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003110 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3111 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003112 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003113 MirrorsPrimaryTemplate = false;
3114 } else if (TemplateTemplateParmDecl *TTP
3115 = dyn_cast<TemplateTemplateParmDecl>(
3116 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003117 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003118 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003119 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003120 if (!ArgDecl ||
3121 ArgDecl->getIndex() != TTP->getIndex() ||
3122 ArgDecl->getDepth() != TTP->getDepth())
3123 MirrorsPrimaryTemplate = false;
3124 }
3125 }
3126
Mike Stump11289f42009-09-09 15:08:12 +00003127 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003128 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003129 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003130 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003131 }
3132
Anders Carlsson40c1d492009-06-13 18:20:51 +00003133 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003134 if (!ArgExpr) {
3135 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003136 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003137 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003138
3139 // C++ [temp.class.spec]p8:
3140 // A non-type argument is non-specialized if it is the name of a
3141 // non-type parameter. All other non-type arguments are
3142 // specialized.
3143 //
3144 // Below, we check the two conditions that only apply to
3145 // specialized non-type arguments, so skip any non-specialized
3146 // arguments.
3147 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003148 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003149 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003150 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003151 (Param->getIndex() != NTTP->getIndex() ||
3152 Param->getDepth() != NTTP->getDepth()))
3153 MirrorsPrimaryTemplate = false;
3154
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003155 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003156 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003157
3158 // C++ [temp.class.spec]p9:
3159 // Within the argument list of a class template partial
3160 // specialization, the following restrictions apply:
3161 // -- A partially specialized non-type argument expression
3162 // shall not involve a template parameter of the partial
3163 // specialization except when the argument expression is a
3164 // simple identifier.
3165 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003166 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003167 diag::err_dependent_non_type_arg_in_partial_spec)
3168 << ArgExpr->getSourceRange();
3169 return true;
3170 }
3171
3172 // -- The type of a template parameter corresponding to a
3173 // specialized non-type argument shall not be dependent on a
3174 // parameter of the specialization.
3175 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003176 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003177 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3178 << Param->getType()
3179 << ArgExpr->getSourceRange();
3180 Diag(Param->getLocation(), diag::note_template_param_here);
3181 return true;
3182 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003183
3184 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003185 }
3186
3187 return false;
3188}
3189
Douglas Gregorc08f4892009-03-25 00:13:59 +00003190Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003191Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3192 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003193 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00003194 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003195 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003196 SourceLocation TemplateNameLoc,
3197 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003198 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003199 SourceLocation RAngleLoc,
3200 AttributeList *Attr,
3201 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003202 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003203
Douglas Gregor67a65642009-02-17 23:15:12 +00003204 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003205 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003206 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003207 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3208
3209 if (!ClassTemplate) {
3210 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3211 << (Name.getAsTemplateDecl() &&
3212 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3213 return true;
3214 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003215
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003216 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003217 bool isPartialSpecialization = false;
3218
Douglas Gregorf47b9112009-02-25 22:02:03 +00003219 // Check the validity of the template headers that introduce this
3220 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003221 // FIXME: We probably shouldn't complain about these headers for
3222 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003223 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003224 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3225 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003226 TemplateParameterLists.size(),
3227 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003228 if (TemplateParams && TemplateParams->size() > 0) {
3229 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003230
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003231 // C++ [temp.class.spec]p10:
3232 // The template parameter list of a specialization shall not
3233 // contain default template argument values.
3234 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3235 Decl *Param = TemplateParams->getParam(I);
3236 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3237 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003238 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003239 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003240 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003241 }
3242 } else if (NonTypeTemplateParmDecl *NTTP
3243 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3244 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003245 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003246 diag::err_default_arg_in_partial_spec)
3247 << DefArg->getSourceRange();
3248 NTTP->setDefaultArgument(0);
3249 DefArg->Destroy(Context);
3250 }
3251 } else {
3252 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003253 if (TTP->hasDefaultArgument()) {
3254 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003255 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003256 << TTP->getDefaultArgument().getSourceRange();
3257 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003258 }
3259 }
3260 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003261 } else if (TemplateParams) {
3262 if (TUK == TUK_Friend)
3263 Diag(KWLoc, diag::err_template_spec_friend)
3264 << CodeModificationHint::CreateRemoval(
3265 SourceRange(TemplateParams->getTemplateLoc(),
3266 TemplateParams->getRAngleLoc()))
3267 << SourceRange(LAngleLoc, RAngleLoc);
3268 else
3269 isExplicitSpecialization = true;
3270 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003271 Diag(KWLoc, diag::err_template_spec_needs_header)
3272 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003273 isExplicitSpecialization = true;
3274 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003275
Douglas Gregor67a65642009-02-17 23:15:12 +00003276 // Check that the specialization uses the same tag kind as the
3277 // original template.
3278 TagDecl::TagKind Kind;
3279 switch (TagSpec) {
3280 default: assert(0 && "Unknown tag type!");
3281 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3282 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3283 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3284 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003285 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003286 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003287 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003288 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003289 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003290 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003291 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003292 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003293 diag::note_previous_use);
3294 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3295 }
3296
Douglas Gregorc40290e2009-03-09 23:48:35 +00003297 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003298 TemplateArgumentListInfo TemplateArgs;
3299 TemplateArgs.setLAngleLoc(LAngleLoc);
3300 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003301 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003302
Douglas Gregor67a65642009-02-17 23:15:12 +00003303 // Check that the template argument list is well-formed for this
3304 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003305 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3306 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003307 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3308 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003309 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003310
Mike Stump11289f42009-09-09 15:08:12 +00003311 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003312 ClassTemplate->getTemplateParameters()->size()) &&
3313 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003314
Douglas Gregor2373c592009-05-31 09:31:02 +00003315 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003316 // corresponds to these arguments.
3317 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003318 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003319 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003320 if (CheckClassTemplatePartialSpecializationArgs(
3321 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003322 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003323 return true;
3324
Douglas Gregor09a30232009-06-12 22:08:06 +00003325 if (MirrorsPrimaryTemplate) {
3326 // C++ [temp.class.spec]p9b3:
3327 //
Mike Stump11289f42009-09-09 15:08:12 +00003328 // -- The argument list of the specialization shall not be identical
3329 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003330 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003331 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00003332 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00003333 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003334 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003335 ClassTemplate->getIdentifier(),
3336 TemplateNameLoc,
3337 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003338 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003339 AS_none);
3340 }
3341
Douglas Gregor2208a292009-09-26 20:57:03 +00003342 // FIXME: Diagnose friend partial specializations
3343
Douglas Gregor2373c592009-05-31 09:31:02 +00003344 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00003345 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003346 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003347 Converted.flatSize(),
3348 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003349 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003350 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003351 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003352 Converted.flatSize(),
3353 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003354 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003355 ClassTemplateSpecializationDecl *PrevDecl = 0;
3356
3357 if (isPartialSpecialization)
3358 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003359 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003360 InsertPos);
3361 else
3362 PrevDecl
3363 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003364
3365 ClassTemplateSpecializationDecl *Specialization = 0;
3366
Douglas Gregorf47b9112009-02-25 22:02:03 +00003367 // Check whether we can declare a class template specialization in
3368 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003369 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003370 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003371 TemplateNameLoc,
3372 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003373 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003374
Douglas Gregor15301382009-07-30 17:40:51 +00003375 // The canonical type
3376 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003377 if (PrevDecl &&
3378 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3379 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003380 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003381 // arguments was referenced but not declared, or we're only
3382 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003383 // declaration node as our own, updating its source location to
3384 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003385 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003386 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003387 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003388 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003389 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003390 // Build the canonical type that describes the converted template
3391 // arguments of the class template partial specialization.
3392 CanonType = Context.getTemplateSpecializationType(
3393 TemplateName(ClassTemplate),
3394 Converted.getFlatArguments(),
3395 Converted.flatSize());
3396
Douglas Gregor2373c592009-05-31 09:31:02 +00003397 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003398 ClassTemplatePartialSpecializationDecl *PrevPartial
3399 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003400 ClassTemplatePartialSpecializationDecl *Partial
3401 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003402 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003403 TemplateNameLoc,
3404 TemplateParams,
3405 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003406 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003407 TemplateArgs,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003408 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00003409
3410 if (PrevPartial) {
3411 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3412 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3413 } else {
3414 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3415 }
3416 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003417
Douglas Gregor21610382009-10-29 00:04:11 +00003418 // If we are providing an explicit specialization of a member class
3419 // template specialization, make a note of that.
3420 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3421 PrevPartial->setMemberSpecialization();
3422
Douglas Gregor91772d12009-06-13 00:26:55 +00003423 // Check that all of the template parameters of the class template
3424 // partial specialization are deducible from the template
3425 // arguments. If not, this class template partial specialization
3426 // will never be used.
3427 llvm::SmallVector<bool, 8> DeducibleParams;
3428 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003429 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003430 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003431 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003432 unsigned NumNonDeducible = 0;
3433 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3434 if (!DeducibleParams[I])
3435 ++NumNonDeducible;
3436
3437 if (NumNonDeducible) {
3438 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3439 << (NumNonDeducible > 1)
3440 << SourceRange(TemplateNameLoc, RAngleLoc);
3441 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3442 if (!DeducibleParams[I]) {
3443 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3444 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003445 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003446 diag::note_partial_spec_unused_parameter)
3447 << Param->getDeclName();
3448 else
Mike Stump11289f42009-09-09 15:08:12 +00003449 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003450 diag::note_partial_spec_unused_parameter)
3451 << std::string("<anonymous>");
3452 }
3453 }
3454 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003455 } else {
3456 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003457 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003458 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003459 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003460 ClassTemplate->getDeclContext(),
3461 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003462 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003463 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003464 PrevDecl);
3465
3466 if (PrevDecl) {
3467 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3468 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3469 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003470 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003471 InsertPos);
3472 }
Douglas Gregor15301382009-07-30 17:40:51 +00003473
3474 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003475 }
3476
Douglas Gregor06db9f52009-10-12 20:18:28 +00003477 // C++ [temp.expl.spec]p6:
3478 // If a template, a member template or the member of a class template is
3479 // explicitly specialized then that specialization shall be declared
3480 // before the first use of that specialization that would cause an implicit
3481 // instantiation to take place, in every translation unit in which such a
3482 // use occurs; no diagnostic is required.
3483 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3484 SourceRange Range(TemplateNameLoc, RAngleLoc);
3485 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3486 << Context.getTypeDeclType(Specialization) << Range;
3487
3488 Diag(PrevDecl->getPointOfInstantiation(),
3489 diag::note_instantiation_required_here)
3490 << (PrevDecl->getTemplateSpecializationKind()
3491 != TSK_ImplicitInstantiation);
3492 return true;
3493 }
3494
Douglas Gregor2208a292009-09-26 20:57:03 +00003495 // If this is not a friend, note that this is an explicit specialization.
3496 if (TUK != TUK_Friend)
3497 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003498
3499 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003500 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003501 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003502 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003503 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003504 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003505 Diag(Def->getLocation(), diag::note_previous_definition);
3506 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003507 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003508 }
3509 }
3510
Douglas Gregord56a91e2009-02-26 22:19:44 +00003511 // Build the fully-sugared type for this class template
3512 // specialization as the user wrote in the specialization
3513 // itself. This means that we'll pretty-print the type retrieved
3514 // from the specialization's declaration the way that the user
3515 // actually wrote the specialization, rather than formatting the
3516 // name based on the "canonical" representation used to store the
3517 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003518 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00003519 = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003520 if (TUK != TUK_Friend)
3521 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003522 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003523
Douglas Gregor1e249f82009-02-25 22:18:32 +00003524 // C++ [temp.expl.spec]p9:
3525 // A template explicit specialization is in the scope of the
3526 // namespace in which the template was defined.
3527 //
3528 // We actually implement this paragraph where we set the semantic
3529 // context (in the creation of the ClassTemplateSpecializationDecl),
3530 // but we also maintain the lexical context where the actual
3531 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003532 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003533
Douglas Gregor67a65642009-02-17 23:15:12 +00003534 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003535 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003536 Specialization->startDefinition();
3537
Douglas Gregor2208a292009-09-26 20:57:03 +00003538 if (TUK == TUK_Friend) {
3539 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3540 TemplateNameLoc,
3541 WrittenTy.getTypePtr(),
3542 /*FIXME:*/KWLoc);
3543 Friend->setAccess(AS_public);
3544 CurContext->addDecl(Friend);
3545 } else {
3546 // Add the specialization into its lexical context, so that it can
3547 // be seen when iterating through the list of declarations in that
3548 // context. However, specializations are not found by name lookup.
3549 CurContext->addDecl(Specialization);
3550 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003551 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003552}
Douglas Gregor333489b2009-03-27 23:10:48 +00003553
Mike Stump11289f42009-09-09 15:08:12 +00003554Sema::DeclPtrTy
3555Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003556 MultiTemplateParamsArg TemplateParameterLists,
3557 Declarator &D) {
3558 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3559}
3560
Mike Stump11289f42009-09-09 15:08:12 +00003561Sema::DeclPtrTy
3562Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003563 MultiTemplateParamsArg TemplateParameterLists,
3564 Declarator &D) {
3565 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3566 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3567 "Not a function declarator!");
3568 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003569
Douglas Gregor17a7c122009-06-24 00:54:41 +00003570 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003571 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003572 }
Mike Stump11289f42009-09-09 15:08:12 +00003573
Douglas Gregor17a7c122009-06-24 00:54:41 +00003574 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003575
3576 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003577 move(TemplateParameterLists),
3578 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003579 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003580 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003581 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003582 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003583 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3584 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003585 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003586}
3587
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003588/// \brief Diagnose cases where we have an explicit template specialization
3589/// before/after an explicit template instantiation, producing diagnostics
3590/// for those cases where they are required and determining whether the
3591/// new specialization/instantiation will have any effect.
3592///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003593/// \param NewLoc the location of the new explicit specialization or
3594/// instantiation.
3595///
3596/// \param NewTSK the kind of the new explicit specialization or instantiation.
3597///
3598/// \param PrevDecl the previous declaration of the entity.
3599///
3600/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3601///
3602/// \param PrevPointOfInstantiation if valid, indicates where the previus
3603/// declaration was instantiated (either implicitly or explicitly).
3604///
3605/// \param SuppressNew will be set to true to indicate that the new
3606/// specialization or instantiation has no effect and should be ignored.
3607///
3608/// \returns true if there was an error that should prevent the introduction of
3609/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003610bool
3611Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3612 TemplateSpecializationKind NewTSK,
3613 NamedDecl *PrevDecl,
3614 TemplateSpecializationKind PrevTSK,
3615 SourceLocation PrevPointOfInstantiation,
3616 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003617 SuppressNew = false;
3618
3619 switch (NewTSK) {
3620 case TSK_Undeclared:
3621 case TSK_ImplicitInstantiation:
3622 assert(false && "Don't check implicit instantiations here");
3623 return false;
3624
3625 case TSK_ExplicitSpecialization:
3626 switch (PrevTSK) {
3627 case TSK_Undeclared:
3628 case TSK_ExplicitSpecialization:
3629 // Okay, we're just specializing something that is either already
3630 // explicitly specialized or has merely been mentioned without any
3631 // instantiation.
3632 return false;
3633
3634 case TSK_ImplicitInstantiation:
3635 if (PrevPointOfInstantiation.isInvalid()) {
3636 // The declaration itself has not actually been instantiated, so it is
3637 // still okay to specialize it.
3638 return false;
3639 }
3640 // Fall through
3641
3642 case TSK_ExplicitInstantiationDeclaration:
3643 case TSK_ExplicitInstantiationDefinition:
3644 assert((PrevTSK == TSK_ImplicitInstantiation ||
3645 PrevPointOfInstantiation.isValid()) &&
3646 "Explicit instantiation without point of instantiation?");
3647
3648 // C++ [temp.expl.spec]p6:
3649 // If a template, a member template or the member of a class template
3650 // is explicitly specialized then that specialization shall be declared
3651 // before the first use of that specialization that would cause an
3652 // implicit instantiation to take place, in every translation unit in
3653 // which such a use occurs; no diagnostic is required.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003654 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003655 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003656 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003657 << (PrevTSK != TSK_ImplicitInstantiation);
3658
3659 return true;
3660 }
3661 break;
3662
3663 case TSK_ExplicitInstantiationDeclaration:
3664 switch (PrevTSK) {
3665 case TSK_ExplicitInstantiationDeclaration:
3666 // This explicit instantiation declaration is redundant (that's okay).
3667 SuppressNew = true;
3668 return false;
3669
3670 case TSK_Undeclared:
3671 case TSK_ImplicitInstantiation:
3672 // We're explicitly instantiating something that may have already been
3673 // implicitly instantiated; that's fine.
3674 return false;
3675
3676 case TSK_ExplicitSpecialization:
3677 // C++0x [temp.explicit]p4:
3678 // For a given set of template parameters, if an explicit instantiation
3679 // of a template appears after a declaration of an explicit
3680 // specialization for that template, the explicit instantiation has no
3681 // effect.
3682 return false;
3683
3684 case TSK_ExplicitInstantiationDefinition:
3685 // C++0x [temp.explicit]p10:
3686 // If an entity is the subject of both an explicit instantiation
3687 // declaration and an explicit instantiation definition in the same
3688 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003689 Diag(NewLoc,
3690 diag::err_explicit_instantiation_declaration_after_definition);
3691 Diag(PrevPointOfInstantiation,
3692 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003693 assert(PrevPointOfInstantiation.isValid() &&
3694 "Explicit instantiation without point of instantiation?");
3695 SuppressNew = true;
3696 return false;
3697 }
3698 break;
3699
3700 case TSK_ExplicitInstantiationDefinition:
3701 switch (PrevTSK) {
3702 case TSK_Undeclared:
3703 case TSK_ImplicitInstantiation:
3704 // We're explicitly instantiating something that may have already been
3705 // implicitly instantiated; that's fine.
3706 return false;
3707
3708 case TSK_ExplicitSpecialization:
3709 // C++ DR 259, C++0x [temp.explicit]p4:
3710 // For a given set of template parameters, if an explicit
3711 // instantiation of a template appears after a declaration of
3712 // an explicit specialization for that template, the explicit
3713 // instantiation has no effect.
3714 //
3715 // In C++98/03 mode, we only give an extension warning here, because it
3716 // is not not harmful to try to explicitly instantiate something that
3717 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003718 if (!getLangOptions().CPlusPlus0x) {
3719 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003720 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003721 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003722 diag::note_previous_template_specialization);
3723 }
3724 SuppressNew = true;
3725 return false;
3726
3727 case TSK_ExplicitInstantiationDeclaration:
3728 // We're explicity instantiating a definition for something for which we
3729 // were previously asked to suppress instantiations. That's fine.
3730 return false;
3731
3732 case TSK_ExplicitInstantiationDefinition:
3733 // C++0x [temp.spec]p5:
3734 // For a given template and a given set of template-arguments,
3735 // - an explicit instantiation definition shall appear at most once
3736 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003737 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003738 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003739 Diag(PrevPointOfInstantiation,
3740 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003741 SuppressNew = true;
3742 return false;
3743 }
3744 break;
3745 }
3746
3747 assert(false && "Missing specialization/instantiation case?");
3748
3749 return false;
3750}
3751
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003752/// \brief Perform semantic analysis for the given function template
3753/// specialization.
3754///
3755/// This routine performs all of the semantic analysis required for an
3756/// explicit function template specialization. On successful completion,
3757/// the function declaration \p FD will become a function template
3758/// specialization.
3759///
3760/// \param FD the function declaration, which will be updated to become a
3761/// function template specialization.
3762///
3763/// \param HasExplicitTemplateArgs whether any template arguments were
3764/// explicitly provided.
3765///
3766/// \param LAngleLoc the location of the left angle bracket ('<'), if
3767/// template arguments were explicitly provided.
3768///
3769/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3770/// if any.
3771///
3772/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3773/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3774/// true as in, e.g., \c void sort<>(char*, char*);
3775///
3776/// \param RAngleLoc the location of the right angle bracket ('>'), if
3777/// template arguments were explicitly provided.
3778///
3779/// \param PrevDecl the set of declarations that
3780bool
3781Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00003782 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00003783 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003784 // The set of function template specializations that could match this
3785 // explicit function template specialization.
3786 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3787 CandidateSet Candidates;
3788
3789 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00003790 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3791 I != E; ++I) {
3792 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3793 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003794 // Only consider templates found within the same semantic lookup scope as
3795 // FD.
3796 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3797 continue;
3798
3799 // C++ [temp.expl.spec]p11:
3800 // A trailing template-argument can be left unspecified in the
3801 // template-id naming an explicit function template specialization
3802 // provided it can be deduced from the function argument type.
3803 // Perform template argument deduction to determine whether we may be
3804 // specializing this template.
3805 // FIXME: It is somewhat wasteful to build
3806 TemplateDeductionInfo Info(Context);
3807 FunctionDecl *Specialization = 0;
3808 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00003809 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003810 FD->getType(),
3811 Specialization,
3812 Info)) {
3813 // FIXME: Template argument deduction failed; record why it failed, so
3814 // that we can provide nifty diagnostics.
3815 (void)TDK;
3816 continue;
3817 }
3818
3819 // Record this candidate.
3820 Candidates.push_back(Specialization);
3821 }
3822 }
3823
Douglas Gregor5de279c2009-09-26 03:41:46 +00003824 // Find the most specialized function template.
3825 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3826 Candidates.size(),
3827 TPOC_Other,
3828 FD->getLocation(),
3829 PartialDiagnostic(diag::err_function_template_spec_no_match)
3830 << FD->getDeclName(),
3831 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00003832 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor5de279c2009-09-26 03:41:46 +00003833 PartialDiagnostic(diag::note_function_template_spec_matched));
3834 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003835 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003836
3837 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003838 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003839
Douglas Gregor54888652009-10-07 00:13:32 +00003840 // Check the scope of this explicit specialization.
3841 if (CheckTemplateSpecializationScope(*this,
3842 Specialization->getPrimaryTemplate(),
3843 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003844 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003845 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003846
3847 // C++ [temp.expl.spec]p6:
3848 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003849 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003850 // before the first use of that specialization that would cause an implicit
3851 // instantiation to take place, in every translation unit in which such a
3852 // use occurs; no diagnostic is required.
3853 FunctionTemplateSpecializationInfo *SpecInfo
3854 = Specialization->getTemplateSpecializationInfo();
3855 assert(SpecInfo && "Function template specialization info missing?");
3856 if (SpecInfo->getPointOfInstantiation().isValid()) {
3857 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3858 << FD;
3859 Diag(SpecInfo->getPointOfInstantiation(),
3860 diag::note_instantiation_required_here)
3861 << (Specialization->getTemplateSpecializationKind()
3862 != TSK_ImplicitInstantiation);
3863 return true;
3864 }
Douglas Gregor54888652009-10-07 00:13:32 +00003865
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003866 // Mark the prior declaration as an explicit specialization, so that later
3867 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003868 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003869
3870 // Turn the given function declaration into a function template
3871 // specialization, with the template arguments from the previous
3872 // specialization.
3873 FD->setFunctionTemplateSpecialization(Context,
3874 Specialization->getPrimaryTemplate(),
3875 new (Context) TemplateArgumentList(
3876 *Specialization->getTemplateSpecializationArgs()),
3877 /*InsertPos=*/0,
3878 TSK_ExplicitSpecialization);
3879
3880 // The "previous declaration" for this function template specialization is
3881 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00003882 Previous.clear();
3883 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003884 return false;
3885}
3886
Douglas Gregor86d142a2009-10-08 07:24:58 +00003887/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003888/// specialization.
3889///
3890/// This routine performs all of the semantic analysis required for an
3891/// explicit member function specialization. On successful completion,
3892/// the function declaration \p FD will become a member function
3893/// specialization.
3894///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003895/// \param Member the member declaration, which will be updated to become a
3896/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003897///
John McCall1f82f242009-11-18 22:49:29 +00003898/// \param Previous the set of declarations, one of which may be specialized
3899/// by this function specialization; the set will be modified to contain the
3900/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003901bool
John McCall1f82f242009-11-18 22:49:29 +00003902Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003903 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3904
3905 // Try to find the member we are instantiating.
3906 NamedDecl *Instantiation = 0;
3907 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003908 MemberSpecializationInfo *MSInfo = 0;
3909
John McCall1f82f242009-11-18 22:49:29 +00003910 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003911 // Nowhere to look anyway.
3912 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003913 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3914 I != E; ++I) {
3915 NamedDecl *D = (*I)->getUnderlyingDecl();
3916 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003917 if (Context.hasSameType(Function->getType(), Method->getType())) {
3918 Instantiation = Method;
3919 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003920 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003921 break;
3922 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003923 }
3924 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003925 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003926 VarDecl *PrevVar;
3927 if (Previous.isSingleResult() &&
3928 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00003929 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00003930 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003931 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003932 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003933 }
3934 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003935 CXXRecordDecl *PrevRecord;
3936 if (Previous.isSingleResult() &&
3937 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
3938 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003939 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003940 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003941 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003942 }
3943
3944 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003945 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003946 // specializations are always out-of-line, the caller will complain about
3947 // this mismatch later.
3948 return false;
3949 }
3950
Douglas Gregor86d142a2009-10-08 07:24:58 +00003951 // Make sure that this is a specialization of a member.
3952 if (!InstantiatedFrom) {
3953 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3954 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003955 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3956 return true;
3957 }
3958
Douglas Gregor06db9f52009-10-12 20:18:28 +00003959 // C++ [temp.expl.spec]p6:
3960 // If a template, a member template or the member of a class template is
3961 // explicitly specialized then that spe- cialization shall be declared
3962 // before the first use of that specialization that would cause an implicit
3963 // instantiation to take place, in every translation unit in which such a
3964 // use occurs; no diagnostic is required.
3965 assert(MSInfo && "Member specialization info missing?");
3966 if (MSInfo->getPointOfInstantiation().isValid()) {
3967 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3968 << Member;
3969 Diag(MSInfo->getPointOfInstantiation(),
3970 diag::note_instantiation_required_here)
3971 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3972 return true;
3973 }
3974
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003975 // Check the scope of this explicit specialization.
3976 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00003977 InstantiatedFrom,
3978 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003979 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003980 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00003981
Douglas Gregor86d142a2009-10-08 07:24:58 +00003982 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003983 // the original declaration to note that it is an explicit specialization
3984 // (if it was previously an implicit instantiation). This latter step
3985 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00003986 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003987 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3988 if (InstantiationFunction->getTemplateSpecializationKind() ==
3989 TSK_ImplicitInstantiation) {
3990 InstantiationFunction->setTemplateSpecializationKind(
3991 TSK_ExplicitSpecialization);
3992 InstantiationFunction->setLocation(Member->getLocation());
3993 }
3994
Douglas Gregor86d142a2009-10-08 07:24:58 +00003995 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3996 cast<CXXMethodDecl>(InstantiatedFrom),
3997 TSK_ExplicitSpecialization);
3998 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003999 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4000 if (InstantiationVar->getTemplateSpecializationKind() ==
4001 TSK_ImplicitInstantiation) {
4002 InstantiationVar->setTemplateSpecializationKind(
4003 TSK_ExplicitSpecialization);
4004 InstantiationVar->setLocation(Member->getLocation());
4005 }
4006
Douglas Gregor86d142a2009-10-08 07:24:58 +00004007 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4008 cast<VarDecl>(InstantiatedFrom),
4009 TSK_ExplicitSpecialization);
4010 } else {
4011 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004012 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4013 if (InstantiationClass->getTemplateSpecializationKind() ==
4014 TSK_ImplicitInstantiation) {
4015 InstantiationClass->setTemplateSpecializationKind(
4016 TSK_ExplicitSpecialization);
4017 InstantiationClass->setLocation(Member->getLocation());
4018 }
4019
Douglas Gregor86d142a2009-10-08 07:24:58 +00004020 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004021 cast<CXXRecordDecl>(InstantiatedFrom),
4022 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004023 }
4024
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004025 // Save the caller the trouble of having to figure out which declaration
4026 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004027 Previous.clear();
4028 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004029 return false;
4030}
4031
Douglas Gregore47f5a72009-10-14 23:41:34 +00004032/// \brief Check the scope of an explicit instantiation.
4033static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4034 SourceLocation InstLoc,
4035 bool WasQualifiedName) {
4036 DeclContext *ExpectedContext
4037 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4038 DeclContext *CurContext = S.CurContext->getLookupContext();
4039
4040 // C++0x [temp.explicit]p2:
4041 // An explicit instantiation shall appear in an enclosing namespace of its
4042 // template.
4043 //
4044 // This is DR275, which we do not retroactively apply to C++98/03.
4045 if (S.getLangOptions().CPlusPlus0x &&
4046 !CurContext->Encloses(ExpectedContext)) {
4047 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4048 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4049 << D << NS;
4050 else
4051 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4052 << D;
4053 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4054 return;
4055 }
4056
4057 // C++0x [temp.explicit]p2:
4058 // If the name declared in the explicit instantiation is an unqualified
4059 // name, the explicit instantiation shall appear in the namespace where
4060 // its template is declared or, if that namespace is inline (7.3.1), any
4061 // namespace from its enclosing namespace set.
4062 if (WasQualifiedName)
4063 return;
4064
4065 if (CurContext->Equals(ExpectedContext))
4066 return;
4067
4068 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4069 << D << ExpectedContext;
4070 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4071}
4072
4073/// \brief Determine whether the given scope specifier has a template-id in it.
4074static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4075 if (!SS.isSet())
4076 return false;
4077
4078 // C++0x [temp.explicit]p2:
4079 // If the explicit instantiation is for a member function, a member class
4080 // or a static data member of a class template specialization, the name of
4081 // the class template specialization in the qualified-id for the member
4082 // name shall be a simple-template-id.
4083 //
4084 // C++98 has the same restriction, just worded differently.
4085 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4086 NNS; NNS = NNS->getPrefix())
4087 if (Type *T = NNS->getAsType())
4088 if (isa<TemplateSpecializationType>(T))
4089 return true;
4090
4091 return false;
4092}
4093
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004094// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00004095// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00004096Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004097Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004098 SourceLocation ExternLoc,
4099 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004100 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004101 SourceLocation KWLoc,
4102 const CXXScopeSpec &SS,
4103 TemplateTy TemplateD,
4104 SourceLocation TemplateNameLoc,
4105 SourceLocation LAngleLoc,
4106 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004107 SourceLocation RAngleLoc,
4108 AttributeList *Attr) {
4109 // Find the class template we're specializing
4110 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004111 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004112 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4113
4114 // Check that the specialization uses the same tag kind as the
4115 // original template.
4116 TagDecl::TagKind Kind;
4117 switch (TagSpec) {
4118 default: assert(0 && "Unknown tag type!");
4119 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4120 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4121 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4122 }
Douglas Gregord9034f02009-05-14 16:41:31 +00004123 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004124 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004125 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004126 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004127 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00004128 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004129 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004130 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004131 diag::note_previous_use);
4132 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4133 }
4134
Douglas Gregore47f5a72009-10-14 23:41:34 +00004135 // C++0x [temp.explicit]p2:
4136 // There are two forms of explicit instantiation: an explicit instantiation
4137 // definition and an explicit instantiation declaration. An explicit
4138 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004139 TemplateSpecializationKind TSK
4140 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4141 : TSK_ExplicitInstantiationDeclaration;
4142
Douglas Gregora1f49972009-05-13 00:25:59 +00004143 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004144 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004145 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004146
4147 // Check that the template argument list is well-formed for this
4148 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004149 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4150 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004151 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4152 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004153 return true;
4154
Mike Stump11289f42009-09-09 15:08:12 +00004155 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004156 ClassTemplate->getTemplateParameters()->size()) &&
4157 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004158
Douglas Gregora1f49972009-05-13 00:25:59 +00004159 // Find the class template specialization declaration that
4160 // corresponds to these arguments.
4161 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004162 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004163 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004164 Converted.flatSize(),
4165 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004166 void *InsertPos = 0;
4167 ClassTemplateSpecializationDecl *PrevDecl
4168 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4169
Douglas Gregor54888652009-10-07 00:13:32 +00004170 // C++0x [temp.explicit]p2:
4171 // [...] An explicit instantiation shall appear in an enclosing
4172 // namespace of its template. [...]
4173 //
4174 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004175 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4176 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004177
Douglas Gregora1f49972009-05-13 00:25:59 +00004178 ClassTemplateSpecializationDecl *Specialization = 0;
4179
Douglas Gregor0681a352009-11-25 06:01:46 +00004180 bool ReusedDecl = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004181 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00004182 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004183 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004184 PrevDecl,
4185 PrevDecl->getSpecializationKind(),
4186 PrevDecl->getPointOfInstantiation(),
4187 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00004188 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004189
Douglas Gregor12e49d32009-10-15 22:53:21 +00004190 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004191 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00004192
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004193 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4194 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4195 // Since the only prior class template specialization with these
4196 // arguments was referenced but not declared, reuse that
4197 // declaration node as our own, updating its source location to
4198 // reflect our new declaration.
4199 Specialization = PrevDecl;
4200 Specialization->setLocation(TemplateNameLoc);
4201 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004202 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004203 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004204 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004205
4206 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004207 // Create a new class template specialization declaration node for
4208 // this explicit specialization.
4209 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00004210 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00004211 ClassTemplate->getDeclContext(),
4212 TemplateNameLoc,
4213 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004214 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004215
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004216 if (PrevDecl) {
4217 // Remove the previous declaration from the folding set, since we want
4218 // to introduce a new declaration.
4219 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4220 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4221 }
4222
4223 // Insert the new specialization.
4224 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004225 }
4226
4227 // Build the fully-sugared type for this explicit instantiation as
4228 // the user wrote in the explicit instantiation itself. This means
4229 // that we'll pretty-print the type retrieved from the
4230 // specialization's declaration the way that the user actually wrote
4231 // the explicit instantiation, rather than formatting the name based
4232 // on the "canonical" representation used to store the template
4233 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004234 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00004235 = Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004236 Context.getTypeDeclType(Specialization));
4237 Specialization->setTypeAsWritten(WrittenTy);
4238 TemplateArgsIn.release();
4239
Douglas Gregor0681a352009-11-25 06:01:46 +00004240 if (!ReusedDecl) {
4241 // Add the explicit instantiation into its lexical context. However,
4242 // since explicit instantiations are never found by name lookup, we
4243 // just put it into the declaration context directly.
4244 Specialization->setLexicalDeclContext(CurContext);
4245 CurContext->addDecl(Specialization);
4246 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004247
4248 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004249 // A definition of a class template or class member template
4250 // shall be in scope at the point of the explicit instantiation of
4251 // the class template or class member template.
4252 //
4253 // This check comes when we actually try to perform the
4254 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004255 ClassTemplateSpecializationDecl *Def
4256 = cast_or_null<ClassTemplateSpecializationDecl>(
4257 Specialization->getDefinition(Context));
4258 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004259 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00004260
4261 // Instantiate the members of this class template specialization.
4262 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4263 Specialization->getDefinition(Context));
4264 if (Def)
Douglas Gregor12e49d32009-10-15 22:53:21 +00004265 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00004266
4267 return DeclPtrTy::make(Specialization);
4268}
4269
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004270// Explicit instantiation of a member class of a class template.
4271Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004272Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004273 SourceLocation ExternLoc,
4274 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004275 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004276 SourceLocation KWLoc,
4277 const CXXScopeSpec &SS,
4278 IdentifierInfo *Name,
4279 SourceLocation NameLoc,
4280 AttributeList *Attr) {
4281
Douglas Gregord6ab8742009-05-28 23:31:59 +00004282 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004283 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004284 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004285 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004286 MultiTemplateParamsArg(*this, 0, 0),
4287 Owned, IsDependent);
4288 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4289
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004290 if (!TagD)
4291 return true;
4292
4293 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4294 if (Tag->isEnum()) {
4295 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4296 << Context.getTypeDeclType(Tag);
4297 return true;
4298 }
4299
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004300 if (Tag->isInvalidDecl())
4301 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004302
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004303 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4304 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4305 if (!Pattern) {
4306 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4307 << Context.getTypeDeclType(Record);
4308 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4309 return true;
4310 }
4311
Douglas Gregore47f5a72009-10-14 23:41:34 +00004312 // C++0x [temp.explicit]p2:
4313 // If the explicit instantiation is for a class or member class, the
4314 // elaborated-type-specifier in the declaration shall include a
4315 // simple-template-id.
4316 //
4317 // C++98 has the same restriction, just worded differently.
4318 if (!ScopeSpecifierHasTemplateId(SS))
4319 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4320 << Record << SS.getRange();
4321
4322 // C++0x [temp.explicit]p2:
4323 // There are two forms of explicit instantiation: an explicit instantiation
4324 // definition and an explicit instantiation declaration. An explicit
4325 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004326 TemplateSpecializationKind TSK
4327 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4328 : TSK_ExplicitInstantiationDeclaration;
4329
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004330 // C++0x [temp.explicit]p2:
4331 // [...] An explicit instantiation shall appear in an enclosing
4332 // namespace of its template. [...]
4333 //
4334 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004335 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004336
4337 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004338 CXXRecordDecl *PrevDecl
4339 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4340 if (!PrevDecl && Record->getDefinition(Context))
4341 PrevDecl = Record;
4342 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004343 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4344 bool SuppressNew = false;
4345 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004346 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004347 PrevDecl,
4348 MSInfo->getTemplateSpecializationKind(),
4349 MSInfo->getPointOfInstantiation(),
4350 SuppressNew))
4351 return true;
4352 if (SuppressNew)
4353 return TagD;
4354 }
4355
Douglas Gregor12e49d32009-10-15 22:53:21 +00004356 CXXRecordDecl *RecordDef
4357 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4358 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004359 // C++ [temp.explicit]p3:
4360 // A definition of a member class of a class template shall be in scope
4361 // at the point of an explicit instantiation of the member class.
4362 CXXRecordDecl *Def
4363 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4364 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004365 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4366 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004367 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4368 << Pattern;
4369 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004370 } else {
4371 if (InstantiateClass(NameLoc, Record, Def,
4372 getTemplateInstantiationArgs(Record),
4373 TSK))
4374 return true;
4375
4376 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4377 if (!RecordDef)
4378 return true;
4379 }
4380 }
4381
4382 // Instantiate all of the members of the class.
4383 InstantiateClassMembers(NameLoc, RecordDef,
4384 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004385
Mike Stump87c57ac2009-05-16 07:39:55 +00004386 // FIXME: We don't have any representation for explicit instantiations of
4387 // member classes. Such a representation is not needed for compilation, but it
4388 // should be available for clients that want to see all of the declarations in
4389 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004390 return TagD;
4391}
4392
Douglas Gregor450f00842009-09-25 18:43:00 +00004393Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4394 SourceLocation ExternLoc,
4395 SourceLocation TemplateLoc,
4396 Declarator &D) {
4397 // Explicit instantiations always require a name.
4398 DeclarationName Name = GetNameForDeclarator(D);
4399 if (!Name) {
4400 if (!D.isInvalidType())
4401 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4402 diag::err_explicit_instantiation_requires_name)
4403 << D.getDeclSpec().getSourceRange()
4404 << D.getSourceRange();
4405
4406 return true;
4407 }
4408
4409 // The scope passed in may not be a decl scope. Zip up the scope tree until
4410 // we find one that is.
4411 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4412 (S->getFlags() & Scope::TemplateParamScope) != 0)
4413 S = S->getParent();
4414
4415 // Determine the type of the declaration.
4416 QualType R = GetTypeForDeclarator(D, S, 0);
4417 if (R.isNull())
4418 return true;
4419
4420 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4421 // Cannot explicitly instantiate a typedef.
4422 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4423 << Name;
4424 return true;
4425 }
4426
Douglas Gregor3c74d412009-10-14 20:14:33 +00004427 // C++0x [temp.explicit]p1:
4428 // [...] An explicit instantiation of a function template shall not use the
4429 // inline or constexpr specifiers.
4430 // Presumably, this also applies to member functions of class templates as
4431 // well.
4432 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4433 Diag(D.getDeclSpec().getInlineSpecLoc(),
4434 diag::err_explicit_instantiation_inline)
Chris Lattner3c7b86f2009-12-06 17:36:05 +00004435 <<CodeModificationHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004436
4437 // FIXME: check for constexpr specifier.
4438
Douglas Gregore47f5a72009-10-14 23:41:34 +00004439 // C++0x [temp.explicit]p2:
4440 // There are two forms of explicit instantiation: an explicit instantiation
4441 // definition and an explicit instantiation declaration. An explicit
4442 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004443 TemplateSpecializationKind TSK
4444 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4445 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004446
John McCall27b18f82009-11-17 02:14:36 +00004447 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4448 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004449
4450 if (!R->isFunctionType()) {
4451 // C++ [temp.explicit]p1:
4452 // A [...] static data member of a class template can be explicitly
4453 // instantiated from the member definition associated with its class
4454 // template.
John McCall27b18f82009-11-17 02:14:36 +00004455 if (Previous.isAmbiguous())
4456 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00004457
John McCall67c00872009-12-02 08:25:40 +00004458 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00004459 if (!Prev || !Prev->isStaticDataMember()) {
4460 // We expect to see a data data member here.
4461 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4462 << Name;
4463 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4464 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004465 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004466 return true;
4467 }
4468
4469 if (!Prev->getInstantiatedFromStaticDataMember()) {
4470 // FIXME: Check for explicit specialization?
4471 Diag(D.getIdentifierLoc(),
4472 diag::err_explicit_instantiation_data_member_not_instantiated)
4473 << Prev;
4474 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4475 // FIXME: Can we provide a note showing where this was declared?
4476 return true;
4477 }
4478
Douglas Gregore47f5a72009-10-14 23:41:34 +00004479 // C++0x [temp.explicit]p2:
4480 // If the explicit instantiation is for a member function, a member class
4481 // or a static data member of a class template specialization, the name of
4482 // the class template specialization in the qualified-id for the member
4483 // name shall be a simple-template-id.
4484 //
4485 // C++98 has the same restriction, just worded differently.
4486 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4487 Diag(D.getIdentifierLoc(),
4488 diag::err_explicit_instantiation_without_qualified_id)
4489 << Prev << D.getCXXScopeSpec().getRange();
4490
4491 // Check the scope of this explicit instantiation.
4492 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4493
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004494 // Verify that it is okay to explicitly instantiate here.
4495 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4496 assert(MSInfo && "Missing static data member specialization info?");
4497 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004498 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004499 MSInfo->getTemplateSpecializationKind(),
4500 MSInfo->getPointOfInstantiation(),
4501 SuppressNew))
4502 return true;
4503 if (SuppressNew)
4504 return DeclPtrTy();
4505
Douglas Gregor450f00842009-09-25 18:43:00 +00004506 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004507 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004508 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004509 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4510 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004511
4512 // FIXME: Create an ExplicitInstantiation node?
4513 return DeclPtrTy();
4514 }
4515
Douglas Gregor0e876e02009-09-25 23:53:26 +00004516 // If the declarator is a template-id, translate the parser's template
4517 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004518 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004519 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004520 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4521 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00004522 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4523 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00004524 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4525 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004526 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00004527 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00004528 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004529 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004530 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004531
Douglas Gregor450f00842009-09-25 18:43:00 +00004532 // C++ [temp.explicit]p1:
4533 // A [...] function [...] can be explicitly instantiated from its template.
4534 // A member function [...] of a class template can be explicitly
4535 // instantiated from the member definition associated with its class
4536 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00004537 llvm::SmallVector<FunctionDecl *, 8> Matches;
4538 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4539 P != PEnd; ++P) {
4540 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004541 if (!HasExplicitTemplateArgs) {
4542 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4543 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4544 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004545
Douglas Gregord90fd522009-09-25 21:45:23 +00004546 Matches.push_back(Method);
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004547 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
4548 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00004549 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004550 }
4551 }
4552
4553 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4554 if (!FunTmpl)
4555 continue;
4556
4557 TemplateDeductionInfo Info(Context);
4558 FunctionDecl *Specialization = 0;
4559 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004560 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00004561 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004562 R, Specialization, Info)) {
4563 // FIXME: Keep track of almost-matches?
4564 (void)TDK;
4565 continue;
4566 }
4567
4568 Matches.push_back(Specialization);
4569 }
4570
4571 // Find the most specialized function template specialization.
4572 FunctionDecl *Specialization
4573 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4574 D.getIdentifierLoc(),
4575 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4576 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4577 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4578
4579 if (!Specialization)
4580 return true;
4581
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004582 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004583 Diag(D.getIdentifierLoc(),
4584 diag::err_explicit_instantiation_member_function_not_instantiated)
4585 << Specialization
4586 << (Specialization->getTemplateSpecializationKind() ==
4587 TSK_ExplicitSpecialization);
4588 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4589 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004590 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004591
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004592 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004593 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4594 PrevDecl = Specialization;
4595
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004596 if (PrevDecl) {
4597 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004598 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004599 PrevDecl,
4600 PrevDecl->getTemplateSpecializationKind(),
4601 PrevDecl->getPointOfInstantiation(),
4602 SuppressNew))
4603 return true;
4604
4605 // FIXME: We may still want to build some representation of this
4606 // explicit specialization.
4607 if (SuppressNew)
4608 return DeclPtrTy();
4609 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00004610
4611 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004612
4613 if (TSK == TSK_ExplicitInstantiationDefinition)
4614 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4615 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004616
Douglas Gregore47f5a72009-10-14 23:41:34 +00004617 // C++0x [temp.explicit]p2:
4618 // If the explicit instantiation is for a member function, a member class
4619 // or a static data member of a class template specialization, the name of
4620 // the class template specialization in the qualified-id for the member
4621 // name shall be a simple-template-id.
4622 //
4623 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004624 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00004625 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00004626 D.getCXXScopeSpec().isSet() &&
4627 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4628 Diag(D.getIdentifierLoc(),
4629 diag::err_explicit_instantiation_without_qualified_id)
4630 << Specialization << D.getCXXScopeSpec().getRange();
4631
4632 CheckExplicitInstantiationScope(*this,
4633 FunTmpl? (NamedDecl *)FunTmpl
4634 : Specialization->getInstantiatedFromMemberFunction(),
4635 D.getIdentifierLoc(),
4636 D.getCXXScopeSpec().isSet());
4637
Douglas Gregor450f00842009-09-25 18:43:00 +00004638 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4639 return DeclPtrTy();
4640}
4641
Douglas Gregor333489b2009-03-27 23:10:48 +00004642Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004643Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4644 const CXXScopeSpec &SS, IdentifierInfo *Name,
4645 SourceLocation TagLoc, SourceLocation NameLoc) {
4646 // This has to hold, because SS is expected to be defined.
4647 assert(Name && "Expected a name in a dependent tag");
4648
4649 NestedNameSpecifier *NNS
4650 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4651 if (!NNS)
4652 return true;
4653
4654 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4655 if (T.isNull())
4656 return true;
4657
4658 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4659 QualType ElabType = Context.getElaboratedType(T, TagKind);
4660
4661 return ElabType.getAsOpaquePtr();
4662}
4663
4664Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004665Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4666 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004667 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004668 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4669 if (!NNS)
4670 return true;
4671
4672 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004673 if (T.isNull())
4674 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004675 return T.getAsOpaquePtr();
4676}
4677
Douglas Gregordce2b622009-04-01 00:28:59 +00004678Sema::TypeResult
4679Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4680 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004681 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004682 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004683 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004684 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004685 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004686 assert(TemplateId && "Expected a template specialization type");
4687
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004688 if (computeDeclContext(SS, false)) {
4689 // If we can compute a declaration context, then the "typename"
4690 // keyword was superfluous. Just build a QualifiedNameType to keep
4691 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004692
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004693 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4694 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4695 }
Mike Stump11289f42009-09-09 15:08:12 +00004696
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004697 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004698}
4699
Douglas Gregor333489b2009-03-27 23:10:48 +00004700/// \brief Build the type that describes a C++ typename specifier,
4701/// e.g., "typename T::type".
4702QualType
4703Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4704 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004705 CXXRecordDecl *CurrentInstantiation = 0;
4706 if (NNS->isDependent()) {
4707 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004708
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004709 // If the nested-name-specifier does not refer to the current
4710 // instantiation, then build a typename type.
4711 if (!CurrentInstantiation)
4712 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004713
Douglas Gregorc707da62009-09-02 13:12:51 +00004714 // The nested-name-specifier refers to the current instantiation, so the
4715 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004716 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004717 // extraneous "typename" keywords, and we retroactively apply this DR to
4718 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004719 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004720
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004721 DeclContext *Ctx = 0;
4722
4723 if (CurrentInstantiation)
4724 Ctx = CurrentInstantiation;
4725 else {
4726 CXXScopeSpec SS;
4727 SS.setScopeRep(NNS);
4728 SS.setRange(Range);
4729 if (RequireCompleteDeclContext(SS))
4730 return QualType();
4731
4732 Ctx = computeDeclContext(SS);
4733 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004734 assert(Ctx && "No declaration context?");
4735
4736 DeclarationName Name(&II);
John McCall27b18f82009-11-17 02:14:36 +00004737 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4738 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00004739 unsigned DiagID = 0;
4740 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00004741 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004742 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004743 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004744 break;
4745
4746 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004747 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004748 // We found a type. Build a QualifiedNameType, since the
4749 // typename-specifier was just sugar. FIXME: Tell
4750 // QualifiedNameType that it has a "typename" prefix.
4751 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4752 }
4753
4754 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004755 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004756 break;
4757
John McCalle61f2ba2009-11-18 02:36:19 +00004758 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004759 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00004760 return QualType();
4761
Douglas Gregor333489b2009-03-27 23:10:48 +00004762 case LookupResult::FoundOverloaded:
4763 DiagID = diag::err_typename_nested_not_type;
4764 Referenced = *Result.begin();
4765 break;
4766
John McCall6538c932009-10-10 05:48:19 +00004767 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004768 return QualType();
4769 }
4770
4771 // If we get here, it's because name lookup did not find a
4772 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004773 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004774 if (Referenced)
4775 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4776 << Name;
4777 return QualType();
4778}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004779
4780namespace {
4781 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00004782 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00004783 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004784 SourceLocation Loc;
4785 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004786
Douglas Gregor15acfb92009-08-06 16:20:37 +00004787 public:
Mike Stump11289f42009-09-09 15:08:12 +00004788 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004789 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004790 DeclarationName Entity)
4791 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004792 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004793
4794 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004795 /// transformed.
4796 ///
4797 /// For the purposes of type reconstruction, a type has already been
4798 /// transformed if it is NULL or if it is not dependent.
4799 bool AlreadyTransformed(QualType T) {
4800 return T.isNull() || !T->isDependentType();
4801 }
Mike Stump11289f42009-09-09 15:08:12 +00004802
4803 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004804 /// rebuilt.
4805 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004806
Douglas Gregor15acfb92009-08-06 16:20:37 +00004807 /// \brief Returns the name of the entity whose type is being rebuilt.
4808 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004809
Douglas Gregoref6ab412009-10-27 06:26:26 +00004810 /// \brief Sets the "base" location and entity when that
4811 /// information is known based on another transformation.
4812 void setBase(SourceLocation Loc, DeclarationName Entity) {
4813 this->Loc = Loc;
4814 this->Entity = Entity;
4815 }
4816
Douglas Gregor15acfb92009-08-06 16:20:37 +00004817 /// \brief Transforms an expression by returning the expression itself
4818 /// (an identity function).
4819 ///
4820 /// FIXME: This is completely unsafe; we will need to actually clone the
4821 /// expressions.
4822 Sema::OwningExprResult TransformExpr(Expr *E) {
4823 return getSema().Owned(E);
4824 }
Mike Stump11289f42009-09-09 15:08:12 +00004825
Douglas Gregor15acfb92009-08-06 16:20:37 +00004826 /// \brief Transforms a typename type by determining whether the type now
4827 /// refers to a member of the current instantiation, and then
4828 /// type-checking and building a QualifiedNameType (when possible).
John McCall550e0c22009-10-21 00:40:46 +00004829 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004830 };
4831}
4832
Mike Stump11289f42009-09-09 15:08:12 +00004833QualType
John McCall550e0c22009-10-21 00:40:46 +00004834CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4835 TypenameTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00004836 TypenameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00004837
Douglas Gregor15acfb92009-08-06 16:20:37 +00004838 NestedNameSpecifier *NNS
4839 = TransformNestedNameSpecifier(T->getQualifier(),
4840 /*FIXME:*/SourceRange(getBaseLocation()));
4841 if (!NNS)
4842 return QualType();
4843
4844 // If the nested-name-specifier did not change, and we cannot compute the
4845 // context corresponding to the nested-name-specifier, then this
4846 // typename type will not change; exit early.
4847 CXXScopeSpec SS;
4848 SS.setRange(SourceRange(getBaseLocation()));
4849 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00004850
4851 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004852 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00004853 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004854
4855 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004856 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00004857 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004858 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004859 = TransformType(QualType(TemplateId, 0));
4860 if (NewTemplateId.isNull())
4861 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004862
Douglas Gregor15acfb92009-08-06 16:20:37 +00004863 if (NNS == T->getQualifier() &&
4864 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00004865 Result = QualType(T, 0);
4866 else
4867 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4868 } else
4869 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4870 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00004871
John McCall0ad16662009-10-29 08:12:44 +00004872 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4873 NewTL.setNameLoc(TL.getNameLoc());
4874 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004875}
4876
4877/// \brief Rebuilds a type within the context of the current instantiation.
4878///
Mike Stump11289f42009-09-09 15:08:12 +00004879/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00004880/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00004881/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00004882/// partial specialization thereof). This routine will rebuild that type now
4883/// that we have entered the declarator's scope, which may produce different
4884/// canonical types, e.g.,
4885///
4886/// \code
4887/// template<typename T>
4888/// struct X {
4889/// typedef T* pointer;
4890/// pointer data();
4891/// };
4892///
4893/// template<typename T>
4894/// typename X<T>::pointer X<T>::data() { ... }
4895/// \endcode
4896///
4897/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4898/// since we do not know that we can look into X<T> when we parsed the type.
4899/// This function will rebuild the type, performing the lookup of "pointer"
4900/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4901/// as the canonical type of T*, allowing the return types of the out-of-line
4902/// definition and the declaration to match.
4903QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4904 DeclarationName Name) {
4905 if (T.isNull() || !T->isDependentType())
4906 return T;
Mike Stump11289f42009-09-09 15:08:12 +00004907
Douglas Gregor15acfb92009-08-06 16:20:37 +00004908 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4909 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00004910}
Douglas Gregorbe999392009-09-15 16:23:51 +00004911
4912/// \brief Produces a formatted string that describes the binding of
4913/// template parameters to template arguments.
4914std::string
4915Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4916 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004917 // FIXME: For variadic templates, we'll need to get the structured list.
4918 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4919 Args.flat_size());
4920}
4921
4922std::string
4923Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4924 const TemplateArgument *Args,
4925 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004926 std::string Result;
4927
Douglas Gregore62e6a02009-11-11 19:13:48 +00004928 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00004929 return Result;
4930
4931 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004932 if (I >= NumArgs)
4933 break;
4934
Douglas Gregorbe999392009-09-15 16:23:51 +00004935 if (I == 0)
4936 Result += "[with ";
4937 else
4938 Result += ", ";
4939
4940 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4941 Result += Id->getName();
4942 } else {
4943 Result += '$';
4944 Result += llvm::utostr(I);
4945 }
4946
4947 Result += " = ";
4948
4949 switch (Args[I].getKind()) {
4950 case TemplateArgument::Null:
4951 Result += "<no value>";
4952 break;
4953
4954 case TemplateArgument::Type: {
4955 std::string TypeStr;
4956 Args[I].getAsType().getAsStringInternal(TypeStr,
4957 Context.PrintingPolicy);
4958 Result += TypeStr;
4959 break;
4960 }
4961
4962 case TemplateArgument::Declaration: {
4963 bool Unnamed = true;
4964 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4965 if (ND->getDeclName()) {
4966 Unnamed = false;
4967 Result += ND->getNameAsString();
4968 }
4969 }
4970
4971 if (Unnamed) {
4972 Result += "<anonymous>";
4973 }
4974 break;
4975 }
4976
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004977 case TemplateArgument::Template: {
4978 std::string Str;
4979 llvm::raw_string_ostream OS(Str);
4980 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
4981 Result += OS.str();
4982 break;
4983 }
4984
Douglas Gregorbe999392009-09-15 16:23:51 +00004985 case TemplateArgument::Integral: {
4986 Result += Args[I].getAsIntegral()->toString(10);
4987 break;
4988 }
4989
4990 case TemplateArgument::Expression: {
4991 assert(false && "No expressions in deduced template arguments!");
4992 Result += "<expression>";
4993 break;
4994 }
4995
4996 case TemplateArgument::Pack:
4997 // FIXME: Format template argument packs
4998 Result += "<template argument pack>";
4999 break;
5000 }
5001 }
5002
5003 Result += ']';
5004 return Result;
5005}