blob: f77454b0594f9660fa467bb9530a5e1be754f429 [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000018#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000020#include "clang/Parse/DeclSpec.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000021#include "clang/Parse/Template.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregorb7bfe792009-09-02 22:59:36 +000027/// \brief Determine whether the declaration found is acceptable as the name
28/// of a template and, if so, return that template declaration. Otherwise,
29/// returns NULL.
30static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
31 if (!D)
32 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000033
Douglas Gregorb7bfe792009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
35 return D;
Mike Stump11289f42009-09-09 15:08:12 +000036
Douglas Gregorb7bfe792009-09-02 22:59:36 +000037 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
38 // C++ [temp.local]p1:
39 // Like normal (non-template) classes, class templates have an
40 // injected-class-name (Clause 9). The injected-class-name
41 // can be used with or without a template-argument-list. When
42 // it is used without a template-argument-list, it is
43 // equivalent to the injected-class-name followed by the
44 // template-parameters of the class template enclosed in
45 // <>. When it is used with a template-argument-list, it
46 // refers to the specified class template specialization,
47 // which could be the current specialization or another
48 // specialization.
49 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000051 if (Record->getDescribedClassTemplate())
52 return Record->getDescribedClassTemplate();
53
54 if (ClassTemplateSpecializationDecl *Spec
55 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
56 return Spec->getSpecializedTemplate();
57 }
Mike Stump11289f42009-09-09 15:08:12 +000058
Douglas Gregorb7bfe792009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump11289f42009-09-09 15:08:12 +000061
Douglas Gregorb7bfe792009-09-02 22:59:36 +000062 return 0;
63}
64
John McCalle66edc12009-11-24 19:00:30 +000065static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor41f90302010-04-12 20:54:26 +000066 // The set of class templates we've already seen.
67 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000068 LookupResult::Filter filter = R.makeFilter();
69 while (filter.hasNext()) {
70 NamedDecl *Orig = filter.next();
71 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
72 if (!Repl)
73 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +000074 else if (Repl != Orig) {
75
76 // C++ [temp.local]p3:
77 // A lookup that finds an injected-class-name (10.2) can result in an
78 // ambiguity in certain cases (for example, if it is found in more than
79 // one base class). If all of the injected-class-names that are found
80 // refer to specializations of the same class template, and if the name
81 // is followed by a template-argument-list, the reference refers to the
82 // class template itself and not a specialization thereof, and is not
83 // ambiguous.
84 //
85 // FIXME: Will we eventually have to do the same for alias templates?
86 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
87 if (!ClassTemplates.insert(ClassTmpl)) {
88 filter.erase();
89 continue;
90 }
91
John McCalle66edc12009-11-24 19:00:30 +000092 filter.replace(Repl);
Douglas Gregor41f90302010-04-12 20:54:26 +000093 }
John McCalle66edc12009-11-24 19:00:30 +000094 }
95 filter.done();
96}
97
Douglas Gregorb7bfe792009-09-02 22:59:36 +000098TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +000099 CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000100 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000101 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000102 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000103 TemplateTy &TemplateResult,
104 bool &MemberOfUnknownSpecialization) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000105 assert(getLangOptions().CPlusPlus && "No template names in C!");
106
Douglas Gregor3cf81312009-11-03 23:16:33 +0000107 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000108 MemberOfUnknownSpecialization = false;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000109
110 switch (Name.getKind()) {
111 case UnqualifiedId::IK_Identifier:
112 TName = DeclarationName(Name.Identifier);
113 break;
114
115 case UnqualifiedId::IK_OperatorFunctionId:
116 TName = Context.DeclarationNames.getCXXOperatorName(
117 Name.OperatorFunctionId.Operator);
118 break;
119
Alexis Hunted0530f2009-11-28 08:58:14 +0000120 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000121 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
122 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000123
Douglas Gregor3cf81312009-11-03 23:16:33 +0000124 default:
125 return TNK_Non_template;
126 }
Mike Stump11289f42009-09-09 15:08:12 +0000127
John McCalle66edc12009-11-24 19:00:30 +0000128 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump11289f42009-09-09 15:08:12 +0000129
Douglas Gregorff18cc12009-12-31 08:11:17 +0000130 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
131 LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +0000132 R.suppressDiagnostics();
Douglas Gregor786123d2010-05-21 23:18:07 +0000133 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
134 MemberOfUnknownSpecialization);
Douglas Gregor41f90302010-04-12 20:54:26 +0000135 if (R.empty() || R.isAmbiguous())
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000136 return TNK_Non_template;
137
John McCalld28ae272009-12-02 08:04:21 +0000138 TemplateName Template;
139 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000140
John McCalld28ae272009-12-02 08:04:21 +0000141 unsigned ResultCount = R.end() - R.begin();
142 if (ResultCount > 1) {
143 // We assume that we'll preserve the qualifier from a function
144 // template name in other ways.
145 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
146 TemplateKind = TNK_Function_template;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000147 } else {
John McCalld28ae272009-12-02 08:04:21 +0000148 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
149
150 if (SS.isSet() && !SS.isInvalid()) {
151 NestedNameSpecifier *Qualifier
152 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
153 Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
154 } else {
155 Template = TemplateName(TD);
156 }
157
158 if (isa<FunctionTemplateDecl>(TD))
159 TemplateKind = TNK_Function_template;
160 else {
161 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
162 TemplateKind = TNK_Type_template;
163 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000164 }
Mike Stump11289f42009-09-09 15:08:12 +0000165
John McCalld28ae272009-12-02 08:04:21 +0000166 TemplateResult = TemplateTy::make(Template);
167 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000168}
169
Douglas Gregor18473f32010-01-12 21:28:44 +0000170bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
171 SourceLocation IILoc,
172 Scope *S,
173 const CXXScopeSpec *SS,
174 TemplateTy &SuggestedTemplate,
175 TemplateNameKind &SuggestedKind) {
176 // We can't recover unless there's a dependent scope specifier preceding the
177 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000178 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000179 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
180 computeDeclContext(*SS))
181 return false;
182
183 // The code is missing a 'template' keyword prior to the dependent template
184 // name.
185 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
186 Diag(IILoc, diag::err_template_kw_missing)
187 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000188 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor18473f32010-01-12 21:28:44 +0000189 SuggestedTemplate
190 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
191 SuggestedKind = TNK_Dependent_template_name;
192 return true;
193}
194
John McCalle66edc12009-11-24 19:00:30 +0000195void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000196 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000197 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000198 bool EnteringContext,
199 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000200 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000201 MemberOfUnknownSpecialization = false;
John McCalle66edc12009-11-24 19:00:30 +0000202 DeclContext *LookupCtx = 0;
203 bool isDependent = false;
204 if (!ObjectType.isNull()) {
205 // This nested-name-specifier occurs in a member access expression, e.g.,
206 // x->B::f, and we are looking into the type of the object.
207 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
208 LookupCtx = computeDeclContext(ObjectType);
209 isDependent = ObjectType->isDependentType();
210 assert((isDependent || !ObjectType->isIncompleteType()) &&
211 "Caller should have completed object type");
212 } else if (SS.isSet()) {
213 // This nested-name-specifier occurs after another nested-name-specifier,
214 // so long into the context associated with the prior nested-name-specifier.
215 LookupCtx = computeDeclContext(SS, EnteringContext);
216 isDependent = isDependentScopeSpecifier(SS);
217
218 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000219 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000220 return;
221 }
222
223 bool ObjectTypeSearchedInScope = false;
224 if (LookupCtx) {
225 // Perform "qualified" name lookup into the declaration context we
226 // computed, which is either the type of the base of a member access
227 // expression or the declaration context associated with a prior
228 // nested-name-specifier.
229 LookupQualifiedName(Found, LookupCtx);
230
231 if (!ObjectType.isNull() && Found.empty()) {
232 // C++ [basic.lookup.classref]p1:
233 // In a class member access expression (5.2.5), if the . or -> token is
234 // immediately followed by an identifier followed by a <, the
235 // identifier must be looked up to determine whether the < is the
236 // beginning of a template argument list (14.2) or a less-than operator.
237 // The identifier is first looked up in the class of the object
238 // expression. If the identifier is not found, it is then looked up in
239 // the context of the entire postfix-expression and shall name a class
240 // or function template.
241 //
242 // FIXME: When we're instantiating a template, do we actually have to
243 // look in the scope of the template? Seems fishy...
244 if (S) LookupName(Found, S);
245 ObjectTypeSearchedInScope = true;
246 }
247 } else if (isDependent) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000248 // We cannot look into a dependent object type or nested nme
249 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000250 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000251 return;
252 } else {
253 // Perform unqualified name lookup in the current scope.
254 LookupName(Found, S);
255 }
256
Douglas Gregorc119dd52010-01-12 17:06:20 +0000257 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000258 // If we did not find any names, attempt to correct any typos.
259 DeclarationName Name = Found.getLookupName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000260 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
261 false, CTC_CXXCasts)) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000262 FilterAcceptableTemplateNames(Context, Found);
263 if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
264 if (LookupCtx)
265 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
266 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000267 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000268 Found.getLookupName().getAsString());
269 else
270 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
271 << Name << Found.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +0000272 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000273 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000274 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
275 Diag(Template->getLocation(), diag::note_previous_decl)
276 << Template->getDeclName();
Douglas Gregorff18cc12009-12-31 08:11:17 +0000277 } else
278 Found.clear();
279 } else {
280 Found.clear();
281 }
282 }
283
John McCalle66edc12009-11-24 19:00:30 +0000284 FilterAcceptableTemplateNames(Context, Found);
285 if (Found.empty())
286 return;
287
288 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
289 // C++ [basic.lookup.classref]p1:
290 // [...] If the lookup in the class of the object expression finds a
291 // template, the name is also looked up in the context of the entire
292 // postfix-expression and [...]
293 //
294 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
295 LookupOrdinaryName);
296 LookupName(FoundOuter, S);
297 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor41f90302010-04-12 20:54:26 +0000298
John McCalle66edc12009-11-24 19:00:30 +0000299 if (FoundOuter.empty()) {
300 // - if the name is not found, the name found in the class of the
301 // object expression is used, otherwise
302 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
303 // - if the name is found in the context of the entire
304 // postfix-expression and does not name a class template, the name
305 // found in the class of the object expression is used, otherwise
306 } else {
307 // - if the name found is a class template, it must refer to the same
308 // entity as the one found in the class of the object expression,
309 // otherwise the program is ill-formed.
310 if (!Found.isSingleResult() ||
311 Found.getFoundDecl()->getCanonicalDecl()
312 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
313 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000314 diag::ext_nested_name_member_ref_lookup_ambiguous)
315 << Found.getLookupName()
316 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000317 Diag(Found.getRepresentativeDecl()->getLocation(),
318 diag::note_ambig_member_ref_object_type)
319 << ObjectType;
320 Diag(FoundOuter.getFoundDecl()->getLocation(),
321 diag::note_ambig_member_ref_scope);
322
323 // Recover by taking the template that we found in the object
324 // expression's type.
325 }
326 }
327 }
328}
329
John McCallcd4b4772009-12-02 03:53:29 +0000330/// ActOnDependentIdExpression - Handle a dependent id-expression that
331/// was just parsed. This is only possible with an explicit scope
332/// specifier naming a dependent type.
John McCalle66edc12009-11-24 19:00:30 +0000333Sema::OwningExprResult
334Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
335 DeclarationName Name,
336 SourceLocation NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +0000337 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000338 const TemplateArgumentListInfo *TemplateArgs) {
339 NestedNameSpecifier *Qualifier
340 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall87fe5d52010-05-20 01:18:31 +0000341
342 DeclContext *DC = getFunctionLevelDeclContext();
John McCalle66edc12009-11-24 19:00:30 +0000343
John McCallcd4b4772009-12-02 03:53:29 +0000344 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000345 isa<CXXMethodDecl>(DC) &&
346 cast<CXXMethodDecl>(DC)->isInstance()) {
347 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCallcd4b4772009-12-02 03:53:29 +0000348
John McCalle66edc12009-11-24 19:00:30 +0000349 // Since the 'this' expression is synthesized, we don't need to
350 // perform the double-lookup check.
351 NamedDecl *FirstQualifierInScope = 0;
352
John McCall2d74de92009-12-01 22:10:20 +0000353 return Owned(CXXDependentScopeMemberExpr::Create(Context,
354 /*This*/ 0, ThisType,
355 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000356 /*Op*/ SourceLocation(),
357 Qualifier, SS.getRange(),
358 FirstQualifierInScope,
359 Name, NameLoc,
360 TemplateArgs));
361 }
362
363 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
364}
365
366Sema::OwningExprResult
367Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
368 DeclarationName Name,
369 SourceLocation NameLoc,
370 const TemplateArgumentListInfo *TemplateArgs) {
371 return Owned(DependentScopeDeclRefExpr::Create(Context,
372 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
373 SS.getRange(),
374 Name, NameLoc,
375 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000376}
377
Douglas Gregor5101c242008-12-05 18:15:24 +0000378/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
379/// that the template parameter 'PrevDecl' is being shadowed by a new
380/// declaration at location Loc. Returns true to indicate that this is
381/// an error, and false otherwise.
382bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000383 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000384
385 // Microsoft Visual C++ permits template parameters to be shadowed.
386 if (getLangOptions().Microsoft)
387 return false;
388
389 // C++ [temp.local]p4:
390 // A template-parameter shall not be redeclared within its
391 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000392 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000393 << cast<NamedDecl>(PrevDecl)->getDeclName();
394 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
395 return true;
396}
397
Douglas Gregor463421d2009-03-03 04:44:36 +0000398/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000399/// the parameter D to reference the templated declaration and return a pointer
400/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000401TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000402 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000403 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000404 return Temp;
405 }
406 return 0;
407}
408
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000409static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
410 const ParsedTemplateArgument &Arg) {
411
412 switch (Arg.getKind()) {
413 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000414 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000415 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
416 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000417 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000418 return TemplateArgumentLoc(TemplateArgument(T), DI);
419 }
420
421 case ParsedTemplateArgument::NonType: {
422 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
423 return TemplateArgumentLoc(TemplateArgument(E), E);
424 }
425
426 case ParsedTemplateArgument::Template: {
427 TemplateName Template
428 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
429 return TemplateArgumentLoc(TemplateArgument(Template),
430 Arg.getScopeSpec().getRange(),
431 Arg.getLocation());
432 }
433 }
434
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000435 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000436 return TemplateArgumentLoc();
437}
438
439/// \brief Translates template arguments as provided by the parser
440/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000441void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
442 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000443 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000444 TemplateArgs.addArgument(translateTemplateArgument(*this,
445 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000446}
447
Douglas Gregor5101c242008-12-05 18:15:24 +0000448/// ActOnTypeParameter - Called when a C++ template type parameter
449/// (e.g., "typename T") has been parsed. Typename specifies whether
450/// the keyword "typename" was used to declare the type parameter
451/// (otherwise, "class" was used), and KeyLoc is the location of the
452/// "class" or "typename" keyword. ParamName is the name of the
453/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000454/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000455/// If the type parameter has a default argument, it will be added
456/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000457Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000458 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000459 SourceLocation KeyLoc,
460 IdentifierInfo *ParamName,
461 SourceLocation ParamNameLoc,
462 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000463 assert(S->isTemplateParamScope() &&
464 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000465 bool Invalid = false;
466
467 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000468 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000469 LookupOrdinaryName,
470 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000471 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000472 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000473 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000474 }
475
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000476 SourceLocation Loc = ParamNameLoc;
477 if (!ParamName)
478 Loc = KeyLoc;
479
Douglas Gregor5101c242008-12-05 18:15:24 +0000480 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000481 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
482 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000483 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000484 if (Invalid)
485 Param->setInvalidDecl();
486
487 if (ParamName) {
488 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000489 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000490 IdResolver.AddDecl(Param);
491 }
492
Chris Lattner83f095c2009-03-28 19:18:32 +0000493 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000494}
495
Douglas Gregordba32632009-02-10 19:49:53 +0000496/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000497/// Default) to the given template type parameter (TypeParam).
498void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000499 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000500 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000501 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000502 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000503 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000504
John McCallbcd03502009-12-07 02:54:59 +0000505 TypeSourceInfo *DefaultTInfo;
506 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall0ad16662009-10-29 08:12:44 +0000507
John McCallbcd03502009-12-07 02:54:59 +0000508 assert(DefaultTInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000509
Anders Carlssond3824352009-06-12 22:30:13 +0000510 // C++0x [temp.param]p9:
511 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000512 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000513 if (Parm->isParameterPack()) {
514 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000515 return;
516 }
Mike Stump11289f42009-09-09 15:08:12 +0000517
Douglas Gregordba32632009-02-10 19:49:53 +0000518 // C++ [temp.param]p14:
519 // A template-parameter shall not be used in its own default argument.
520 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000521
Douglas Gregordba32632009-02-10 19:49:53 +0000522 // Check the template argument itself.
John McCallbcd03502009-12-07 02:54:59 +0000523 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000524 Parm->setInvalidDecl();
525 return;
526 }
527
John McCallbcd03502009-12-07 02:54:59 +0000528 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000529}
530
Douglas Gregor463421d2009-03-03 04:44:36 +0000531/// \brief Check that the type of a non-type template parameter is
532/// well-formed.
533///
534/// \returns the (possibly-promoted) parameter type if valid;
535/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000536QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000537Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000538 // We don't allow variably-modified types as the type of non-type template
539 // parameters.
540 if (T->isVariablyModifiedType()) {
541 Diag(Loc, diag::err_variably_modified_nontype_template_param)
542 << T;
543 return QualType();
544 }
545
Douglas Gregor463421d2009-03-03 04:44:36 +0000546 // C++ [temp.param]p4:
547 //
548 // A non-type template-parameter shall have one of the following
549 // (optionally cv-qualified) types:
550 //
551 // -- integral or enumeration type,
552 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000553 // -- pointer to object or pointer to function,
554 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000555 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
556 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000557 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000558 T->isReferenceType() ||
559 // -- pointer to member.
560 T->isMemberPointerType() ||
561 // If T is a dependent type, we can't do the check now, so we
562 // assume that it is well-formed.
563 T->isDependentType())
564 return T;
565 // C++ [temp.param]p8:
566 //
567 // A non-type template-parameter of type "array of T" or
568 // "function returning T" is adjusted to be of type "pointer to
569 // T" or "pointer to function returning T", respectively.
570 else if (T->isArrayType())
571 // FIXME: Keep the type prior to promotion?
572 return Context.getArrayDecayedType(T);
573 else if (T->isFunctionType())
574 // FIXME: Keep the type prior to promotion?
575 return Context.getPointerType(T);
Douglas Gregor959d5a02010-05-22 16:17:30 +0000576
Douglas Gregor463421d2009-03-03 04:44:36 +0000577 Diag(Loc, diag::err_template_nontype_parm_bad_type)
578 << T;
579
580 return QualType();
581}
582
Douglas Gregor5101c242008-12-05 18:15:24 +0000583/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
584/// template parameter (e.g., "int Size" in "template<int Size>
585/// class Array") has been parsed. S is the current scope and D is
586/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000587Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000588 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000589 unsigned Position) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000590 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
591 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000592
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000593 assert(S->isTemplateParamScope() &&
594 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000595 bool Invalid = false;
596
597 IdentifierInfo *ParamName = D.getIdentifier();
598 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000599 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000600 LookupOrdinaryName,
601 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000602 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000603 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000604 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000605 }
606
Douglas Gregor463421d2009-03-03 04:44:36 +0000607 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000608 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000609 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000610 Invalid = true;
611 }
Douglas Gregor81338792009-02-10 17:43:50 +0000612
Douglas Gregor5101c242008-12-05 18:15:24 +0000613 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000614 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
615 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000616 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000617 if (Invalid)
618 Param->setInvalidDecl();
619
620 if (D.getIdentifier()) {
621 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000622 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000623 IdResolver.AddDecl(Param);
624 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000625 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000626}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000627
Douglas Gregordba32632009-02-10 19:49:53 +0000628/// \brief Adds a default argument to the given non-type template
629/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000630void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000631 SourceLocation EqualLoc,
632 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000633 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000634 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000635 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000636
Douglas Gregordba32632009-02-10 19:49:53 +0000637 // C++ [temp.param]p14:
638 // A template-parameter shall not be used in its own default argument.
639 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000640
Douglas Gregordba32632009-02-10 19:49:53 +0000641 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000642 TemplateArgument Converted;
643 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
644 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000645 TemplateParm->setInvalidDecl();
646 return;
647 }
648
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000649 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000650}
651
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000652
653/// ActOnTemplateTemplateParameter - Called when a C++ template template
654/// parameter (e.g. T in template <template <typename> class T> class array)
655/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000656Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
657 SourceLocation TmpLoc,
658 TemplateParamsTy *Params,
659 IdentifierInfo *Name,
660 SourceLocation NameLoc,
661 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000662 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000663 assert(S->isTemplateParamScope() &&
664 "Template template parameter not in template parameter scope!");
665
666 // Construct the parameter object.
667 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000668 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
669 TmpLoc, Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000670 (TemplateParameterList*)Params);
671
672 // Make sure the parameter is valid.
673 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
674 // do anything yet. However, if the template parameter list or (eventual)
675 // default value is ever invalidated, that will propagate here.
676 bool Invalid = false;
677 if (Invalid) {
678 Param->setInvalidDecl();
679 }
680
681 // If the tt-param has a name, then link the identifier into the scope
682 // and lookup mechanisms.
683 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000684 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000685 IdResolver.AddDecl(Param);
686 }
687
Chris Lattner83f095c2009-03-28 19:18:32 +0000688 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000689}
690
Douglas Gregordba32632009-02-10 19:49:53 +0000691/// \brief Adds a default argument to the given template template
692/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000693void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000694 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000695 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000696 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000697 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000698
Douglas Gregordba32632009-02-10 19:49:53 +0000699 // C++ [temp.param]p14:
700 // A template-parameter shall not be used in its own default argument.
701 // FIXME: Implement this check! Needs a recursive walk over the types.
702
Douglas Gregore62e6a02009-11-11 19:13:48 +0000703 // Check only that we have a template template argument. We don't want to
704 // try to check well-formedness now, because our template template parameter
705 // might have dependent types in its template parameters, which we wouldn't
706 // be able to match now.
707 //
708 // If none of the template template parameter's template arguments mention
709 // other template parameters, we could actually perform more checking here.
710 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000711 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000712 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
713 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
714 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000715 return;
716 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000717
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000718 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000719}
720
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000721/// ActOnTemplateParameterList - Builds a TemplateParameterList that
722/// contains the template parameters in Params/NumParams.
723Sema::TemplateParamsTy *
724Sema::ActOnTemplateParameterList(unsigned Depth,
725 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000726 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000727 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000728 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000729 SourceLocation RAngleLoc) {
730 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000731 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000732
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000733 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000734 (NamedDecl**)Params, NumParams,
735 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000736}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000737
John McCall3e11ebe2010-03-15 10:12:16 +0000738static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
739 if (SS.isSet())
740 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
741 SS.getRange());
742}
743
Douglas Gregorc08f4892009-03-25 00:13:59 +0000744Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000745Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000746 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000747 IdentifierInfo *Name, SourceLocation NameLoc,
748 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000749 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000750 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000751 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000752 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000753 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000754 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000755
756 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000757 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000758 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000759
Abramo Bagnara6150c882010-05-11 21:36:43 +0000760 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
761 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000762
763 // There is no such thing as an unnamed class template.
764 if (!Name) {
765 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000766 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000767 }
768
769 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000770 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000771 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000772 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000773 if (SS.isNotEmpty() && !SS.isInvalid()) {
774 SemanticContext = computeDeclContext(SS, true);
775 if (!SemanticContext) {
776 // FIXME: Produce a reasonable diagnostic here
777 return true;
778 }
Mike Stump11289f42009-09-09 15:08:12 +0000779
John McCall0b66eb32010-05-01 00:40:08 +0000780 if (RequireCompleteDeclContext(SS, SemanticContext))
781 return true;
782
John McCall27b18f82009-11-17 02:14:36 +0000783 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000784 } else {
785 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000786 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000787 }
Mike Stump11289f42009-09-09 15:08:12 +0000788
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000789 if (Previous.isAmbiguous())
790 return true;
791
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000792 NamedDecl *PrevDecl = 0;
793 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000794 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000795
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000796 // If there is a previous declaration with the same name, check
797 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000798 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000799 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000800
801 // We may have found the injected-class-name of a class template,
802 // class template partial specialization, or class template specialization.
803 // In these cases, grab the template that is being defined or specialized.
804 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
805 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
806 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
807 PrevClassTemplate
808 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
809 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
810 PrevClassTemplate
811 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
812 ->getSpecializedTemplate();
813 }
814 }
815
John McCalld43784f2009-12-18 11:25:59 +0000816 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000817 // C++ [namespace.memdef]p3:
818 // [...] When looking for a prior declaration of a class or a function
819 // declared as a friend, and when the name of the friend class or
820 // function is neither a qualified name nor a template-id, scopes outside
821 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000822 if (!SS.isSet()) {
823 DeclContext *OutermostContext = CurContext;
824 while (!OutermostContext->isFileContext())
825 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000826
Douglas Gregorb74b1032010-04-18 17:37:40 +0000827 if (PrevDecl &&
828 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
829 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
830 SemanticContext = PrevDecl->getDeclContext();
831 } else {
832 // Declarations in outer scopes don't matter. However, the outermost
833 // context we computed is the semantic context for our new
834 // declaration.
835 PrevDecl = PrevClassTemplate = 0;
836 SemanticContext = OutermostContext;
837 }
John McCall90d3bb92009-12-17 23:21:11 +0000838 }
Douglas Gregorb74b1032010-04-18 17:37:40 +0000839
John McCall90d3bb92009-12-17 23:21:11 +0000840 if (CurContext->isDependentContext()) {
841 // If this is a dependent context, we don't want to link the friend
842 // class template to the template in scope, because that would perform
843 // checking of the template parameter lists that can't be performed
844 // until the outer context is instantiated.
845 PrevDecl = PrevClassTemplate = 0;
846 }
847 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
848 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000849
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000850 if (PrevClassTemplate) {
851 // Ensure that the template parameter lists are compatible.
852 if (!TemplateParameterListsAreEqual(TemplateParams,
853 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000854 /*Complain=*/true,
855 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000856 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000857
858 // C++ [temp.class]p4:
859 // In a redeclaration, partial specialization, explicit
860 // specialization or explicit instantiation of a class template,
861 // the class-key shall agree in kind with the original class
862 // template declaration (7.1.5.3).
863 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000864 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000865 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000866 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000867 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000868 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000869 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000870 }
871
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000872 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000873 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000874 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000875 Diag(NameLoc, diag::err_redefinition) << Name;
876 Diag(Def->getLocation(), diag::note_previous_definition);
877 // FIXME: Would it make sense to try to "forget" the previous
878 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000879 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000880 }
881 }
882 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
883 // Maybe we will complain about the shadowed template parameter.
884 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
885 // Just pretend that we didn't see the previous declaration.
886 PrevDecl = 0;
887 } else if (PrevDecl) {
888 // C++ [temp]p5:
889 // A class template shall not have the same name as any other
890 // template, class, function, object, enumeration, enumerator,
891 // namespace, or type in the same scope (3.3), except as specified
892 // in (14.5.4).
893 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
894 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000895 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000896 }
897
Douglas Gregordba32632009-02-10 19:49:53 +0000898 // Check the template parameter list of this declaration, possibly
899 // merging in the template parameter list from the previous class
900 // template declaration.
901 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000902 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
903 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000904 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000905
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000906 if (SS.isSet()) {
907 // If the name of the template was qualified, we must be defining the
908 // template out-of-line.
909 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
910 !(TUK == TUK_Friend && CurContext->isDependentContext()))
911 Diag(NameLoc, diag::err_member_def_does_not_match)
912 << Name << SemanticContext << SS.getRange();
913 }
914
Mike Stump11289f42009-09-09 15:08:12 +0000915 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000916 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000917 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000918 PrevClassTemplate->getTemplatedDecl() : 0,
919 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000920 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000921
922 ClassTemplateDecl *NewTemplate
923 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
924 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000925 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000926 NewClass->setDescribedClassTemplate(NewTemplate);
927
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000928 // Build the type for the class template declaration now.
John McCalle78aac42010-03-10 03:28:59 +0000929 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
930 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000931 assert(T->isDependentType() && "Class template type is not dependent?");
932 (void)T;
933
Douglas Gregorcf915552009-10-13 16:30:37 +0000934 // If we are providing an explicit specialization of a member that is a
935 // class template, make a note of that.
936 if (PrevClassTemplate &&
937 PrevClassTemplate->getInstantiatedFromMemberTemplate())
938 PrevClassTemplate->setMemberSpecialization();
939
Anders Carlsson137108d2009-03-26 01:24:28 +0000940 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000941 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000942 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000943
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000944 // Set the lexical context of these templates
945 NewClass->setLexicalDeclContext(CurContext);
946 NewTemplate->setLexicalDeclContext(CurContext);
947
John McCall9bb74a52009-07-31 02:45:11 +0000948 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000949 NewClass->startDefinition();
950
951 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000952 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000953
John McCall27b5c252009-09-14 21:59:20 +0000954 if (TUK != TUK_Friend)
955 PushOnScopeChains(NewTemplate, S);
956 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000957 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000958 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000959 NewClass->setAccess(PrevClassTemplate->getAccess());
960 }
John McCall27b5c252009-09-14 21:59:20 +0000961
Douglas Gregor3dad8422009-09-26 06:47:28 +0000962 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
963 PrevClassTemplate != NULL);
964
John McCall27b5c252009-09-14 21:59:20 +0000965 // Friend templates are visible in fairly strange ways.
966 if (!CurContext->isDependentContext()) {
967 DeclContext *DC = SemanticContext->getLookupContext();
968 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
969 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
970 PushOnScopeChains(NewTemplate, EnclosingScope,
971 /* AddToContext = */ false);
972 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000973
974 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
975 NewClass->getLocation(),
976 NewTemplate,
977 /*FIXME:*/NewClass->getLocation());
978 Friend->setAccess(AS_public);
979 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000980 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000981
Douglas Gregordba32632009-02-10 19:49:53 +0000982 if (Invalid) {
983 NewTemplate->setInvalidDecl();
984 NewClass->setInvalidDecl();
985 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000986 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000987}
988
Douglas Gregored5731f2009-11-25 17:50:39 +0000989/// \brief Diagnose the presence of a default template argument on a
990/// template parameter, which is ill-formed in certain contexts.
991///
992/// \returns true if the default template argument should be dropped.
993static bool DiagnoseDefaultTemplateArgument(Sema &S,
994 Sema::TemplateParamListContext TPC,
995 SourceLocation ParamLoc,
996 SourceRange DefArgRange) {
997 switch (TPC) {
998 case Sema::TPC_ClassTemplate:
999 return false;
1000
1001 case Sema::TPC_FunctionTemplate:
1002 // C++ [temp.param]p9:
1003 // A default template-argument shall not be specified in a
1004 // function template declaration or a function template
1005 // definition [...]
1006 // (This sentence is not in C++0x, per DR226).
1007 if (!S.getLangOptions().CPlusPlus0x)
1008 S.Diag(ParamLoc,
1009 diag::err_template_parameter_default_in_function_template)
1010 << DefArgRange;
1011 return false;
1012
1013 case Sema::TPC_ClassTemplateMember:
1014 // C++0x [temp.param]p9:
1015 // A default template-argument shall not be specified in the
1016 // template-parameter-lists of the definition of a member of a
1017 // class template that appears outside of the member's class.
1018 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1019 << DefArgRange;
1020 return true;
1021
1022 case Sema::TPC_FriendFunctionTemplate:
1023 // C++ [temp.param]p9:
1024 // A default template-argument shall not be specified in a
1025 // friend template declaration.
1026 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1027 << DefArgRange;
1028 return true;
1029
1030 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1031 // for friend function templates if there is only a single
1032 // declaration (and it is a definition). Strange!
1033 }
1034
1035 return false;
1036}
1037
Douglas Gregordba32632009-02-10 19:49:53 +00001038/// \brief Checks the validity of a template parameter list, possibly
1039/// considering the template parameter list from a previous
1040/// declaration.
1041///
1042/// If an "old" template parameter list is provided, it must be
1043/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1044/// template parameter list.
1045///
1046/// \param NewParams Template parameter list for a new template
1047/// declaration. This template parameter list will be updated with any
1048/// default arguments that are carried through from the previous
1049/// template parameter list.
1050///
1051/// \param OldParams If provided, template parameter list from a
1052/// previous declaration of the same template. Default template
1053/// arguments will be merged from the old template parameter list to
1054/// the new template parameter list.
1055///
Douglas Gregored5731f2009-11-25 17:50:39 +00001056/// \param TPC Describes the context in which we are checking the given
1057/// template parameter list.
1058///
Douglas Gregordba32632009-02-10 19:49:53 +00001059/// \returns true if an error occurred, false otherwise.
1060bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001061 TemplateParameterList *OldParams,
1062 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001063 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001064
Douglas Gregordba32632009-02-10 19:49:53 +00001065 // C++ [temp.param]p10:
1066 // The set of default template-arguments available for use with a
1067 // template declaration or definition is obtained by merging the
1068 // default arguments from the definition (if in scope) and all
1069 // declarations in scope in the same way default function
1070 // arguments are (8.3.6).
1071 bool SawDefaultArgument = false;
1072 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001073
Anders Carlsson327865d2009-06-12 23:20:15 +00001074 bool SawParameterPack = false;
1075 SourceLocation ParameterPackLoc;
1076
Mike Stumpc89c8e32009-02-11 23:03:27 +00001077 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001078 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001079 if (OldParams)
1080 OldParam = OldParams->begin();
1081
1082 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1083 NewParamEnd = NewParams->end();
1084 NewParam != NewParamEnd; ++NewParam) {
1085 // Variables used to diagnose redundant default arguments
1086 bool RedundantDefaultArg = false;
1087 SourceLocation OldDefaultLoc;
1088 SourceLocation NewDefaultLoc;
1089
1090 // Variables used to diagnose missing default arguments
1091 bool MissingDefaultArg = false;
1092
Anders Carlsson327865d2009-06-12 23:20:15 +00001093 // C++0x [temp.param]p11:
1094 // If a template parameter of a class template is a template parameter pack,
1095 // it must be the last template parameter.
1096 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001097 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001098 diag::err_template_param_pack_must_be_last_template_parameter);
1099 Invalid = true;
1100 }
1101
Douglas Gregordba32632009-02-10 19:49:53 +00001102 if (TemplateTypeParmDecl *NewTypeParm
1103 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001104 // Check the presence of a default argument here.
1105 if (NewTypeParm->hasDefaultArgument() &&
1106 DiagnoseDefaultTemplateArgument(*this, TPC,
1107 NewTypeParm->getLocation(),
1108 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001109 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001110 NewTypeParm->removeDefaultArgument();
1111
1112 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001113 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001114 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001115
Anders Carlsson327865d2009-06-12 23:20:15 +00001116 if (NewTypeParm->isParameterPack()) {
1117 assert(!NewTypeParm->hasDefaultArgument() &&
1118 "Parameter packs can't have a default argument!");
1119 SawParameterPack = true;
1120 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001121 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001122 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001123 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1124 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1125 SawDefaultArgument = true;
1126 RedundantDefaultArg = true;
1127 PreviousDefaultArgLoc = NewDefaultLoc;
1128 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1129 // Merge the default argument from the old declaration to the
1130 // new declaration.
1131 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001132 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001133 true);
1134 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1135 } else if (NewTypeParm->hasDefaultArgument()) {
1136 SawDefaultArgument = true;
1137 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1138 } else if (SawDefaultArgument)
1139 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001140 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001141 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001142 // Check the presence of a default argument here.
1143 if (NewNonTypeParm->hasDefaultArgument() &&
1144 DiagnoseDefaultTemplateArgument(*this, TPC,
1145 NewNonTypeParm->getLocation(),
1146 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1147 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1148 NewNonTypeParm->setDefaultArgument(0);
1149 }
1150
Mike Stump12b8ce12009-08-04 21:02:39 +00001151 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001152 NonTypeTemplateParmDecl *OldNonTypeParm
1153 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001154 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001155 NewNonTypeParm->hasDefaultArgument()) {
1156 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1157 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1158 SawDefaultArgument = true;
1159 RedundantDefaultArg = true;
1160 PreviousDefaultArgLoc = NewDefaultLoc;
1161 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1162 // Merge the default argument from the old declaration to the
1163 // new declaration.
1164 SawDefaultArgument = true;
1165 // FIXME: We need to create a new kind of "default argument"
1166 // expression that points to a previous template template
1167 // parameter.
1168 NewNonTypeParm->setDefaultArgument(
1169 OldNonTypeParm->getDefaultArgument());
1170 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1171 } else if (NewNonTypeParm->hasDefaultArgument()) {
1172 SawDefaultArgument = true;
1173 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1174 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001175 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001176 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001177 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001178 TemplateTemplateParmDecl *NewTemplateParm
1179 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001180 if (NewTemplateParm->hasDefaultArgument() &&
1181 DiagnoseDefaultTemplateArgument(*this, TPC,
1182 NewTemplateParm->getLocation(),
1183 NewTemplateParm->getDefaultArgument().getSourceRange()))
1184 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1185
1186 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001187 TemplateTemplateParmDecl *OldTemplateParm
1188 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001189 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001190 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001191 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1192 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001193 SawDefaultArgument = true;
1194 RedundantDefaultArg = true;
1195 PreviousDefaultArgLoc = NewDefaultLoc;
1196 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1197 // Merge the default argument from the old declaration to the
1198 // new declaration.
1199 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001200 // FIXME: We need to create a new kind of "default argument" expression
1201 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001202 NewTemplateParm->setDefaultArgument(
1203 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001204 PreviousDefaultArgLoc
1205 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001206 } else if (NewTemplateParm->hasDefaultArgument()) {
1207 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001208 PreviousDefaultArgLoc
1209 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001210 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001211 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001212 }
1213
1214 if (RedundantDefaultArg) {
1215 // C++ [temp.param]p12:
1216 // A template-parameter shall not be given default arguments
1217 // by two different declarations in the same scope.
1218 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1219 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1220 Invalid = true;
1221 } else if (MissingDefaultArg) {
1222 // C++ [temp.param]p11:
1223 // If a template-parameter has a default template-argument,
1224 // all subsequent template-parameters shall have a default
1225 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001226 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001227 diag::err_template_param_default_arg_missing);
1228 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1229 Invalid = true;
1230 }
1231
1232 // If we have an old template parameter list that we're merging
1233 // in, move on to the next parameter.
1234 if (OldParams)
1235 ++OldParam;
1236 }
1237
1238 return Invalid;
1239}
Douglas Gregord32e0282009-02-09 23:23:08 +00001240
Mike Stump11289f42009-09-09 15:08:12 +00001241/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001242/// specifier, returning the template parameter list that applies to the
1243/// name.
1244///
1245/// \param DeclStartLoc the start of the declaration that has a scope
1246/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001247///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001248/// \param SS the scope specifier that will be matched to the given template
1249/// parameter lists. This scope specifier precedes a qualified name that is
1250/// being declared.
1251///
1252/// \param ParamLists the template parameter lists, from the outermost to the
1253/// innermost template parameter lists.
1254///
1255/// \param NumParamLists the number of template parameter lists in ParamLists.
1256///
John McCalle820e5e2010-04-13 20:37:33 +00001257/// \param IsFriend Whether to apply the slightly different rules for
1258/// matching template parameters to scope specifiers in friend
1259/// declarations.
1260///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001261/// \param IsExplicitSpecialization will be set true if the entity being
1262/// declared is an explicit specialization, false otherwise.
1263///
Mike Stump11289f42009-09-09 15:08:12 +00001264/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001265/// name that is preceded by the scope specifier @p SS. This template
1266/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001267/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001268/// template specialization), or may be NULL (if we were's declaring isn't
1269/// itself a template).
1270TemplateParameterList *
1271Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1272 const CXXScopeSpec &SS,
1273 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001274 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001275 bool IsFriend,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001276 bool &IsExplicitSpecialization) {
1277 IsExplicitSpecialization = false;
1278
Douglas Gregord8d297c2009-07-21 23:53:31 +00001279 // Find the template-ids that occur within the nested-name-specifier. These
1280 // template-ids will match up with the template parameter lists.
1281 llvm::SmallVector<const TemplateSpecializationType *, 4>
1282 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001283 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1284 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001285 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1286 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001287 const Type *T = NNS->getAsType();
1288 if (!T) break;
1289
1290 // C++0x [temp.expl.spec]p17:
1291 // A member or a member template may be nested within many
1292 // enclosing class templates. In an explicit specialization for
1293 // such a member, the member declaration shall be preceded by a
1294 // template<> for each enclosing class template that is
1295 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001296 //
1297 // Following the existing practice of GNU and EDG, we allow a typedef of a
1298 // template specialization type.
1299 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1300 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001301
Mike Stump11289f42009-09-09 15:08:12 +00001302 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001303 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001304 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1305 if (!Template)
1306 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001307
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001308 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001309 ClassTemplateSpecializationDecl *SpecDecl
1310 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1311 // If the nested name specifier refers to an explicit specialization,
1312 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001313 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1314 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001315 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001316 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001317 }
Mike Stump11289f42009-09-09 15:08:12 +00001318
Douglas Gregord8d297c2009-07-21 23:53:31 +00001319 TemplateIdsInSpecifier.push_back(SpecType);
1320 }
1321 }
Mike Stump11289f42009-09-09 15:08:12 +00001322
Douglas Gregord8d297c2009-07-21 23:53:31 +00001323 // Reverse the list of template-ids in the scope specifier, so that we can
1324 // more easily match up the template-ids and the template parameter lists.
1325 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001326
Douglas Gregord8d297c2009-07-21 23:53:31 +00001327 SourceLocation FirstTemplateLoc = DeclStartLoc;
1328 if (NumParamLists)
1329 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001330
Douglas Gregord8d297c2009-07-21 23:53:31 +00001331 // Match the template-ids found in the specifier to the template parameter
1332 // lists.
1333 unsigned Idx = 0;
1334 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1335 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001336 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1337 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001338 if (Idx >= NumParamLists) {
1339 // We have a template-id without a corresponding template parameter
1340 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001341
1342 // ...which is fine if this is a friend declaration.
1343 if (IsFriend) {
1344 IsExplicitSpecialization = true;
1345 break;
1346 }
1347
Douglas Gregord8d297c2009-07-21 23:53:31 +00001348 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001349 // FIXME: the location information here isn't great.
1350 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001351 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001352 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001353 << SS.getRange();
1354 } else {
1355 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1356 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001357 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001358 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001359 }
1360 return 0;
1361 }
Mike Stump11289f42009-09-09 15:08:12 +00001362
Douglas Gregord8d297c2009-07-21 23:53:31 +00001363 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001364 if (DependentTemplateId) {
John McCall2408e322010-04-27 00:57:59 +00001365 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00001366
John McCall2408e322010-04-27 00:57:59 +00001367 // Are there cases in (e.g.) friends where this won't match?
1368 if (const InjectedClassNameType *Injected
1369 = TemplateId->getAs<InjectedClassNameType>()) {
1370 CXXRecordDecl *Record = Injected->getDecl();
1371 if (ClassTemplatePartialSpecializationDecl *Partial =
1372 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1373 ExpectedTemplateParams = Partial->getTemplateParameters();
1374 else
1375 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1376 ->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001377 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001378
John McCall2408e322010-04-27 00:57:59 +00001379 if (ExpectedTemplateParams)
1380 TemplateParameterListsAreEqual(ParamLists[Idx],
1381 ExpectedTemplateParams,
1382 true, TPL_TemplateMatch);
1383
Douglas Gregored5731f2009-11-25 17:50:39 +00001384 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001385 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001386 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001387 diag::err_template_param_list_matches_nontemplate)
1388 << TemplateId
1389 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001390 else
1391 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001392 }
Mike Stump11289f42009-09-09 15:08:12 +00001393
Douglas Gregord8d297c2009-07-21 23:53:31 +00001394 // If there were at least as many template-ids as there were template
1395 // parameter lists, then there are no template parameter lists remaining for
1396 // the declaration itself.
1397 if (Idx >= NumParamLists)
1398 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001399
Douglas Gregord8d297c2009-07-21 23:53:31 +00001400 // If there were too many template parameter lists, complain about that now.
1401 if (Idx != NumParamLists - 1) {
1402 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001403 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001404 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001405 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1406 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001407 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1408 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001409
1410 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1411 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1412 diag::note_explicit_template_spec_does_not_need_header)
1413 << ExplicitSpecializationsInSpecifier.back();
1414 ExplicitSpecializationsInSpecifier.pop_back();
1415 }
1416
Douglas Gregord8d297c2009-07-21 23:53:31 +00001417 ++Idx;
1418 }
1419 }
Mike Stump11289f42009-09-09 15:08:12 +00001420
Douglas Gregord8d297c2009-07-21 23:53:31 +00001421 // Return the last template parameter list, which corresponds to the
1422 // entity being declared.
1423 return ParamLists[NumParamLists - 1];
1424}
1425
Douglas Gregordc572a32009-03-30 22:58:21 +00001426QualType Sema::CheckTemplateIdType(TemplateName Name,
1427 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001428 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001429 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001430 if (!Template) {
1431 // The template name does not resolve to a template, so we just
1432 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001433 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001434 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001435
Douglas Gregorc40290e2009-03-09 23:48:35 +00001436 // Check that the template argument list is well-formed for this
1437 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001438 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001439 TemplateArgs.size());
1440 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001441 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001442 return QualType();
1443
Mike Stump11289f42009-09-09 15:08:12 +00001444 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001445 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001446 "Converted template argument list is too short!");
1447
1448 QualType CanonType;
John McCall2408e322010-04-27 00:57:59 +00001449 bool IsCurrentInstantiation = false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001450
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001451 if (Name.isDependent() ||
1452 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001453 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001454 // This class template specialization is a dependent
1455 // type. Therefore, its canonical type is another class template
1456 // specialization type that contains all of the converted
1457 // arguments in canonical form. This ensures that, e.g., A<T> and
1458 // A<T, T> have identical types when A is declared as:
1459 //
1460 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001461 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001462 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001463 Converted.getFlatArguments(),
1464 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001465
Douglas Gregora8e02e72009-07-28 23:00:59 +00001466 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001467 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001468 // In the future, we need to teach getTemplateSpecializationType to only
1469 // build the canonical type and return that to us.
1470 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001471
1472 // This might work out to be a current instantiation, in which
1473 // case the canonical type needs to be the InjectedClassNameType.
1474 //
1475 // TODO: in theory this could be a simple hashtable lookup; most
1476 // changes to CurContext don't change the set of current
1477 // instantiations.
1478 if (isa<ClassTemplateDecl>(Template)) {
1479 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1480 // If we get out to a namespace, we're done.
1481 if (Ctx->isFileContext()) break;
1482
1483 // If this isn't a record, keep looking.
1484 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1485 if (!Record) continue;
1486
1487 // Look for one of the two cases with InjectedClassNameTypes
1488 // and check whether it's the same template.
1489 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1490 !Record->getDescribedClassTemplate())
1491 continue;
1492
1493 // Fetch the injected class name type and check whether its
1494 // injected type is equal to the type we just built.
1495 QualType ICNT = Context.getTypeDeclType(Record);
1496 QualType Injected = cast<InjectedClassNameType>(ICNT)
1497 ->getInjectedSpecializationType();
1498
1499 if (CanonType != Injected->getCanonicalTypeInternal())
1500 continue;
1501
1502 // If so, the canonical type of this TST is the injected
1503 // class name type of the record we just found.
1504 assert(ICNT.isCanonical());
1505 CanonType = ICNT;
1506 IsCurrentInstantiation = true;
1507 break;
1508 }
1509 }
Mike Stump11289f42009-09-09 15:08:12 +00001510 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001511 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001512 // Find the class template specialization declaration that
1513 // corresponds to these arguments.
1514 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001515 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001516 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001517 Converted.flatSize(),
1518 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001519 void *InsertPos = 0;
1520 ClassTemplateSpecializationDecl *Decl
1521 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1522 if (!Decl) {
1523 // This is the first time we have referenced this class template
1524 // specialization. Create the canonical declaration and add it to
1525 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001526 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001527 ClassTemplate->getTemplatedDecl()->getTagKind(),
1528 ClassTemplate->getDeclContext(),
1529 ClassTemplate->getLocation(),
1530 ClassTemplate,
1531 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001532 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1533 Decl->setLexicalDeclContext(CurContext);
1534 }
1535
1536 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001537 assert(isa<RecordType>(CanonType) &&
1538 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001539 }
Mike Stump11289f42009-09-09 15:08:12 +00001540
Douglas Gregorc40290e2009-03-09 23:48:35 +00001541 // Build the fully-sugared type for this class template
1542 // specialization, which refers back to the class template
1543 // specialization we created or found.
John McCall2408e322010-04-27 00:57:59 +00001544 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType,
1545 IsCurrentInstantiation);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001546}
1547
Douglas Gregor67a65642009-02-17 23:15:12 +00001548Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001549Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001550 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001551 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001552 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001553 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001554
Douglas Gregorc40290e2009-03-09 23:48:35 +00001555 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001556 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001557 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001558
John McCall6b51f282009-11-23 01:53:49 +00001559 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001560 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001561
1562 if (Result.isNull())
1563 return true;
1564
John McCallbcd03502009-12-07 02:54:59 +00001565 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001566 TemplateSpecializationTypeLoc TL
1567 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1568 TL.setTemplateNameLoc(TemplateLoc);
1569 TL.setLAngleLoc(LAngleLoc);
1570 TL.setRAngleLoc(RAngleLoc);
1571 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1572 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1573
1574 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001575}
John McCall06f6fe8d2009-09-04 01:14:41 +00001576
John McCalld8fe9af2009-09-08 17:47:29 +00001577Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1578 TagUseKind TUK,
1579 DeclSpec::TST TagSpec,
1580 SourceLocation TagLoc) {
1581 if (TypeResult.isInvalid())
1582 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001583
John McCall0ad16662009-10-29 08:12:44 +00001584 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001585 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001586 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001587
John McCalld8fe9af2009-09-08 17:47:29 +00001588 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001589 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001590
John McCalld8fe9af2009-09-08 17:47:29 +00001591 if (const RecordType *RT = Type->getAs<RecordType>()) {
1592 RecordDecl *D = RT->getDecl();
1593
1594 IdentifierInfo *Id = D->getIdentifier();
1595 assert(Id && "templated class must have an identifier");
1596
1597 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1598 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001599 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001600 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001601 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001602 }
1603 }
1604
Abramo Bagnara6150c882010-05-11 21:36:43 +00001605 ElaboratedTypeKeyword Keyword
1606 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1607 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001608
1609 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001610}
1611
John McCalle66edc12009-11-24 19:00:30 +00001612Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1613 LookupResult &R,
1614 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001615 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001616 // FIXME: Can we do any checking at this point? I guess we could check the
1617 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001618 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001619 // though.
John McCalle66edc12009-11-24 19:00:30 +00001620
1621 // These should be filtered out by our callers.
1622 assert(!R.empty() && "empty lookup results when building templateid");
1623 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1624
1625 NestedNameSpecifier *Qualifier = 0;
1626 SourceRange QualifierRange;
1627 if (SS.isSet()) {
1628 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1629 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001630 }
John McCall58cc69d2010-01-27 01:50:18 +00001631
1632 // We don't want lookup warnings at this point.
1633 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001634
John McCalle66edc12009-11-24 19:00:30 +00001635 bool Dependent
1636 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1637 &TemplateArgs);
1638 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001639 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001640 Qualifier, QualifierRange,
1641 R.getLookupName(), R.getNameLoc(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001642 RequiresADL, TemplateArgs,
1643 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001644
1645 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001646}
1647
John McCalle66edc12009-11-24 19:00:30 +00001648// We actually only call this from template instantiation.
1649Sema::OwningExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001650Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001651 DeclarationName Name,
1652 SourceLocation NameLoc,
1653 const TemplateArgumentListInfo &TemplateArgs) {
1654 DeclContext *DC;
1655 if (!(DC = computeDeclContext(SS, false)) ||
1656 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001657 RequireCompleteDeclContext(SS, DC))
John McCalle66edc12009-11-24 19:00:30 +00001658 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001659
Douglas Gregor786123d2010-05-21 23:18:07 +00001660 bool MemberOfUnknownSpecialization;
John McCalle66edc12009-11-24 19:00:30 +00001661 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00001662 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1663 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00001664
John McCalle66edc12009-11-24 19:00:30 +00001665 if (R.isAmbiguous())
1666 return ExprError();
1667
1668 if (R.empty()) {
1669 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1670 << Name << SS.getRange();
1671 return ExprError();
1672 }
1673
1674 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1675 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1676 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1677 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1678 return ExprError();
1679 }
1680
1681 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001682}
1683
Douglas Gregorb67535d2009-03-31 00:43:58 +00001684/// \brief Form a dependent template name.
1685///
1686/// This action forms a dependent template name given the template
1687/// name and its (presumably dependent) scope specifier. For
1688/// example, given "MetaFun::template apply", the scope specifier \p
1689/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1690/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001691Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001692Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001693 CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001694 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001695 TypeTy *ObjectType,
1696 bool EnteringContext) {
Douglas Gregor9abe2372010-01-19 16:01:07 +00001697 DeclContext *LookupCtx = 0;
1698 if (SS.isSet())
1699 LookupCtx = computeDeclContext(SS, EnteringContext);
1700 if (!LookupCtx && ObjectType)
1701 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1702 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001703 // C++0x [temp.names]p5:
1704 // If a name prefixed by the keyword template is not the name of
1705 // a template, the program is ill-formed. [Note: the keyword
1706 // template may not be applied to non-template members of class
1707 // templates. -end note ] [ Note: as is the case with the
1708 // typename prefix, the template prefix is allowed in cases
1709 // where it is not strictly necessary; i.e., when the
1710 // nested-name-specifier or the expression on the left of the ->
1711 // or . is not dependent on a template-parameter, or the use
1712 // does not appear in the scope of a template. -end note]
1713 //
1714 // Note: C++03 was more strict here, because it banned the use of
1715 // the "template" keyword prior to a template-name that was not a
1716 // dependent name. C++ DR468 relaxed this requirement (the
1717 // "template" keyword is now permitted). We follow the C++0x
1718 // rules, even in C++03 mode, retroactively applying the DR.
1719 TemplateTy Template;
Douglas Gregor786123d2010-05-21 23:18:07 +00001720 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001721 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00001722 EnteringContext, Template,
1723 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001724 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1725 isa<CXXRecordDecl>(LookupCtx) &&
1726 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00001727 // This is a dependent template.
1728 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001729 Diag(Name.getSourceRange().getBegin(),
1730 diag::err_template_kw_refers_to_non_template)
1731 << GetNameFromUnqualifiedId(Name)
Douglas Gregorb22ee882010-05-05 05:58:24 +00001732 << Name.getSourceRange()
1733 << TemplateKWLoc;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001734 return TemplateTy();
Douglas Gregord2e6a452010-01-14 17:47:39 +00001735 } else {
1736 // We found something; return it.
1737 return Template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001738 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001739 }
1740
Mike Stump11289f42009-09-09 15:08:12 +00001741 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001742 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001743
1744 switch (Name.getKind()) {
1745 case UnqualifiedId::IK_Identifier:
1746 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1747 Name.Identifier));
1748
Douglas Gregor71395fa2009-11-04 00:56:37 +00001749 case UnqualifiedId::IK_OperatorFunctionId:
1750 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1751 Name.OperatorFunctionId.Operator));
Alexis Hunted0530f2009-11-28 08:58:14 +00001752
1753 case UnqualifiedId::IK_LiteralOperatorId:
1754 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1755
Douglas Gregor3cf81312009-11-03 23:16:33 +00001756 default:
1757 break;
1758 }
1759
1760 Diag(Name.getSourceRange().getBegin(),
1761 diag::err_template_kw_refers_to_non_template)
1762 << GetNameFromUnqualifiedId(Name)
Douglas Gregorb22ee882010-05-05 05:58:24 +00001763 << Name.getSourceRange()
1764 << TemplateKWLoc;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001765 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001766}
1767
Mike Stump11289f42009-09-09 15:08:12 +00001768bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001769 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001770 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001771 const TemplateArgument &Arg = AL.getArgument();
1772
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001773 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001774 switch(Arg.getKind()) {
1775 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001776 // C++ [temp.arg.type]p1:
1777 // A template-argument for a template-parameter which is a
1778 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001779 break;
1780 case TemplateArgument::Template: {
1781 // We have a template type parameter but the template argument
1782 // is a template without any arguments.
1783 SourceRange SR = AL.getSourceRange();
1784 TemplateName Name = Arg.getAsTemplate();
1785 Diag(SR.getBegin(), diag::err_template_missing_args)
1786 << Name << SR;
1787 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1788 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001789
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001790 return true;
1791 }
1792 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001793 // We have a template type parameter but the template argument
1794 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001795 SourceRange SR = AL.getSourceRange();
1796 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001797 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001798
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001799 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001800 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001801 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001802
John McCallbcd03502009-12-07 02:54:59 +00001803 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001804 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001805
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001806 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001807 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001808 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001809 return false;
1810}
1811
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001812/// \brief Substitute template arguments into the default template argument for
1813/// the given template type parameter.
1814///
1815/// \param SemaRef the semantic analysis object for which we are performing
1816/// the substitution.
1817///
1818/// \param Template the template that we are synthesizing template arguments
1819/// for.
1820///
1821/// \param TemplateLoc the location of the template name that started the
1822/// template-id we are checking.
1823///
1824/// \param RAngleLoc the location of the right angle bracket ('>') that
1825/// terminates the template-id.
1826///
1827/// \param Param the template template parameter whose default we are
1828/// substituting into.
1829///
1830/// \param Converted the list of template arguments provided for template
1831/// parameters that precede \p Param in the template parameter list.
1832///
1833/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001834static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001835SubstDefaultTemplateArgument(Sema &SemaRef,
1836 TemplateDecl *Template,
1837 SourceLocation TemplateLoc,
1838 SourceLocation RAngleLoc,
1839 TemplateTypeParmDecl *Param,
1840 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001841 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001842
1843 // If the argument type is dependent, instantiate it now based
1844 // on the previously-computed template arguments.
1845 if (ArgType->getType()->isDependentType()) {
1846 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1847 /*TakeArgs=*/false);
1848
1849 MultiLevelTemplateArgumentList AllTemplateArgs
1850 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1851
1852 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1853 Template, Converted.getFlatArguments(),
1854 Converted.flatSize(),
1855 SourceRange(TemplateLoc, RAngleLoc));
1856
1857 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1858 Param->getDefaultArgumentLoc(),
1859 Param->getDeclName());
1860 }
1861
1862 return ArgType;
1863}
1864
1865/// \brief Substitute template arguments into the default template argument for
1866/// the given non-type template parameter.
1867///
1868/// \param SemaRef the semantic analysis object for which we are performing
1869/// the substitution.
1870///
1871/// \param Template the template that we are synthesizing template arguments
1872/// for.
1873///
1874/// \param TemplateLoc the location of the template name that started the
1875/// template-id we are checking.
1876///
1877/// \param RAngleLoc the location of the right angle bracket ('>') that
1878/// terminates the template-id.
1879///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001880/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001881/// substituting into.
1882///
1883/// \param Converted the list of template arguments provided for template
1884/// parameters that precede \p Param in the template parameter list.
1885///
1886/// \returns the substituted template argument, or NULL if an error occurred.
1887static Sema::OwningExprResult
1888SubstDefaultTemplateArgument(Sema &SemaRef,
1889 TemplateDecl *Template,
1890 SourceLocation TemplateLoc,
1891 SourceLocation RAngleLoc,
1892 NonTypeTemplateParmDecl *Param,
1893 TemplateArgumentListBuilder &Converted) {
1894 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1895 /*TakeArgs=*/false);
1896
1897 MultiLevelTemplateArgumentList AllTemplateArgs
1898 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1899
1900 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1901 Template, Converted.getFlatArguments(),
1902 Converted.flatSize(),
1903 SourceRange(TemplateLoc, RAngleLoc));
1904
1905 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1906}
1907
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001908/// \brief Substitute template arguments into the default template argument for
1909/// the given template template parameter.
1910///
1911/// \param SemaRef the semantic analysis object for which we are performing
1912/// the substitution.
1913///
1914/// \param Template the template that we are synthesizing template arguments
1915/// for.
1916///
1917/// \param TemplateLoc the location of the template name that started the
1918/// template-id we are checking.
1919///
1920/// \param RAngleLoc the location of the right angle bracket ('>') that
1921/// terminates the template-id.
1922///
1923/// \param Param the template template parameter whose default we are
1924/// substituting into.
1925///
1926/// \param Converted the list of template arguments provided for template
1927/// parameters that precede \p Param in the template parameter list.
1928///
1929/// \returns the substituted template argument, or NULL if an error occurred.
1930static TemplateName
1931SubstDefaultTemplateArgument(Sema &SemaRef,
1932 TemplateDecl *Template,
1933 SourceLocation TemplateLoc,
1934 SourceLocation RAngleLoc,
1935 TemplateTemplateParmDecl *Param,
1936 TemplateArgumentListBuilder &Converted) {
1937 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1938 /*TakeArgs=*/false);
1939
1940 MultiLevelTemplateArgumentList AllTemplateArgs
1941 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1942
1943 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1944 Template, Converted.getFlatArguments(),
1945 Converted.flatSize(),
1946 SourceRange(TemplateLoc, RAngleLoc));
1947
1948 return SemaRef.SubstTemplateName(
1949 Param->getDefaultArgument().getArgument().getAsTemplate(),
1950 Param->getDefaultArgument().getTemplateNameLoc(),
1951 AllTemplateArgs);
1952}
1953
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001954/// \brief If the given template parameter has a default template
1955/// argument, substitute into that default template argument and
1956/// return the corresponding template argument.
1957TemplateArgumentLoc
1958Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1959 SourceLocation TemplateLoc,
1960 SourceLocation RAngleLoc,
1961 Decl *Param,
1962 TemplateArgumentListBuilder &Converted) {
1963 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1964 if (!TypeParm->hasDefaultArgument())
1965 return TemplateArgumentLoc();
1966
John McCallbcd03502009-12-07 02:54:59 +00001967 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001968 TemplateLoc,
1969 RAngleLoc,
1970 TypeParm,
1971 Converted);
1972 if (DI)
1973 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1974
1975 return TemplateArgumentLoc();
1976 }
1977
1978 if (NonTypeTemplateParmDecl *NonTypeParm
1979 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1980 if (!NonTypeParm->hasDefaultArgument())
1981 return TemplateArgumentLoc();
1982
1983 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1984 TemplateLoc,
1985 RAngleLoc,
1986 NonTypeParm,
1987 Converted);
1988 if (Arg.isInvalid())
1989 return TemplateArgumentLoc();
1990
1991 Expr *ArgE = Arg.takeAs<Expr>();
1992 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1993 }
1994
1995 TemplateTemplateParmDecl *TempTempParm
1996 = cast<TemplateTemplateParmDecl>(Param);
1997 if (!TempTempParm->hasDefaultArgument())
1998 return TemplateArgumentLoc();
1999
2000 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2001 TemplateLoc,
2002 RAngleLoc,
2003 TempTempParm,
2004 Converted);
2005 if (TName.isNull())
2006 return TemplateArgumentLoc();
2007
2008 return TemplateArgumentLoc(TemplateArgument(TName),
2009 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2010 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2011}
2012
Douglas Gregorda0fb532009-11-11 19:31:23 +00002013/// \brief Check that the given template argument corresponds to the given
2014/// template parameter.
2015bool Sema::CheckTemplateArgument(NamedDecl *Param,
2016 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002017 TemplateDecl *Template,
2018 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002019 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002020 TemplateArgumentListBuilder &Converted,
2021 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00002022 // Check template type parameters.
2023 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002024 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002025
Douglas Gregoreebed722009-11-11 19:41:09 +00002026 // Check non-type template parameters.
2027 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00002028 // Do substitution on the type of the non-type template parameter
2029 // with the template arguments we've seen thus far.
2030 QualType NTTPType = NTTP->getType();
2031 if (NTTPType->isDependentType()) {
2032 // Do substitution on the type of the non-type template parameter.
2033 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2034 NTTP, Converted.getFlatArguments(),
2035 Converted.flatSize(),
2036 SourceRange(TemplateLoc, RAngleLoc));
2037
2038 TemplateArgumentList TemplateArgs(Context, Converted,
2039 /*TakeArgs=*/false);
2040 NTTPType = SubstType(NTTPType,
2041 MultiLevelTemplateArgumentList(TemplateArgs),
2042 NTTP->getLocation(),
2043 NTTP->getDeclName());
2044 // If that worked, check the non-type template parameter type
2045 // for validity.
2046 if (!NTTPType.isNull())
2047 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2048 NTTP->getLocation());
2049 if (NTTPType.isNull())
2050 return true;
2051 }
2052
2053 switch (Arg.getArgument().getKind()) {
2054 case TemplateArgument::Null:
2055 assert(false && "Should never see a NULL template argument here");
2056 return true;
2057
2058 case TemplateArgument::Expression: {
2059 Expr *E = Arg.getArgument().getAsExpr();
2060 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002061 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002062 return true;
2063
2064 Converted.Append(Result);
2065 break;
2066 }
2067
2068 case TemplateArgument::Declaration:
2069 case TemplateArgument::Integral:
2070 // We've already checked this template argument, so just copy
2071 // it to the list of converted arguments.
2072 Converted.Append(Arg.getArgument());
2073 break;
2074
2075 case TemplateArgument::Template:
2076 // We were given a template template argument. It may not be ill-formed;
2077 // see below.
2078 if (DependentTemplateName *DTN
2079 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2080 // We have a template argument such as \c T::template X, which we
2081 // parsed as a template template argument. However, since we now
2082 // know that we need a non-type template argument, convert this
2083 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00002084 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2085 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002086 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00002087 DTN->getIdentifier(),
2088 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00002089
2090 TemplateArgument Result;
2091 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2092 return true;
2093
2094 Converted.Append(Result);
2095 break;
2096 }
2097
2098 // We have a template argument that actually does refer to a class
2099 // template, template alias, or template template parameter, and
2100 // therefore cannot be a non-type template argument.
2101 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2102 << Arg.getSourceRange();
2103
2104 Diag(Param->getLocation(), diag::note_template_param_here);
2105 return true;
2106
2107 case TemplateArgument::Type: {
2108 // We have a non-type template parameter but the template
2109 // argument is a type.
2110
2111 // C++ [temp.arg]p2:
2112 // In a template-argument, an ambiguity between a type-id and
2113 // an expression is resolved to a type-id, regardless of the
2114 // form of the corresponding template-parameter.
2115 //
2116 // We warn specifically about this case, since it can be rather
2117 // confusing for users.
2118 QualType T = Arg.getArgument().getAsType();
2119 SourceRange SR = Arg.getSourceRange();
2120 if (T->isFunctionType())
2121 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2122 else
2123 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2124 Diag(Param->getLocation(), diag::note_template_param_here);
2125 return true;
2126 }
2127
2128 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002129 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002130 break;
2131 }
2132
2133 return false;
2134 }
2135
2136
2137 // Check template template parameters.
2138 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2139
2140 // Substitute into the template parameter list of the template
2141 // template parameter, since previously-supplied template arguments
2142 // may appear within the template template parameter.
2143 {
2144 // Set up a template instantiation context.
2145 LocalInstantiationScope Scope(*this);
2146 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2147 TempParm, Converted.getFlatArguments(),
2148 Converted.flatSize(),
2149 SourceRange(TemplateLoc, RAngleLoc));
2150
2151 TemplateArgumentList TemplateArgs(Context, Converted,
2152 /*TakeArgs=*/false);
2153 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2154 SubstDecl(TempParm, CurContext,
2155 MultiLevelTemplateArgumentList(TemplateArgs)));
2156 if (!TempParm)
2157 return true;
2158
2159 // FIXME: TempParam is leaked.
2160 }
2161
2162 switch (Arg.getArgument().getKind()) {
2163 case TemplateArgument::Null:
2164 assert(false && "Should never see a NULL template argument here");
2165 return true;
2166
2167 case TemplateArgument::Template:
2168 if (CheckTemplateArgument(TempParm, Arg))
2169 return true;
2170
2171 Converted.Append(Arg.getArgument());
2172 break;
2173
2174 case TemplateArgument::Expression:
2175 case TemplateArgument::Type:
2176 // We have a template template parameter but the template
2177 // argument does not refer to a template.
2178 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2179 return true;
2180
2181 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002182 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002183 "Declaration argument with template template parameter");
2184 break;
2185 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002186 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002187 "Integral argument with template template parameter");
2188 break;
2189
2190 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002191 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002192 break;
2193 }
2194
2195 return false;
2196}
2197
Douglas Gregord32e0282009-02-09 23:23:08 +00002198/// \brief Check that the given template argument list is well-formed
2199/// for specializing the given template.
2200bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2201 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002202 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002203 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002204 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002205 TemplateParameterList *Params = Template->getTemplateParameters();
2206 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002207 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002208 bool Invalid = false;
2209
John McCall6b51f282009-11-23 01:53:49 +00002210 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2211
Mike Stump11289f42009-09-09 15:08:12 +00002212 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002213 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002214
Anders Carlsson15201f12009-06-13 02:08:00 +00002215 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002216 (NumArgs < Params->getMinRequiredArguments() &&
2217 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002218 // FIXME: point at either the first arg beyond what we can handle,
2219 // or the '>', depending on whether we have too many or too few
2220 // arguments.
2221 SourceRange Range;
2222 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002223 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002224 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2225 << (NumArgs > NumParams)
2226 << (isa<ClassTemplateDecl>(Template)? 0 :
2227 isa<FunctionTemplateDecl>(Template)? 1 :
2228 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2229 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002230 Diag(Template->getLocation(), diag::note_template_decl_here)
2231 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002232 Invalid = true;
2233 }
Mike Stump11289f42009-09-09 15:08:12 +00002234
2235 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002236 // [...] The type and form of each template-argument specified in
2237 // a template-id shall match the type and form specified for the
2238 // corresponding parameter declared by the template in its
2239 // template-parameter-list.
2240 unsigned ArgIdx = 0;
2241 for (TemplateParameterList::iterator Param = Params->begin(),
2242 ParamEnd = Params->end();
2243 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002244 if (ArgIdx > NumArgs && PartialTemplateArgs)
2245 break;
Mike Stump11289f42009-09-09 15:08:12 +00002246
Douglas Gregoreebed722009-11-11 19:41:09 +00002247 // If we have a template parameter pack, check every remaining template
2248 // argument against that template parameter pack.
2249 if ((*Param)->isTemplateParameterPack()) {
2250 Converted.BeginPack();
2251 for (; ArgIdx < NumArgs; ++ArgIdx) {
2252 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2253 TemplateLoc, RAngleLoc, Converted)) {
2254 Invalid = true;
2255 break;
2256 }
2257 }
2258 Converted.EndPack();
2259 continue;
2260 }
2261
Douglas Gregor84d49a22009-11-11 21:54:23 +00002262 if (ArgIdx < NumArgs) {
2263 // Check the template argument we were given.
2264 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2265 TemplateLoc, RAngleLoc, Converted))
2266 return true;
2267
2268 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002269 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002270
Douglas Gregor84d49a22009-11-11 21:54:23 +00002271 // We have a default template argument that we will use.
2272 TemplateArgumentLoc Arg;
2273
2274 // Retrieve the default template argument from the template
2275 // parameter. For each kind of template parameter, we substitute the
2276 // template arguments provided thus far and any "outer" template arguments
2277 // (when the template parameter was part of a nested template) into
2278 // the default argument.
2279 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2280 if (!TTP->hasDefaultArgument()) {
2281 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2282 break;
2283 }
2284
John McCallbcd03502009-12-07 02:54:59 +00002285 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002286 Template,
2287 TemplateLoc,
2288 RAngleLoc,
2289 TTP,
2290 Converted);
2291 if (!ArgType)
2292 return true;
2293
2294 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2295 ArgType);
2296 } else if (NonTypeTemplateParmDecl *NTTP
2297 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2298 if (!NTTP->hasDefaultArgument()) {
2299 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2300 break;
2301 }
2302
2303 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2304 TemplateLoc,
2305 RAngleLoc,
2306 NTTP,
2307 Converted);
2308 if (E.isInvalid())
2309 return true;
2310
2311 Expr *Ex = E.takeAs<Expr>();
2312 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2313 } else {
2314 TemplateTemplateParmDecl *TempParm
2315 = cast<TemplateTemplateParmDecl>(*Param);
2316
2317 if (!TempParm->hasDefaultArgument()) {
2318 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2319 break;
2320 }
2321
2322 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2323 TemplateLoc,
2324 RAngleLoc,
2325 TempParm,
2326 Converted);
2327 if (Name.isNull())
2328 return true;
2329
2330 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2331 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2332 TempParm->getDefaultArgument().getTemplateNameLoc());
2333 }
2334
2335 // Introduce an instantiation record that describes where we are using
2336 // the default template argument.
2337 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2338 Converted.getFlatArguments(),
2339 Converted.flatSize(),
2340 SourceRange(TemplateLoc, RAngleLoc));
2341
2342 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002343 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002344 RAngleLoc, Converted))
2345 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002346 }
2347
2348 return Invalid;
2349}
2350
2351/// \brief Check a template argument against its corresponding
2352/// template type parameter.
2353///
2354/// This routine implements the semantics of C++ [temp.arg.type]. It
2355/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002356bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002357 TypeSourceInfo *ArgInfo) {
2358 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002359 QualType Arg = ArgInfo->getType();
2360
Douglas Gregord32e0282009-02-09 23:23:08 +00002361 // C++ [temp.arg.type]p2:
2362 // A local type, a type with no linkage, an unnamed type or a type
2363 // compounded from any of these types shall not be used as a
2364 // template-argument for a template type-parameter.
2365 //
Douglas Gregor959d5a02010-05-22 16:17:30 +00002366 // FIXME: Perform the unnamed type check.
2367 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002368 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002369 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002370 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002371 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002372 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002373 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002374 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall0ad16662009-10-29 08:12:44 +00002375 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2376 << QualType(Tag, 0) << SR;
2377 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002378 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002379 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002380 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2381 return true;
Douglas Gregor959d5a02010-05-22 16:17:30 +00002382 } else if (Arg->isVariablyModifiedType()) {
2383 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2384 << Arg;
2385 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002386 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002387 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002388 }
2389
2390 return false;
2391}
2392
Douglas Gregorccb07762009-02-11 19:52:55 +00002393/// \brief Checks whether the given template argument is the address
2394/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002395static bool
2396CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2397 NonTypeTemplateParmDecl *Param,
2398 QualType ParamType,
2399 Expr *ArgIn,
2400 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002401 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002402 Expr *Arg = ArgIn;
2403 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002404
2405 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002406 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002407 Arg = Cast->getSubExpr();
2408
2409 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002410 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002411 // A template-argument for a non-type, non-template
2412 // template-parameter shall be one of: [...]
2413 //
2414 // -- the address of an object or function with external
2415 // linkage, including function templates and function
2416 // template-ids but excluding non-static class members,
2417 // expressed as & id-expression where the & is optional if
2418 // the name refers to a function or array, or if the
2419 // corresponding template-parameter is a reference; or
2420 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002421
Douglas Gregorccb07762009-02-11 19:52:55 +00002422 // Ignore (and complain about) any excess parentheses.
2423 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2424 if (!Invalid) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002425 S.Diag(Arg->getSourceRange().getBegin(),
2426 diag::err_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002427 << Arg->getSourceRange();
2428 Invalid = true;
2429 }
2430
2431 Arg = Parens->getSubExpr();
2432 }
2433
Douglas Gregorb242683d2010-04-01 18:32:35 +00002434 bool AddressTaken = false;
2435 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002436 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002437 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002438 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002439 AddressTaken = true;
2440 AddrOpLoc = UnOp->getOperatorLoc();
2441 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002442 } else
2443 DRE = dyn_cast<DeclRefExpr>(Arg);
2444
Douglas Gregorb242683d2010-04-01 18:32:35 +00002445 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002446 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2447 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002448 S.Diag(Param->getLocation(), diag::note_template_param_here);
2449 return true;
2450 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002451
2452 // Stop checking the precise nature of the argument if it is value dependent,
2453 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002454 if (Arg->isValueDependent()) {
2455 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002456 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002457 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002458
Douglas Gregorb242683d2010-04-01 18:32:35 +00002459 if (!isa<ValueDecl>(DRE->getDecl())) {
2460 S.Diag(Arg->getSourceRange().getBegin(),
2461 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002462 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002463 S.Diag(Param->getLocation(), diag::note_template_param_here);
2464 return true;
2465 }
2466
2467 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002468
2469 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002470 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2471 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002472 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002473 S.Diag(Param->getLocation(), diag::note_template_param_here);
2474 return true;
2475 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002476
2477 // Cannot refer to non-static member functions
2478 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002479 if (!Method->isStatic()) {
2480 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002481 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002482 S.Diag(Param->getLocation(), diag::note_template_param_here);
2483 return true;
2484 }
Mike Stump11289f42009-09-09 15:08:12 +00002485
Douglas Gregorccb07762009-02-11 19:52:55 +00002486 // Functions must have external linkage.
2487 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002488 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002489 S.Diag(Arg->getSourceRange().getBegin(),
2490 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002491 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002492 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002493 << true;
2494 return true;
2495 }
2496
2497 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002498 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002499
Douglas Gregorb242683d2010-04-01 18:32:35 +00002500 // If the template parameter has pointer type, the function decays.
2501 if (ParamType->isPointerType() && !AddressTaken)
2502 ArgType = S.Context.getPointerType(Func->getType());
2503 else if (AddressTaken && ParamType->isReferenceType()) {
2504 // If we originally had an address-of operator, but the
2505 // parameter has reference type, complain and (if things look
2506 // like they will work) drop the address-of operator.
2507 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2508 ParamType.getNonReferenceType())) {
2509 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2510 << ParamType;
2511 S.Diag(Param->getLocation(), diag::note_template_param_here);
2512 return true;
2513 }
2514
2515 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2516 << ParamType
2517 << FixItHint::CreateRemoval(AddrOpLoc);
2518 S.Diag(Param->getLocation(), diag::note_template_param_here);
2519
2520 ArgType = Func->getType();
2521 }
2522 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002523 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002524 S.Diag(Arg->getSourceRange().getBegin(),
2525 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002526 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002527 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002528 << true;
2529 return true;
2530 }
2531
Douglas Gregorb242683d2010-04-01 18:32:35 +00002532 // A value of reference type is not an object.
2533 if (Var->getType()->isReferenceType()) {
2534 S.Diag(Arg->getSourceRange().getBegin(),
2535 diag::err_template_arg_reference_var)
2536 << Var->getType() << Arg->getSourceRange();
2537 S.Diag(Param->getLocation(), diag::note_template_param_here);
2538 return true;
2539 }
2540
Douglas Gregorccb07762009-02-11 19:52:55 +00002541 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002542 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002543
2544 // If the template parameter has pointer type, we must have taken
2545 // the address of this object.
2546 if (ParamType->isReferenceType()) {
2547 if (AddressTaken) {
2548 // If we originally had an address-of operator, but the
2549 // parameter has reference type, complain and (if things look
2550 // like they will work) drop the address-of operator.
2551 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2552 ParamType.getNonReferenceType())) {
2553 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2554 << ParamType;
2555 S.Diag(Param->getLocation(), diag::note_template_param_here);
2556 return true;
2557 }
2558
2559 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2560 << ParamType
2561 << FixItHint::CreateRemoval(AddrOpLoc);
2562 S.Diag(Param->getLocation(), diag::note_template_param_here);
2563
2564 ArgType = Var->getType();
2565 }
2566 } else if (!AddressTaken && ParamType->isPointerType()) {
2567 if (Var->getType()->isArrayType()) {
2568 // Array-to-pointer decay.
2569 ArgType = S.Context.getArrayDecayedType(Var->getType());
2570 } else {
2571 // If the template parameter has pointer type but the address of
2572 // this object was not taken, complain and (possibly) recover by
2573 // taking the address of the entity.
2574 ArgType = S.Context.getPointerType(Var->getType());
2575 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2576 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2577 << ParamType;
2578 S.Diag(Param->getLocation(), diag::note_template_param_here);
2579 return true;
2580 }
2581
2582 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2583 << ParamType
2584 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2585
2586 S.Diag(Param->getLocation(), diag::note_template_param_here);
2587 }
2588 }
2589 } else {
2590 // We found something else, but we don't know specifically what it is.
2591 S.Diag(Arg->getSourceRange().getBegin(),
2592 diag::err_template_arg_not_object_or_func)
2593 << Arg->getSourceRange();
2594 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2595 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002596 }
Mike Stump11289f42009-09-09 15:08:12 +00002597
Douglas Gregorb242683d2010-04-01 18:32:35 +00002598 if (ParamType->isPointerType() &&
2599 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2600 S.IsQualificationConversion(ArgType, ParamType)) {
2601 // For pointer-to-object types, qualification conversions are
2602 // permitted.
2603 } else {
2604 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2605 if (!ParamRef->getPointeeType()->isFunctionType()) {
2606 // C++ [temp.arg.nontype]p5b3:
2607 // For a non-type template-parameter of type reference to
2608 // object, no conversions apply. The type referred to by the
2609 // reference may be more cv-qualified than the (otherwise
2610 // identical) type of the template- argument. The
2611 // template-parameter is bound directly to the
2612 // template-argument, which shall be an lvalue.
2613
2614 // FIXME: Other qualifiers?
2615 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2616 unsigned ArgQuals = ArgType.getCVRQualifiers();
2617
2618 if ((ParamQuals | ArgQuals) != ParamQuals) {
2619 S.Diag(Arg->getSourceRange().getBegin(),
2620 diag::err_template_arg_ref_bind_ignores_quals)
2621 << ParamType << Arg->getType()
2622 << Arg->getSourceRange();
2623 S.Diag(Param->getLocation(), diag::note_template_param_here);
2624 return true;
2625 }
2626 }
2627 }
2628
2629 // At this point, the template argument refers to an object or
2630 // function with external linkage. We now need to check whether the
2631 // argument and parameter types are compatible.
2632 if (!S.Context.hasSameUnqualifiedType(ArgType,
2633 ParamType.getNonReferenceType())) {
2634 // We can't perform this conversion or binding.
2635 if (ParamType->isReferenceType())
2636 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2637 << ParamType << Arg->getType() << Arg->getSourceRange();
2638 else
2639 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2640 << Arg->getType() << ParamType << Arg->getSourceRange();
2641 S.Diag(Param->getLocation(), diag::note_template_param_here);
2642 return true;
2643 }
2644 }
2645
2646 // Create the template argument.
2647 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002648 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002649 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002650}
2651
2652/// \brief Checks whether the given template argument is a pointer to
2653/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002654bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2655 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002656 bool Invalid = false;
2657
2658 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002659 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002660 Arg = Cast->getSubExpr();
2661
2662 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002663 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002664 // A template-argument for a non-type, non-template
2665 // template-parameter shall be one of: [...]
2666 //
2667 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002668 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002669
2670 // Ignore (and complain about) any excess parentheses.
2671 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2672 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002673 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002674 diag::err_template_arg_extra_parens)
2675 << Arg->getSourceRange();
2676 Invalid = true;
2677 }
2678
2679 Arg = Parens->getSubExpr();
2680 }
2681
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002682 // A pointer-to-member constant written &Class::member.
2683 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002684 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2685 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2686 if (DRE && !DRE->getQualifier())
2687 DRE = 0;
2688 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002689 }
2690 // A constant of pointer-to-member type.
2691 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2692 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2693 if (VD->getType()->isMemberPointerType()) {
2694 if (isa<NonTypeTemplateParmDecl>(VD) ||
2695 (isa<VarDecl>(VD) &&
2696 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2697 if (Arg->isTypeDependent() || Arg->isValueDependent())
2698 Converted = TemplateArgument(Arg->Retain());
2699 else
2700 Converted = TemplateArgument(VD->getCanonicalDecl());
2701 return Invalid;
2702 }
2703 }
2704 }
2705
2706 DRE = 0;
2707 }
2708
Douglas Gregorccb07762009-02-11 19:52:55 +00002709 if (!DRE)
2710 return Diag(Arg->getSourceRange().getBegin(),
2711 diag::err_template_arg_not_pointer_to_member_form)
2712 << Arg->getSourceRange();
2713
2714 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2715 assert((isa<FieldDecl>(DRE->getDecl()) ||
2716 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2717 "Only non-static member pointers can make it here");
2718
2719 // Okay: this is the address of a non-static member, and therefore
2720 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002721 if (Arg->isTypeDependent() || Arg->isValueDependent())
2722 Converted = TemplateArgument(Arg->Retain());
2723 else
2724 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002725 return Invalid;
2726 }
2727
2728 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002729 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002730 diag::err_template_arg_not_pointer_to_member_form)
2731 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002732 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002733 diag::note_template_arg_refers_here);
2734 return true;
2735}
2736
Douglas Gregord32e0282009-02-09 23:23:08 +00002737/// \brief Check a template argument against its corresponding
2738/// non-type template parameter.
2739///
Douglas Gregor463421d2009-03-03 04:44:36 +00002740/// This routine implements the semantics of C++ [temp.arg.nontype].
2741/// It returns true if an error occurred, and false otherwise. \p
2742/// InstantiatedParamType is the type of the non-type template
2743/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002744///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002745/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002746bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002747 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002748 TemplateArgument &Converted,
2749 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002750 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2751
Douglas Gregor86560402009-02-10 23:36:10 +00002752 // If either the parameter has a dependent type or the argument is
2753 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002754 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2755 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002756 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002757 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002758 }
Douglas Gregor86560402009-02-10 23:36:10 +00002759
2760 // C++ [temp.arg.nontype]p5:
2761 // The following conversions are performed on each expression used
2762 // as a non-type template-argument. If a non-type
2763 // template-argument cannot be converted to the type of the
2764 // corresponding template-parameter then the program is
2765 // ill-formed.
2766 //
2767 // -- for a non-type template-parameter of integral or
2768 // enumeration type, integral promotions (4.5) and integral
2769 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002770 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002771 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002772 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002773 // C++ [temp.arg.nontype]p1:
2774 // A template-argument for a non-type, non-template
2775 // template-parameter shall be one of:
2776 //
2777 // -- an integral constant-expression of integral or enumeration
2778 // type; or
2779 // -- the name of a non-type template-parameter; or
2780 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002781 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002782 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002783 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002784 diag::err_template_arg_not_integral_or_enumeral)
2785 << ArgType << Arg->getSourceRange();
2786 Diag(Param->getLocation(), diag::note_template_param_here);
2787 return true;
2788 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002789 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002790 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2791 << ArgType << Arg->getSourceRange();
2792 return true;
2793 }
2794
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002795 // From here on out, all we care about are the unqualified forms
2796 // of the parameter and argument types.
2797 ParamType = ParamType.getUnqualifiedType();
2798 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00002799
2800 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002801 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002802 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002803 } else if (CTAK == CTAK_Deduced) {
2804 // C++ [temp.deduct.type]p17:
2805 // If, in the declaration of a function template with a non-type
2806 // template-parameter, the non-type template- parameter is used
2807 // in an expression in the function parameter-list and, if the
2808 // corresponding template-argument is deduced, the
2809 // template-argument type shall match the type of the
2810 // template-parameter exactly, except that a template-argument
2811 // deduced from an array bound may be of any integral type.
2812 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2813 << ArgType << ParamType;
2814 Diag(Param->getLocation(), diag::note_template_param_here);
2815 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00002816 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2817 !ParamType->isEnumeralType()) {
2818 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002819 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002820 } else {
2821 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002822 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002823 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002824 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002825 Diag(Param->getLocation(), diag::note_template_param_here);
2826 return true;
2827 }
2828
Douglas Gregor52aba872009-03-14 00:20:21 +00002829 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002830 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002831 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002832
2833 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002834 llvm::APSInt OldValue = Value;
2835
2836 // Coerce the template argument's value to the value it will have
2837 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002838 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002839 if (Value.getBitWidth() != AllowedBits)
2840 Value.extOrTrunc(AllowedBits);
2841 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002842
2843 // Complain if an unsigned parameter received a negative value.
2844 if (IntegerType->isUnsignedIntegerType()
2845 && (OldValue.isSigned() && OldValue.isNegative())) {
2846 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2847 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2848 << Arg->getSourceRange();
2849 Diag(Param->getLocation(), diag::note_template_param_here);
2850 }
2851
2852 // Complain if we overflowed the template parameter's type.
2853 unsigned RequiredBits;
2854 if (IntegerType->isUnsignedIntegerType())
2855 RequiredBits = OldValue.getActiveBits();
2856 else if (OldValue.isUnsigned())
2857 RequiredBits = OldValue.getActiveBits() + 1;
2858 else
2859 RequiredBits = OldValue.getMinSignedBits();
2860 if (RequiredBits > AllowedBits) {
2861 Diag(Arg->getSourceRange().getBegin(),
2862 diag::warn_template_arg_too_large)
2863 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2864 << Arg->getSourceRange();
2865 Diag(Param->getLocation(), diag::note_template_param_here);
2866 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002867 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002868
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002869 // Add the value of this argument to the list of converted
2870 // arguments. We use the bitwidth and signedness of the template
2871 // parameter.
2872 if (Arg->isValueDependent()) {
2873 // The argument is value-dependent. Create a new
2874 // TemplateArgument with the converted expression.
2875 Converted = TemplateArgument(Arg);
2876 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002877 }
2878
John McCall0ad16662009-10-29 08:12:44 +00002879 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002880 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002881 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002882 return false;
2883 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002884
John McCall16df1e52010-03-30 21:47:33 +00002885 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2886
Douglas Gregorb242683d2010-04-01 18:32:35 +00002887 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2888 // from a template argument of type std::nullptr_t to a non-type
2889 // template parameter of type pointer to object, pointer to
2890 // function, or pointer-to-member, respectively.
2891 if (ArgType->isNullPtrType() &&
2892 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2893 Converted = TemplateArgument((NamedDecl *)0);
2894 return false;
2895 }
2896
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002897 // Handle pointer-to-function, reference-to-function, and
2898 // pointer-to-member-function all in (roughly) the same way.
2899 if (// -- For a non-type template-parameter of type pointer to
2900 // function, only the function-to-pointer conversion (4.3) is
2901 // applied. If the template-argument represents a set of
2902 // overloaded functions (or a pointer to such), the matching
2903 // function is selected from the set (13.4).
2904 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002905 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002906 // -- For a non-type template-parameter of type reference to
2907 // function, no conversions apply. If the template-argument
2908 // represents a set of overloaded functions, the matching
2909 // function is selected from the set (13.4).
2910 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002911 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002912 // -- For a non-type template-parameter of type pointer to
2913 // member function, no conversions apply. If the
2914 // template-argument represents a set of overloaded member
2915 // functions, the matching member function is selected from
2916 // the set (13.4).
2917 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002918 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002919 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002920
Douglas Gregor064fdb22010-04-14 23:11:21 +00002921 if (Arg->getType() == Context.OverloadTy) {
2922 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2923 true,
2924 FoundResult)) {
2925 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2926 return true;
2927
2928 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2929 ArgType = Arg->getType();
2930 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00002931 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002932 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002933
Douglas Gregorb242683d2010-04-01 18:32:35 +00002934 if (!ParamType->isMemberPointerType())
2935 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2936 ParamType,
2937 Arg, Converted);
2938
2939 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
2940 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2941 Arg->isLvalue(Context) == Expr::LV_Valid);
2942 } else if (!Context.hasSameUnqualifiedType(ArgType,
2943 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002944 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002945 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002946 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002947 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002948 Diag(Param->getLocation(), diag::note_template_param_here);
2949 return true;
2950 }
Mike Stump11289f42009-09-09 15:08:12 +00002951
Douglas Gregorb242683d2010-04-01 18:32:35 +00002952 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002953 }
2954
Chris Lattner696197c2009-02-20 21:37:53 +00002955 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002956 // -- for a non-type template-parameter of type pointer to
2957 // object, qualification conversions (4.4) and the
2958 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002959 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002960 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002961 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002962
Douglas Gregorb242683d2010-04-01 18:32:35 +00002963 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2964 ParamType,
2965 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00002966 }
Mike Stump11289f42009-09-09 15:08:12 +00002967
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002968 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002969 // -- For a non-type template-parameter of type reference to
2970 // object, no conversions apply. The type referred to by the
2971 // reference may be more cv-qualified than the (otherwise
2972 // identical) type of the template-argument. The
2973 // template-parameter is bound directly to the
2974 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002975 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002976 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002977
Douglas Gregor064fdb22010-04-14 23:11:21 +00002978 if (Arg->getType() == Context.OverloadTy) {
2979 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2980 ParamRefType->getPointeeType(),
2981 true,
2982 FoundResult)) {
2983 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2984 return true;
2985
2986 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2987 ArgType = Arg->getType();
2988 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00002989 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002990 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002991
Douglas Gregorb242683d2010-04-01 18:32:35 +00002992 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2993 ParamType,
2994 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002995 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002996
2997 // -- For a non-type template-parameter of type pointer to data
2998 // member, qualification conversions (4.4) are applied.
2999 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3000
Douglas Gregor1515f762009-02-11 18:22:40 +00003001 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00003002 // Types match exactly: nothing more to do here.
3003 } else if (IsQualificationConversion(ArgType, ParamType)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003004 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
3005 Arg->isLvalue(Context) == Expr::LV_Valid);
Douglas Gregor0e558532009-02-11 16:16:59 +00003006 } else {
3007 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003008 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00003009 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003010 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00003011 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003012 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00003013 }
3014
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00003015 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00003016}
3017
3018/// \brief Check a template argument against its corresponding
3019/// template template parameter.
3020///
3021/// This routine implements the semantics of C++ [temp.arg.template].
3022/// It returns true if an error occurred, and false otherwise.
3023bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003024 const TemplateArgumentLoc &Arg) {
3025 TemplateName Name = Arg.getArgument().getAsTemplate();
3026 TemplateDecl *Template = Name.getAsTemplateDecl();
3027 if (!Template) {
3028 // Any dependent template name is fine.
3029 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3030 return false;
3031 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003032
3033 // C++ [temp.arg.template]p1:
3034 // A template-argument for a template template-parameter shall be
3035 // the name of a class template, expressed as id-expression. Only
3036 // primary class templates are considered when matching the
3037 // template template argument with the corresponding parameter;
3038 // partial specializations are not considered even if their
3039 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003040 //
3041 // Note that we also allow template template parameters here, which
3042 // will happen when we are dealing with, e.g., class template
3043 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003044 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003045 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003046 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003047 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003048 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003049 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003050 << Template;
3051 }
3052
3053 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3054 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003055 true,
3056 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003057 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003058}
3059
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003060/// \brief Given a non-type template argument that refers to a
3061/// declaration and the type of its corresponding non-type template
3062/// parameter, produce an expression that properly refers to that
3063/// declaration.
3064Sema::OwningExprResult
3065Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3066 QualType ParamType,
3067 SourceLocation Loc) {
3068 assert(Arg.getKind() == TemplateArgument::Declaration &&
3069 "Only declaration template arguments permitted here");
3070 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3071
3072 if (VD->getDeclContext()->isRecord() &&
3073 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3074 // If the value is a class member, we might have a pointer-to-member.
3075 // Determine whether the non-type template template parameter is of
3076 // pointer-to-member type. If so, we need to build an appropriate
3077 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3078 // would refer to the member itself.
3079 if (ParamType->isMemberPointerType()) {
3080 QualType ClassType
3081 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3082 NestedNameSpecifier *Qualifier
3083 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
3084 CXXScopeSpec SS;
3085 SS.setScopeRep(Qualifier);
3086 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
3087 VD->getType().getNonReferenceType(),
3088 Loc,
3089 &SS);
3090 if (RefExpr.isInvalid())
3091 return ExprError();
3092
3093 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003094
3095 // We might need to perform a trailing qualification conversion, since
3096 // the element type on the parameter could be more qualified than the
3097 // element type in the expression we constructed.
3098 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3099 ParamType.getUnqualifiedType())) {
3100 Expr *RefE = RefExpr.takeAs<Expr>();
3101 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(),
3102 CastExpr::CK_NoOp);
3103 RefExpr = Owned(RefE);
3104 }
3105
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003106 assert(!RefExpr.isInvalid() &&
3107 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003108 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003109 return move(RefExpr);
3110 }
3111 }
3112
3113 QualType T = VD->getType().getNonReferenceType();
3114 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003115 // When the non-type template parameter is a pointer, take the
3116 // address of the declaration.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003117 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3118 if (RefExpr.isInvalid())
3119 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003120
3121 if (T->isFunctionType() || T->isArrayType()) {
3122 // Decay functions and arrays.
3123 Expr *RefE = (Expr *)RefExpr.get();
3124 DefaultFunctionArrayConversion(RefE);
3125 if (RefE != RefExpr.get()) {
3126 RefExpr.release();
3127 RefExpr = Owned(RefE);
3128 }
3129
3130 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003131 }
3132
Douglas Gregorb242683d2010-04-01 18:32:35 +00003133 // Take the address of everything else
3134 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003135 }
3136
3137 // If the non-type template parameter has reference type, qualify the
3138 // resulting declaration reference with the extra qualifiers on the
3139 // type that the reference refers to.
3140 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3141 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3142
3143 return BuildDeclRefExpr(VD, T, Loc);
3144}
3145
3146/// \brief Construct a new expression that refers to the given
3147/// integral template argument with the given source-location
3148/// information.
3149///
3150/// This routine takes care of the mapping from an integral template
3151/// argument (which may have any integral type) to the appropriate
3152/// literal value.
3153Sema::OwningExprResult
3154Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3155 SourceLocation Loc) {
3156 assert(Arg.getKind() == TemplateArgument::Integral &&
3157 "Operation is only value for integral template arguments");
3158 QualType T = Arg.getIntegralType();
3159 if (T->isCharType() || T->isWideCharType())
3160 return Owned(new (Context) CharacterLiteral(
3161 Arg.getAsIntegral()->getZExtValue(),
3162 T->isWideCharType(),
3163 T,
3164 Loc));
3165 if (T->isBooleanType())
3166 return Owned(new (Context) CXXBoolLiteralExpr(
3167 Arg.getAsIntegral()->getBoolValue(),
3168 T,
3169 Loc));
3170
3171 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3172}
3173
3174
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003175/// \brief Determine whether the given template parameter lists are
3176/// equivalent.
3177///
Mike Stump11289f42009-09-09 15:08:12 +00003178/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003179/// source code as part of a new template declaration.
3180///
3181/// \param Old The old template parameter list, typically found via
3182/// name lookup of the template declared with this template parameter
3183/// list.
3184///
3185/// \param Complain If true, this routine will produce a diagnostic if
3186/// the template parameter lists are not equivalent.
3187///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003188/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003189///
3190/// \param TemplateArgLoc If this source location is valid, then we
3191/// are actually checking the template parameter list of a template
3192/// argument (New) against the template parameter list of its
3193/// corresponding template template parameter (Old). We produce
3194/// slightly different diagnostics in this scenario.
3195///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003196/// \returns True if the template parameter lists are equal, false
3197/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003198bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003199Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3200 TemplateParameterList *Old,
3201 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003202 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003203 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003204 if (Old->size() != New->size()) {
3205 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003206 unsigned NextDiag = diag::err_template_param_list_different_arity;
3207 if (TemplateArgLoc.isValid()) {
3208 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3209 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003210 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003211 Diag(New->getTemplateLoc(), NextDiag)
3212 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003213 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003214 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003215 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003216 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003217 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3218 }
3219
3220 return false;
3221 }
3222
3223 for (TemplateParameterList::iterator OldParm = Old->begin(),
3224 OldParmEnd = Old->end(), NewParm = New->begin();
3225 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3226 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003227 if (Complain) {
3228 unsigned NextDiag = diag::err_template_param_different_kind;
3229 if (TemplateArgLoc.isValid()) {
3230 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3231 NextDiag = diag::note_template_param_different_kind;
3232 }
3233 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003234 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003235 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003236 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003237 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003238 return false;
3239 }
3240
Douglas Gregor2e87ca22010-06-04 08:34:32 +00003241 if (TemplateTypeParmDecl *OldTTP
3242 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3243 // Template type parameters are equivalent if either both are template
3244 // type parameter packs or neither are (since we know we're at the same
3245 // index).
3246 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3247 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3248 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3249 // allow one to match a template parameter pack in the template
3250 // parameter list of a template template parameter to one or more
3251 // template parameters in the template parameter list of the
3252 // corresponding template template argument.
3253 if (Complain) {
3254 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3255 if (TemplateArgLoc.isValid()) {
3256 Diag(TemplateArgLoc,
3257 diag::err_template_arg_template_params_mismatch);
3258 NextDiag = diag::note_template_parameter_pack_non_pack;
3259 }
3260 Diag(NewTTP->getLocation(), NextDiag)
3261 << 0 << NewTTP->isParameterPack();
3262 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3263 << 0 << OldTTP->isParameterPack();
3264 }
3265 return false;
3266 }
Mike Stump11289f42009-09-09 15:08:12 +00003267 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003268 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3269 // The types of non-type template parameters must agree.
3270 NonTypeTemplateParmDecl *NewNTTP
3271 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003272
3273 // If we are matching a template template argument to a template
3274 // template parameter and one of the non-type template parameter types
3275 // is dependent, then we must wait until template instantiation time
3276 // to actually compare the arguments.
3277 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3278 (OldNTTP->getType()->isDependentType() ||
3279 NewNTTP->getType()->isDependentType()))
3280 continue;
3281
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003282 if (Context.getCanonicalType(OldNTTP->getType()) !=
3283 Context.getCanonicalType(NewNTTP->getType())) {
3284 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003285 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3286 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003287 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003288 diag::err_template_arg_template_params_mismatch);
3289 NextDiag = diag::note_template_nontype_parm_different_type;
3290 }
3291 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003292 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003293 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003294 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003295 diag::note_template_nontype_parm_prev_declaration)
3296 << OldNTTP->getType();
3297 }
3298 return false;
3299 }
3300 } else {
3301 // The template parameter lists of template template
3302 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003303 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003304 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003305 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003306 = cast<TemplateTemplateParmDecl>(*OldParm);
3307 TemplateTemplateParmDecl *NewTTP
3308 = cast<TemplateTemplateParmDecl>(*NewParm);
3309 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3310 OldTTP->getTemplateParameters(),
3311 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003312 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003313 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003314 return false;
3315 }
3316 }
3317
3318 return true;
3319}
3320
3321/// \brief Check whether a template can be declared within this scope.
3322///
3323/// If the template declaration is valid in this scope, returns
3324/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003325bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003326Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003327 // Find the nearest enclosing declaration scope.
3328 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3329 (S->getFlags() & Scope::TemplateParamScope) != 0)
3330 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003331
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003332 // C++ [temp]p2:
3333 // A template-declaration can appear only as a namespace scope or
3334 // class scope declaration.
3335 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003336 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3337 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003338 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003339 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003340
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003341 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003342 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003343
3344 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3345 return false;
3346
Mike Stump11289f42009-09-09 15:08:12 +00003347 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003348 diag::err_template_outside_namespace_or_class_scope)
3349 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003350}
Douglas Gregor67a65642009-02-17 23:15:12 +00003351
Douglas Gregor54888652009-10-07 00:13:32 +00003352/// \brief Determine what kind of template specialization the given declaration
3353/// is.
3354static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3355 if (!D)
3356 return TSK_Undeclared;
3357
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003358 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3359 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003360 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3361 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003362 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3363 return Var->getTemplateSpecializationKind();
3364
Douglas Gregor54888652009-10-07 00:13:32 +00003365 return TSK_Undeclared;
3366}
3367
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003368/// \brief Check whether a specialization is well-formed in the current
3369/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003370///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003371/// This routine determines whether a template specialization can be declared
3372/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003373///
3374/// \param S the semantic analysis object for which this check is being
3375/// performed.
3376///
3377/// \param Specialized the entity being specialized or instantiated, which
3378/// may be a kind of template (class template, function template, etc.) or
3379/// a member of a class template (member function, static data member,
3380/// member class).
3381///
3382/// \param PrevDecl the previous declaration of this entity, if any.
3383///
3384/// \param Loc the location of the explicit specialization or instantiation of
3385/// this entity.
3386///
3387/// \param IsPartialSpecialization whether this is a partial specialization of
3388/// a class template.
3389///
Douglas Gregor54888652009-10-07 00:13:32 +00003390/// \returns true if there was an error that we cannot recover from, false
3391/// otherwise.
3392static bool CheckTemplateSpecializationScope(Sema &S,
3393 NamedDecl *Specialized,
3394 NamedDecl *PrevDecl,
3395 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003396 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003397 // Keep these "kind" numbers in sync with the %select statements in the
3398 // various diagnostics emitted by this routine.
3399 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003400 bool isTemplateSpecialization = false;
3401 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003402 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003403 isTemplateSpecialization = true;
3404 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003405 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003406 isTemplateSpecialization = true;
3407 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003408 EntityKind = 3;
3409 else if (isa<VarDecl>(Specialized))
3410 EntityKind = 4;
3411 else if (isa<RecordDecl>(Specialized))
3412 EntityKind = 5;
3413 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003414 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3415 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003416 return true;
3417 }
3418
Douglas Gregorf47b9112009-02-25 22:02:03 +00003419 // C++ [temp.expl.spec]p2:
3420 // An explicit specialization shall be declared in the namespace
3421 // of which the template is a member, or, for member templates, in
3422 // the namespace of which the enclosing class or enclosing class
3423 // template is a member. An explicit specialization of a member
3424 // function, member class or static data member of a class
3425 // template shall be declared in the namespace of which the class
3426 // template is a member. Such a declaration may also be a
3427 // definition. If the declaration is not a definition, the
3428 // specialization may be defined later in the name- space in which
3429 // the explicit specialization was declared, or in a namespace
3430 // that encloses the one in which the explicit specialization was
3431 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003432 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3433 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003434 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003435 return true;
3436 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003437
Douglas Gregor40fb7442009-10-07 17:30:37 +00003438 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3439 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003440 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003441 return true;
3442 }
3443
Douglas Gregore4b05162009-10-07 17:21:34 +00003444 // C++ [temp.class.spec]p6:
3445 // A class template partial specialization may be declared or redeclared
3446 // in any namespace scope in which its definition may be defined (14.5.1
3447 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003448 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003449 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003450 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003451 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003452 if ((!PrevDecl ||
3453 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3454 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3455 // There is no prior declaration of this entity, so this
3456 // specialization must be in the same context as the template
3457 // itself.
3458 if (!DC->Equals(SpecializedContext)) {
3459 if (isa<TranslationUnitDecl>(SpecializedContext))
3460 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3461 << EntityKind << Specialized;
3462 else if (isa<NamespaceDecl>(SpecializedContext))
3463 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3464 << EntityKind << Specialized
3465 << cast<NamedDecl>(SpecializedContext);
3466
3467 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3468 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003469 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003470 }
Douglas Gregor54888652009-10-07 00:13:32 +00003471
3472 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003473 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003474 // Note that HandleDeclarator() performs this check for explicit
3475 // specializations of function templates, static data members, and member
3476 // functions, so we skip the check here for those kinds of entities.
3477 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003478 // Should we refactor that check, so that it occurs later?
3479 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003480 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3481 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003482 if (isa<TranslationUnitDecl>(SpecializedContext))
3483 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3484 << EntityKind << Specialized;
3485 else if (isa<NamespaceDecl>(SpecializedContext))
3486 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3487 << EntityKind << Specialized
3488 << cast<NamedDecl>(SpecializedContext);
3489
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003490 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003491 }
Douglas Gregor54888652009-10-07 00:13:32 +00003492
3493 // FIXME: check for specialization-after-instantiation errors and such.
3494
Douglas Gregorf47b9112009-02-25 22:02:03 +00003495 return false;
3496}
Douglas Gregor54888652009-10-07 00:13:32 +00003497
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003498/// \brief Check the non-type template arguments of a class template
3499/// partial specialization according to C++ [temp.class.spec]p9.
3500///
Douglas Gregor09a30232009-06-12 22:08:06 +00003501/// \param TemplateParams the template parameters of the primary class
3502/// template.
3503///
3504/// \param TemplateArg the template arguments of the class template
3505/// partial specialization.
3506///
3507/// \param MirrorsPrimaryTemplate will be set true if the class
3508/// template partial specialization arguments are identical to the
3509/// implicit template arguments of the primary template. This is not
3510/// necessarily an error (C++0x), and it is left to the caller to diagnose
3511/// this condition when it is an error.
3512///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003513/// \returns true if there was an error, false otherwise.
3514bool Sema::CheckClassTemplatePartialSpecializationArgs(
3515 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003516 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003517 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003518 // FIXME: the interface to this function will have to change to
3519 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003520 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003521
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003522 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003523
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003524 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003525 // Determine whether the template argument list of the partial
3526 // specialization is identical to the implicit argument list of
3527 // the primary template. The caller may need to diagnostic this as
3528 // an error per C++ [temp.class.spec]p9b3.
3529 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003530 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003531 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3532 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003533 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003534 MirrorsPrimaryTemplate = false;
3535 } else if (TemplateTemplateParmDecl *TTP
3536 = dyn_cast<TemplateTemplateParmDecl>(
3537 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003538 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003539 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003540 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003541 if (!ArgDecl ||
3542 ArgDecl->getIndex() != TTP->getIndex() ||
3543 ArgDecl->getDepth() != TTP->getDepth())
3544 MirrorsPrimaryTemplate = false;
3545 }
3546 }
3547
Mike Stump11289f42009-09-09 15:08:12 +00003548 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003549 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003550 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003551 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003552 }
3553
Anders Carlsson40c1d492009-06-13 18:20:51 +00003554 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003555 if (!ArgExpr) {
3556 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003557 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003558 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003559
3560 // C++ [temp.class.spec]p8:
3561 // A non-type argument is non-specialized if it is the name of a
3562 // non-type parameter. All other non-type arguments are
3563 // specialized.
3564 //
3565 // Below, we check the two conditions that only apply to
3566 // specialized non-type arguments, so skip any non-specialized
3567 // arguments.
3568 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003569 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003570 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003571 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003572 (Param->getIndex() != NTTP->getIndex() ||
3573 Param->getDepth() != NTTP->getDepth()))
3574 MirrorsPrimaryTemplate = false;
3575
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003576 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003577 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003578
3579 // C++ [temp.class.spec]p9:
3580 // Within the argument list of a class template partial
3581 // specialization, the following restrictions apply:
3582 // -- A partially specialized non-type argument expression
3583 // shall not involve a template parameter of the partial
3584 // specialization except when the argument expression is a
3585 // simple identifier.
3586 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003587 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003588 diag::err_dependent_non_type_arg_in_partial_spec)
3589 << ArgExpr->getSourceRange();
3590 return true;
3591 }
3592
3593 // -- The type of a template parameter corresponding to a
3594 // specialized non-type argument shall not be dependent on a
3595 // parameter of the specialization.
3596 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003597 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003598 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3599 << Param->getType()
3600 << ArgExpr->getSourceRange();
3601 Diag(Param->getLocation(), diag::note_template_param_here);
3602 return true;
3603 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003604
3605 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003606 }
3607
3608 return false;
3609}
3610
Douglas Gregorc854c662010-02-26 06:03:23 +00003611/// \brief Retrieve the previous declaration of the given declaration.
3612static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3613 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3614 return VD->getPreviousDeclaration();
3615 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3616 return FD->getPreviousDeclaration();
3617 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3618 return TD->getPreviousDeclaration();
3619 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3620 return TD->getPreviousDeclaration();
3621 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3622 return FTD->getPreviousDeclaration();
3623 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3624 return CTD->getPreviousDeclaration();
3625 return 0;
3626}
3627
Douglas Gregorc08f4892009-03-25 00:13:59 +00003628Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003629Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3630 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003631 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003632 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003633 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003634 SourceLocation TemplateNameLoc,
3635 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003636 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003637 SourceLocation RAngleLoc,
3638 AttributeList *Attr,
3639 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003640 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003641
Douglas Gregor67a65642009-02-17 23:15:12 +00003642 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003643 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003644 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003645 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3646
3647 if (!ClassTemplate) {
3648 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3649 << (Name.getAsTemplateDecl() &&
3650 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3651 return true;
3652 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003653
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003654 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003655 bool isPartialSpecialization = false;
3656
Douglas Gregorf47b9112009-02-25 22:02:03 +00003657 // Check the validity of the template headers that introduce this
3658 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003659 // FIXME: We probably shouldn't complain about these headers for
3660 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003661 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003662 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3663 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003664 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003665 TUK == TUK_Friend,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003666 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003667 if (TemplateParams && TemplateParams->size() > 0) {
3668 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003669
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003670 // C++ [temp.class.spec]p10:
3671 // The template parameter list of a specialization shall not
3672 // contain default template argument values.
3673 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3674 Decl *Param = TemplateParams->getParam(I);
3675 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3676 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003677 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003678 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003679 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003680 }
3681 } else if (NonTypeTemplateParmDecl *NTTP
3682 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3683 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003684 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003685 diag::err_default_arg_in_partial_spec)
3686 << DefArg->getSourceRange();
3687 NTTP->setDefaultArgument(0);
3688 DefArg->Destroy(Context);
3689 }
3690 } else {
3691 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003692 if (TTP->hasDefaultArgument()) {
3693 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003694 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003695 << TTP->getDefaultArgument().getSourceRange();
3696 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003697 }
3698 }
3699 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003700 } else if (TemplateParams) {
3701 if (TUK == TUK_Friend)
3702 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003703 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003704 SourceRange(TemplateParams->getTemplateLoc(),
3705 TemplateParams->getRAngleLoc()))
3706 << SourceRange(LAngleLoc, RAngleLoc);
3707 else
3708 isExplicitSpecialization = true;
3709 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003710 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003711 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003712 isExplicitSpecialization = true;
3713 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003714
Douglas Gregor67a65642009-02-17 23:15:12 +00003715 // Check that the specialization uses the same tag kind as the
3716 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003717 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3718 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00003719 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003720 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003721 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003722 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003723 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003724 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003725 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003726 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003727 diag::note_previous_use);
3728 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3729 }
3730
Douglas Gregorc40290e2009-03-09 23:48:35 +00003731 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003732 TemplateArgumentListInfo TemplateArgs;
3733 TemplateArgs.setLAngleLoc(LAngleLoc);
3734 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003735 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003736
Douglas Gregor67a65642009-02-17 23:15:12 +00003737 // Check that the template argument list is well-formed for this
3738 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003739 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3740 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003741 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3742 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003743 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003744
Mike Stump11289f42009-09-09 15:08:12 +00003745 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003746 ClassTemplate->getTemplateParameters()->size()) &&
3747 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003748
Douglas Gregor2373c592009-05-31 09:31:02 +00003749 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003750 // corresponds to these arguments.
3751 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003752 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003753 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003754 if (CheckClassTemplatePartialSpecializationArgs(
3755 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003756 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003757 return true;
3758
Douglas Gregor09a30232009-06-12 22:08:06 +00003759 if (MirrorsPrimaryTemplate) {
3760 // C++ [temp.class.spec]p9b3:
3761 //
Mike Stump11289f42009-09-09 15:08:12 +00003762 // -- The argument list of the specialization shall not be identical
3763 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003764 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003765 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003766 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003767 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003768 ClassTemplate->getIdentifier(),
3769 TemplateNameLoc,
3770 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003771 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003772 AS_none);
3773 }
3774
Douglas Gregor2208a292009-09-26 20:57:03 +00003775 // FIXME: Diagnose friend partial specializations
3776
Douglas Gregor92354b62010-02-09 00:37:32 +00003777 if (!Name.isDependent() &&
3778 !TemplateSpecializationType::anyDependentTemplateArguments(
3779 TemplateArgs.getArgumentArray(),
3780 TemplateArgs.size())) {
3781 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3782 << ClassTemplate->getDeclName();
3783 isPartialSpecialization = false;
3784 } else {
3785 // FIXME: Template parameter list matters, too
3786 ClassTemplatePartialSpecializationDecl::Profile(ID,
3787 Converted.getFlatArguments(),
3788 Converted.flatSize(),
3789 Context);
3790 }
3791 }
3792
3793 if (!isPartialSpecialization)
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003794 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003795 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003796 Converted.flatSize(),
3797 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003798 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003799 ClassTemplateSpecializationDecl *PrevDecl = 0;
3800
3801 if (isPartialSpecialization)
3802 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003803 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003804 InsertPos);
3805 else
3806 PrevDecl
3807 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003808
3809 ClassTemplateSpecializationDecl *Specialization = 0;
3810
Douglas Gregorf47b9112009-02-25 22:02:03 +00003811 // Check whether we can declare a class template specialization in
3812 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003813 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003814 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003815 TemplateNameLoc,
3816 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003817 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003818
Douglas Gregor15301382009-07-30 17:40:51 +00003819 // The canonical type
3820 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003821 if (PrevDecl &&
3822 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003823 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003824 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003825 // arguments was referenced but not declared, or we're only
3826 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003827 // declaration node as our own, updating its source location to
3828 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003829 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003830 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003831 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003832 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003833 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003834 // Build the canonical type that describes the converted template
3835 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003836 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3837 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003838 Converted.getFlatArguments(),
3839 Converted.flatSize());
3840
Douglas Gregor2373c592009-05-31 09:31:02 +00003841 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003842 ClassTemplatePartialSpecializationDecl *PrevPartial
3843 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00003844 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
3845 : ClassTemplate->getPartialSpecializations().size();
Mike Stump11289f42009-09-09 15:08:12 +00003846 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00003847 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00003848 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003849 TemplateNameLoc,
3850 TemplateParams,
3851 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003852 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003853 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003854 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00003855 PrevPartial,
3856 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00003857 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor2373c592009-05-31 09:31:02 +00003858
3859 if (PrevPartial) {
3860 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3861 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3862 } else {
3863 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3864 }
3865 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003866
Douglas Gregor21610382009-10-29 00:04:11 +00003867 // If we are providing an explicit specialization of a member class
3868 // template specialization, make a note of that.
3869 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3870 PrevPartial->setMemberSpecialization();
3871
Douglas Gregor91772d12009-06-13 00:26:55 +00003872 // Check that all of the template parameters of the class template
3873 // partial specialization are deducible from the template
3874 // arguments. If not, this class template partial specialization
3875 // will never be used.
3876 llvm::SmallVector<bool, 8> DeducibleParams;
3877 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003878 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003879 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003880 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003881 unsigned NumNonDeducible = 0;
3882 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3883 if (!DeducibleParams[I])
3884 ++NumNonDeducible;
3885
3886 if (NumNonDeducible) {
3887 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3888 << (NumNonDeducible > 1)
3889 << SourceRange(TemplateNameLoc, RAngleLoc);
3890 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3891 if (!DeducibleParams[I]) {
3892 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3893 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003894 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003895 diag::note_partial_spec_unused_parameter)
3896 << Param->getDeclName();
3897 else
Mike Stump11289f42009-09-09 15:08:12 +00003898 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003899 diag::note_partial_spec_unused_parameter)
3900 << std::string("<anonymous>");
3901 }
3902 }
3903 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003904 } else {
3905 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003906 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003907 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00003908 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00003909 ClassTemplate->getDeclContext(),
3910 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003911 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003912 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003913 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00003914 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor67a65642009-02-17 23:15:12 +00003915
3916 if (PrevDecl) {
3917 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3918 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3919 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003920 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003921 InsertPos);
3922 }
Douglas Gregor15301382009-07-30 17:40:51 +00003923
3924 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003925 }
3926
Douglas Gregor06db9f52009-10-12 20:18:28 +00003927 // C++ [temp.expl.spec]p6:
3928 // If a template, a member template or the member of a class template is
3929 // explicitly specialized then that specialization shall be declared
3930 // before the first use of that specialization that would cause an implicit
3931 // instantiation to take place, in every translation unit in which such a
3932 // use occurs; no diagnostic is required.
3933 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003934 bool Okay = false;
3935 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3936 // Is there any previous explicit specialization declaration?
3937 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3938 Okay = true;
3939 break;
3940 }
3941 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003942
Douglas Gregorc854c662010-02-26 06:03:23 +00003943 if (!Okay) {
3944 SourceRange Range(TemplateNameLoc, RAngleLoc);
3945 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3946 << Context.getTypeDeclType(Specialization) << Range;
3947
3948 Diag(PrevDecl->getPointOfInstantiation(),
3949 diag::note_instantiation_required_here)
3950 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003951 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003952 return true;
3953 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003954 }
3955
Douglas Gregor2208a292009-09-26 20:57:03 +00003956 // If this is not a friend, note that this is an explicit specialization.
3957 if (TUK != TUK_Friend)
3958 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003959
3960 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003961 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003962 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003963 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003964 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003965 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003966 Diag(Def->getLocation(), diag::note_previous_definition);
3967 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003968 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003969 }
3970 }
3971
Douglas Gregord56a91e2009-02-26 22:19:44 +00003972 // Build the fully-sugared type for this class template
3973 // specialization as the user wrote in the specialization
3974 // itself. This means that we'll pretty-print the type retrieved
3975 // from the specialization's declaration the way that the user
3976 // actually wrote the specialization, rather than formatting the
3977 // name based on the "canonical" representation used to store the
3978 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003979 TypeSourceInfo *WrittenTy
3980 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3981 TemplateArgs, CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003982 if (TUK != TUK_Friend)
3983 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003984 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003985
Douglas Gregor1e249f82009-02-25 22:18:32 +00003986 // C++ [temp.expl.spec]p9:
3987 // A template explicit specialization is in the scope of the
3988 // namespace in which the template was defined.
3989 //
3990 // We actually implement this paragraph where we set the semantic
3991 // context (in the creation of the ClassTemplateSpecializationDecl),
3992 // but we also maintain the lexical context where the actual
3993 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003994 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003995
Douglas Gregor67a65642009-02-17 23:15:12 +00003996 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003997 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003998 Specialization->startDefinition();
3999
Douglas Gregor2208a292009-09-26 20:57:03 +00004000 if (TUK == TUK_Friend) {
4001 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4002 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00004003 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00004004 /*FIXME:*/KWLoc);
4005 Friend->setAccess(AS_public);
4006 CurContext->addDecl(Friend);
4007 } else {
4008 // Add the specialization into its lexical context, so that it can
4009 // be seen when iterating through the list of declarations in that
4010 // context. However, specializations are not found by name lookup.
4011 CurContext->addDecl(Specialization);
4012 }
Chris Lattner83f095c2009-03-28 19:18:32 +00004013 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00004014}
Douglas Gregor333489b2009-03-27 23:10:48 +00004015
Mike Stump11289f42009-09-09 15:08:12 +00004016Sema::DeclPtrTy
4017Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004018 MultiTemplateParamsArg TemplateParameterLists,
4019 Declarator &D) {
4020 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4021}
4022
Mike Stump11289f42009-09-09 15:08:12 +00004023Sema::DeclPtrTy
4024Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004025 MultiTemplateParamsArg TemplateParameterLists,
4026 Declarator &D) {
4027 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4028 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4029 "Not a function declarator!");
4030 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00004031
Douglas Gregor17a7c122009-06-24 00:54:41 +00004032 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004033 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004034 }
Mike Stump11289f42009-09-09 15:08:12 +00004035
Douglas Gregor17a7c122009-06-24 00:54:41 +00004036 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004037
4038 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004039 move(TemplateParameterLists),
4040 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004041 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00004042 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00004043 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004044 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00004045 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
4046 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004047 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00004048}
4049
John McCall4f7ced62010-02-11 01:33:53 +00004050/// \brief Strips various properties off an implicit instantiation
4051/// that has just been explicitly specialized.
4052static void StripImplicitInstantiation(NamedDecl *D) {
4053 D->invalidateAttrs();
4054
4055 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4056 FD->setInlineSpecified(false);
4057 }
4058}
4059
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004060/// \brief Diagnose cases where we have an explicit template specialization
4061/// before/after an explicit template instantiation, producing diagnostics
4062/// for those cases where they are required and determining whether the
4063/// new specialization/instantiation will have any effect.
4064///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004065/// \param NewLoc the location of the new explicit specialization or
4066/// instantiation.
4067///
4068/// \param NewTSK the kind of the new explicit specialization or instantiation.
4069///
4070/// \param PrevDecl the previous declaration of the entity.
4071///
4072/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4073///
4074/// \param PrevPointOfInstantiation if valid, indicates where the previus
4075/// declaration was instantiated (either implicitly or explicitly).
4076///
4077/// \param SuppressNew will be set to true to indicate that the new
4078/// specialization or instantiation has no effect and should be ignored.
4079///
4080/// \returns true if there was an error that should prevent the introduction of
4081/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004082bool
4083Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4084 TemplateSpecializationKind NewTSK,
4085 NamedDecl *PrevDecl,
4086 TemplateSpecializationKind PrevTSK,
4087 SourceLocation PrevPointOfInstantiation,
4088 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004089 SuppressNew = false;
4090
4091 switch (NewTSK) {
4092 case TSK_Undeclared:
4093 case TSK_ImplicitInstantiation:
4094 assert(false && "Don't check implicit instantiations here");
4095 return false;
4096
4097 case TSK_ExplicitSpecialization:
4098 switch (PrevTSK) {
4099 case TSK_Undeclared:
4100 case TSK_ExplicitSpecialization:
4101 // Okay, we're just specializing something that is either already
4102 // explicitly specialized or has merely been mentioned without any
4103 // instantiation.
4104 return false;
4105
4106 case TSK_ImplicitInstantiation:
4107 if (PrevPointOfInstantiation.isInvalid()) {
4108 // The declaration itself has not actually been instantiated, so it is
4109 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004110 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004111 return false;
4112 }
4113 // Fall through
4114
4115 case TSK_ExplicitInstantiationDeclaration:
4116 case TSK_ExplicitInstantiationDefinition:
4117 assert((PrevTSK == TSK_ImplicitInstantiation ||
4118 PrevPointOfInstantiation.isValid()) &&
4119 "Explicit instantiation without point of instantiation?");
4120
4121 // C++ [temp.expl.spec]p6:
4122 // If a template, a member template or the member of a class template
4123 // is explicitly specialized then that specialization shall be declared
4124 // before the first use of that specialization that would cause an
4125 // implicit instantiation to take place, in every translation unit in
4126 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004127 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4128 // Is there any previous explicit specialization declaration?
4129 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4130 return false;
4131 }
4132
Douglas Gregor1d957a32009-10-27 18:42:08 +00004133 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004134 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004135 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004136 << (PrevTSK != TSK_ImplicitInstantiation);
4137
4138 return true;
4139 }
4140 break;
4141
4142 case TSK_ExplicitInstantiationDeclaration:
4143 switch (PrevTSK) {
4144 case TSK_ExplicitInstantiationDeclaration:
4145 // This explicit instantiation declaration is redundant (that's okay).
4146 SuppressNew = true;
4147 return false;
4148
4149 case TSK_Undeclared:
4150 case TSK_ImplicitInstantiation:
4151 // We're explicitly instantiating something that may have already been
4152 // implicitly instantiated; that's fine.
4153 return false;
4154
4155 case TSK_ExplicitSpecialization:
4156 // C++0x [temp.explicit]p4:
4157 // For a given set of template parameters, if an explicit instantiation
4158 // of a template appears after a declaration of an explicit
4159 // specialization for that template, the explicit instantiation has no
4160 // effect.
John McCall6b21eb52010-03-02 23:09:38 +00004161 SuppressNew = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004162 return false;
4163
4164 case TSK_ExplicitInstantiationDefinition:
4165 // C++0x [temp.explicit]p10:
4166 // If an entity is the subject of both an explicit instantiation
4167 // declaration and an explicit instantiation definition in the same
4168 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004169 Diag(NewLoc,
4170 diag::err_explicit_instantiation_declaration_after_definition);
4171 Diag(PrevPointOfInstantiation,
4172 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004173 assert(PrevPointOfInstantiation.isValid() &&
4174 "Explicit instantiation without point of instantiation?");
4175 SuppressNew = true;
4176 return false;
4177 }
4178 break;
4179
4180 case TSK_ExplicitInstantiationDefinition:
4181 switch (PrevTSK) {
4182 case TSK_Undeclared:
4183 case TSK_ImplicitInstantiation:
4184 // We're explicitly instantiating something that may have already been
4185 // implicitly instantiated; that's fine.
4186 return false;
4187
4188 case TSK_ExplicitSpecialization:
4189 // C++ DR 259, C++0x [temp.explicit]p4:
4190 // For a given set of template parameters, if an explicit
4191 // instantiation of a template appears after a declaration of
4192 // an explicit specialization for that template, the explicit
4193 // instantiation has no effect.
4194 //
4195 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004196 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004197 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004198 if (!getLangOptions().CPlusPlus0x) {
4199 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004200 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004201 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004202 diag::note_previous_template_specialization);
4203 }
4204 SuppressNew = true;
4205 return false;
4206
4207 case TSK_ExplicitInstantiationDeclaration:
4208 // We're explicity instantiating a definition for something for which we
4209 // were previously asked to suppress instantiations. That's fine.
4210 return false;
4211
4212 case TSK_ExplicitInstantiationDefinition:
4213 // C++0x [temp.spec]p5:
4214 // For a given template and a given set of template-arguments,
4215 // - an explicit instantiation definition shall appear at most once
4216 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004217 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004218 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004219 Diag(PrevPointOfInstantiation,
4220 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004221 SuppressNew = true;
4222 return false;
4223 }
4224 break;
4225 }
4226
4227 assert(false && "Missing specialization/instantiation case?");
4228
4229 return false;
4230}
4231
John McCallb9c78482010-04-08 09:05:18 +00004232/// \brief Perform semantic analysis for the given dependent function
4233/// template specialization. The only possible way to get a dependent
4234/// function template specialization is with a friend declaration,
4235/// like so:
4236///
4237/// template <class T> void foo(T);
4238/// template <class T> class A {
4239/// friend void foo<>(T);
4240/// };
4241///
4242/// There really isn't any useful analysis we can do here, so we
4243/// just store the information.
4244bool
4245Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4246 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4247 LookupResult &Previous) {
4248 // Remove anything from Previous that isn't a function template in
4249 // the correct context.
4250 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4251 LookupResult::Filter F = Previous.makeFilter();
4252 while (F.hasNext()) {
4253 NamedDecl *D = F.next()->getUnderlyingDecl();
4254 if (!isa<FunctionTemplateDecl>(D) ||
4255 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4256 F.erase();
4257 }
4258 F.done();
4259
4260 // Should this be diagnosed here?
4261 if (Previous.empty()) return true;
4262
4263 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4264 ExplicitTemplateArgs);
4265 return false;
4266}
4267
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004268/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004269/// specialization.
4270///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004271/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004272/// explicit function template specialization. On successful completion,
4273/// the function declaration \p FD will become a function template
4274/// specialization.
4275///
4276/// \param FD the function declaration, which will be updated to become a
4277/// function template specialization.
4278///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004279/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4280/// if any. Note that this may be valid info even when 0 arguments are
4281/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4282/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004283///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004284/// \param PrevDecl the set of declarations that may be specialized by
4285/// this function specialization.
4286bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004287Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004288 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004289 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004290 // The set of function template specializations that could match this
4291 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004292 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004293
4294 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00004295 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4296 I != E; ++I) {
4297 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4298 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004299 // Only consider templates found within the same semantic lookup scope as
4300 // FD.
4301 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4302 continue;
4303
4304 // C++ [temp.expl.spec]p11:
4305 // A trailing template-argument can be left unspecified in the
4306 // template-id naming an explicit function template specialization
4307 // provided it can be deduced from the function argument type.
4308 // Perform template argument deduction to determine whether we may be
4309 // specializing this template.
4310 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004311 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004312 FunctionDecl *Specialization = 0;
4313 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004314 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004315 FD->getType(),
4316 Specialization,
4317 Info)) {
4318 // FIXME: Template argument deduction failed; record why it failed, so
4319 // that we can provide nifty diagnostics.
4320 (void)TDK;
4321 continue;
4322 }
4323
4324 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004325 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004326 }
4327 }
4328
Douglas Gregor5de279c2009-09-26 03:41:46 +00004329 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004330 UnresolvedSetIterator Result
4331 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4332 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004333 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004334 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004335 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004336 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004337 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004338 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004339 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004340
4341 // Ignore access information; it doesn't figure into redeclaration checking.
4342 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004343 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004344
4345 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004346 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004347
4348 // If this is a friend declaration, then we're not really declaring
4349 // an explicit specialization.
4350 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004351
Douglas Gregor54888652009-10-07 00:13:32 +00004352 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004353 if (!isFriend &&
4354 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004355 Specialization->getPrimaryTemplate(),
4356 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004357 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004358 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004359
4360 // C++ [temp.expl.spec]p6:
4361 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004362 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004363 // before the first use of that specialization that would cause an implicit
4364 // instantiation to take place, in every translation unit in which such a
4365 // use occurs; no diagnostic is required.
4366 FunctionTemplateSpecializationInfo *SpecInfo
4367 = Specialization->getTemplateSpecializationInfo();
4368 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004369
4370 bool SuppressNew = false;
John McCall816d75b2010-03-24 07:46:06 +00004371 if (!isFriend &&
4372 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004373 TSK_ExplicitSpecialization,
4374 Specialization,
4375 SpecInfo->getTemplateSpecializationKind(),
4376 SpecInfo->getPointOfInstantiation(),
4377 SuppressNew))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004378 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004379
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004380 // Mark the prior declaration as an explicit specialization, so that later
4381 // clients know that this is an explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004382 if (!isFriend)
4383 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004384
4385 // Turn the given function declaration into a function template
4386 // specialization, with the template arguments from the previous
4387 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004388 // Take copies of (semantic and syntactic) template argument lists.
4389 const TemplateArgumentList* TemplArgs = new (Context)
4390 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4391 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4392 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004393 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004394 TemplArgs, /*InsertPos=*/0,
4395 SpecInfo->getTemplateSpecializationKind(),
4396 TemplArgsAsWritten);
4397
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004398 // The "previous declaration" for this function template specialization is
4399 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004400 Previous.clear();
4401 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004402 return false;
4403}
4404
Douglas Gregor86d142a2009-10-08 07:24:58 +00004405/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004406/// specialization.
4407///
4408/// This routine performs all of the semantic analysis required for an
4409/// explicit member function specialization. On successful completion,
4410/// the function declaration \p FD will become a member function
4411/// specialization.
4412///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004413/// \param Member the member declaration, which will be updated to become a
4414/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004415///
John McCall1f82f242009-11-18 22:49:29 +00004416/// \param Previous the set of declarations, one of which may be specialized
4417/// by this function specialization; the set will be modified to contain the
4418/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004419bool
John McCall1f82f242009-11-18 22:49:29 +00004420Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004421 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004422
Douglas Gregor86d142a2009-10-08 07:24:58 +00004423 // Try to find the member we are instantiating.
4424 NamedDecl *Instantiation = 0;
4425 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004426 MemberSpecializationInfo *MSInfo = 0;
4427
John McCall1f82f242009-11-18 22:49:29 +00004428 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004429 // Nowhere to look anyway.
4430 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004431 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4432 I != E; ++I) {
4433 NamedDecl *D = (*I)->getUnderlyingDecl();
4434 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004435 if (Context.hasSameType(Function->getType(), Method->getType())) {
4436 Instantiation = Method;
4437 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004438 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004439 break;
4440 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004441 }
4442 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004443 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004444 VarDecl *PrevVar;
4445 if (Previous.isSingleResult() &&
4446 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004447 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004448 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004449 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004450 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004451 }
4452 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004453 CXXRecordDecl *PrevRecord;
4454 if (Previous.isSingleResult() &&
4455 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4456 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004457 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004458 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004459 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004460 }
4461
4462 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004463 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004464 // specializations are always out-of-line, the caller will complain about
4465 // this mismatch later.
4466 return false;
4467 }
John McCalle820e5e2010-04-13 20:37:33 +00004468
4469 // If this is a friend, just bail out here before we start turning
4470 // things into explicit specializations.
4471 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4472 // Preserve instantiation information.
4473 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4474 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4475 cast<CXXMethodDecl>(InstantiatedFrom),
4476 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4477 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4478 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4479 cast<CXXRecordDecl>(InstantiatedFrom),
4480 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4481 }
4482
4483 Previous.clear();
4484 Previous.addDecl(Instantiation);
4485 return false;
4486 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004487
Douglas Gregor86d142a2009-10-08 07:24:58 +00004488 // Make sure that this is a specialization of a member.
4489 if (!InstantiatedFrom) {
4490 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4491 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004492 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4493 return true;
4494 }
4495
Douglas Gregor06db9f52009-10-12 20:18:28 +00004496 // C++ [temp.expl.spec]p6:
4497 // If a template, a member template or the member of a class template is
4498 // explicitly specialized then that spe- cialization shall be declared
4499 // before the first use of that specialization that would cause an implicit
4500 // instantiation to take place, in every translation unit in which such a
4501 // use occurs; no diagnostic is required.
4502 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004503
4504 bool SuppressNew = false;
4505 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4506 TSK_ExplicitSpecialization,
4507 Instantiation,
4508 MSInfo->getTemplateSpecializationKind(),
4509 MSInfo->getPointOfInstantiation(),
4510 SuppressNew))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004511 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004512
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004513 // Check the scope of this explicit specialization.
4514 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004515 InstantiatedFrom,
4516 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004517 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004518 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004519
Douglas Gregor86d142a2009-10-08 07:24:58 +00004520 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004521 // the original declaration to note that it is an explicit specialization
4522 // (if it was previously an implicit instantiation). This latter step
4523 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004524 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004525 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4526 if (InstantiationFunction->getTemplateSpecializationKind() ==
4527 TSK_ImplicitInstantiation) {
4528 InstantiationFunction->setTemplateSpecializationKind(
4529 TSK_ExplicitSpecialization);
4530 InstantiationFunction->setLocation(Member->getLocation());
4531 }
4532
Douglas Gregor86d142a2009-10-08 07:24:58 +00004533 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4534 cast<CXXMethodDecl>(InstantiatedFrom),
4535 TSK_ExplicitSpecialization);
4536 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004537 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4538 if (InstantiationVar->getTemplateSpecializationKind() ==
4539 TSK_ImplicitInstantiation) {
4540 InstantiationVar->setTemplateSpecializationKind(
4541 TSK_ExplicitSpecialization);
4542 InstantiationVar->setLocation(Member->getLocation());
4543 }
4544
Douglas Gregor86d142a2009-10-08 07:24:58 +00004545 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4546 cast<VarDecl>(InstantiatedFrom),
4547 TSK_ExplicitSpecialization);
4548 } else {
4549 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004550 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4551 if (InstantiationClass->getTemplateSpecializationKind() ==
4552 TSK_ImplicitInstantiation) {
4553 InstantiationClass->setTemplateSpecializationKind(
4554 TSK_ExplicitSpecialization);
4555 InstantiationClass->setLocation(Member->getLocation());
4556 }
4557
Douglas Gregor86d142a2009-10-08 07:24:58 +00004558 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004559 cast<CXXRecordDecl>(InstantiatedFrom),
4560 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004561 }
4562
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004563 // Save the caller the trouble of having to figure out which declaration
4564 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004565 Previous.clear();
4566 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004567 return false;
4568}
4569
Douglas Gregore47f5a72009-10-14 23:41:34 +00004570/// \brief Check the scope of an explicit instantiation.
4571static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4572 SourceLocation InstLoc,
4573 bool WasQualifiedName) {
4574 DeclContext *ExpectedContext
4575 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4576 DeclContext *CurContext = S.CurContext->getLookupContext();
4577
4578 // C++0x [temp.explicit]p2:
4579 // An explicit instantiation shall appear in an enclosing namespace of its
4580 // template.
4581 //
4582 // This is DR275, which we do not retroactively apply to C++98/03.
4583 if (S.getLangOptions().CPlusPlus0x &&
4584 !CurContext->Encloses(ExpectedContext)) {
4585 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004586 S.Diag(InstLoc,
4587 S.getLangOptions().CPlusPlus0x?
4588 diag::err_explicit_instantiation_out_of_scope
4589 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004590 << D << NS;
4591 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004592 S.Diag(InstLoc,
4593 S.getLangOptions().CPlusPlus0x?
4594 diag::err_explicit_instantiation_must_be_global
4595 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004596 << D;
4597 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4598 return;
4599 }
4600
4601 // C++0x [temp.explicit]p2:
4602 // If the name declared in the explicit instantiation is an unqualified
4603 // name, the explicit instantiation shall appear in the namespace where
4604 // its template is declared or, if that namespace is inline (7.3.1), any
4605 // namespace from its enclosing namespace set.
4606 if (WasQualifiedName)
4607 return;
4608
4609 if (CurContext->Equals(ExpectedContext))
4610 return;
4611
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004612 S.Diag(InstLoc,
4613 S.getLangOptions().CPlusPlus0x?
4614 diag::err_explicit_instantiation_unqualified_wrong_namespace
4615 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004616 << D << ExpectedContext;
4617 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4618}
4619
4620/// \brief Determine whether the given scope specifier has a template-id in it.
4621static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4622 if (!SS.isSet())
4623 return false;
4624
4625 // C++0x [temp.explicit]p2:
4626 // If the explicit instantiation is for a member function, a member class
4627 // or a static data member of a class template specialization, the name of
4628 // the class template specialization in the qualified-id for the member
4629 // name shall be a simple-template-id.
4630 //
4631 // C++98 has the same restriction, just worded differently.
4632 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4633 NNS; NNS = NNS->getPrefix())
4634 if (Type *T = NNS->getAsType())
4635 if (isa<TemplateSpecializationType>(T))
4636 return true;
4637
4638 return false;
4639}
4640
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004641// Explicit instantiation of a class template specialization
Douglas Gregora1f49972009-05-13 00:25:59 +00004642Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004643Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004644 SourceLocation ExternLoc,
4645 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004646 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004647 SourceLocation KWLoc,
4648 const CXXScopeSpec &SS,
4649 TemplateTy TemplateD,
4650 SourceLocation TemplateNameLoc,
4651 SourceLocation LAngleLoc,
4652 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004653 SourceLocation RAngleLoc,
4654 AttributeList *Attr) {
4655 // Find the class template we're specializing
4656 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004657 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004658 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4659
4660 // Check that the specialization uses the same tag kind as the
4661 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004662 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4663 assert(Kind != TTK_Enum &&
4664 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004665 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004666 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004667 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004668 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004669 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004670 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004671 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004672 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004673 diag::note_previous_use);
4674 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4675 }
4676
Douglas Gregore47f5a72009-10-14 23:41:34 +00004677 // C++0x [temp.explicit]p2:
4678 // There are two forms of explicit instantiation: an explicit instantiation
4679 // definition and an explicit instantiation declaration. An explicit
4680 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004681 TemplateSpecializationKind TSK
4682 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4683 : TSK_ExplicitInstantiationDeclaration;
4684
Douglas Gregora1f49972009-05-13 00:25:59 +00004685 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004686 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004687 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004688
4689 // Check that the template argument list is well-formed for this
4690 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004691 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4692 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004693 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4694 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004695 return true;
4696
Mike Stump11289f42009-09-09 15:08:12 +00004697 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004698 ClassTemplate->getTemplateParameters()->size()) &&
4699 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004700
Douglas Gregora1f49972009-05-13 00:25:59 +00004701 // Find the class template specialization declaration that
4702 // corresponds to these arguments.
4703 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004704 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004705 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004706 Converted.flatSize(),
4707 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004708 void *InsertPos = 0;
4709 ClassTemplateSpecializationDecl *PrevDecl
4710 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4711
Douglas Gregor54888652009-10-07 00:13:32 +00004712 // C++0x [temp.explicit]p2:
4713 // [...] An explicit instantiation shall appear in an enclosing
4714 // namespace of its template. [...]
4715 //
4716 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004717 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4718 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004719
Douglas Gregora1f49972009-05-13 00:25:59 +00004720 ClassTemplateSpecializationDecl *Specialization = 0;
4721
Douglas Gregor0681a352009-11-25 06:01:46 +00004722 bool ReusedDecl = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004723 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00004724 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004725 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004726 PrevDecl,
4727 PrevDecl->getSpecializationKind(),
4728 PrevDecl->getPointOfInstantiation(),
4729 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00004730 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004731
Douglas Gregor12e49d32009-10-15 22:53:21 +00004732 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004733 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00004734
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004735 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4736 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4737 // Since the only prior class template specialization with these
4738 // arguments was referenced but not declared, reuse that
4739 // declaration node as our own, updating its source location to
4740 // reflect our new declaration.
4741 Specialization = PrevDecl;
4742 Specialization->setLocation(TemplateNameLoc);
4743 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004744 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004745 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004746 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004747
4748 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004749 // Create a new class template specialization declaration node for
4750 // this explicit specialization.
4751 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004752 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00004753 ClassTemplate->getDeclContext(),
4754 TemplateNameLoc,
4755 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004756 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004757 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004758
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004759 if (PrevDecl) {
4760 // Remove the previous declaration from the folding set, since we want
4761 // to introduce a new declaration.
4762 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4763 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4764 }
4765
4766 // Insert the new specialization.
4767 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004768 }
4769
4770 // Build the fully-sugared type for this explicit instantiation as
4771 // the user wrote in the explicit instantiation itself. This means
4772 // that we'll pretty-print the type retrieved from the
4773 // specialization's declaration the way that the user actually wrote
4774 // the explicit instantiation, rather than formatting the name based
4775 // on the "canonical" representation used to store the template
4776 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004777 TypeSourceInfo *WrittenTy
4778 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4779 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004780 Context.getTypeDeclType(Specialization));
4781 Specialization->setTypeAsWritten(WrittenTy);
4782 TemplateArgsIn.release();
4783
Douglas Gregor0681a352009-11-25 06:01:46 +00004784 if (!ReusedDecl) {
4785 // Add the explicit instantiation into its lexical context. However,
4786 // since explicit instantiations are never found by name lookup, we
4787 // just put it into the declaration context directly.
4788 Specialization->setLexicalDeclContext(CurContext);
4789 CurContext->addDecl(Specialization);
4790 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004791
4792 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004793 // A definition of a class template or class member template
4794 // shall be in scope at the point of the explicit instantiation of
4795 // the class template or class member template.
4796 //
4797 // This check comes when we actually try to perform the
4798 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004799 ClassTemplateSpecializationDecl *Def
4800 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004801 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004802 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004803 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor88d292c2010-05-13 16:44:06 +00004804 else if (TSK == TSK_ExplicitInstantiationDefinition)
4805 MarkVTableUsed(TemplateNameLoc, Specialization, true);
4806
Douglas Gregor1d957a32009-10-27 18:42:08 +00004807 // Instantiate the members of this class template specialization.
4808 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004809 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004810 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004811 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4812
4813 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4814 // TSK_ExplicitInstantiationDefinition
4815 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4816 TSK == TSK_ExplicitInstantiationDefinition)
4817 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004818
Douglas Gregor12e49d32009-10-15 22:53:21 +00004819 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004820 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004821
4822 return DeclPtrTy::make(Specialization);
4823}
4824
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004825// Explicit instantiation of a member class of a class template.
4826Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004827Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004828 SourceLocation ExternLoc,
4829 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004830 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004831 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004832 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004833 IdentifierInfo *Name,
4834 SourceLocation NameLoc,
4835 AttributeList *Attr) {
4836
Douglas Gregord6ab8742009-05-28 23:31:59 +00004837 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004838 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004839 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004840 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004841 MultiTemplateParamsArg(*this, 0, 0),
4842 Owned, IsDependent);
4843 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4844
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004845 if (!TagD)
4846 return true;
4847
4848 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4849 if (Tag->isEnum()) {
4850 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4851 << Context.getTypeDeclType(Tag);
4852 return true;
4853 }
4854
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004855 if (Tag->isInvalidDecl())
4856 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004857
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004858 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4859 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4860 if (!Pattern) {
4861 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4862 << Context.getTypeDeclType(Record);
4863 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4864 return true;
4865 }
4866
Douglas Gregore47f5a72009-10-14 23:41:34 +00004867 // C++0x [temp.explicit]p2:
4868 // If the explicit instantiation is for a class or member class, the
4869 // elaborated-type-specifier in the declaration shall include a
4870 // simple-template-id.
4871 //
4872 // C++98 has the same restriction, just worded differently.
4873 if (!ScopeSpecifierHasTemplateId(SS))
4874 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4875 << Record << SS.getRange();
4876
4877 // C++0x [temp.explicit]p2:
4878 // There are two forms of explicit instantiation: an explicit instantiation
4879 // definition and an explicit instantiation declaration. An explicit
4880 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004881 TemplateSpecializationKind TSK
4882 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4883 : TSK_ExplicitInstantiationDeclaration;
4884
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004885 // C++0x [temp.explicit]p2:
4886 // [...] An explicit instantiation shall appear in an enclosing
4887 // namespace of its template. [...]
4888 //
4889 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004890 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004891
4892 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004893 CXXRecordDecl *PrevDecl
4894 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004895 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004896 PrevDecl = Record;
4897 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004898 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4899 bool SuppressNew = false;
4900 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004901 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004902 PrevDecl,
4903 MSInfo->getTemplateSpecializationKind(),
4904 MSInfo->getPointOfInstantiation(),
4905 SuppressNew))
4906 return true;
4907 if (SuppressNew)
4908 return TagD;
4909 }
4910
Douglas Gregor12e49d32009-10-15 22:53:21 +00004911 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004912 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004913 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004914 // C++ [temp.explicit]p3:
4915 // A definition of a member class of a class template shall be in scope
4916 // at the point of an explicit instantiation of the member class.
4917 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004918 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004919 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004920 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4921 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004922 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4923 << Pattern;
4924 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004925 } else {
4926 if (InstantiateClass(NameLoc, Record, Def,
4927 getTemplateInstantiationArgs(Record),
4928 TSK))
4929 return true;
4930
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004931 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004932 if (!RecordDef)
4933 return true;
4934 }
4935 }
4936
4937 // Instantiate all of the members of the class.
4938 InstantiateClassMembers(NameLoc, RecordDef,
4939 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004940
Douglas Gregor88d292c2010-05-13 16:44:06 +00004941 if (TSK == TSK_ExplicitInstantiationDefinition)
4942 MarkVTableUsed(NameLoc, RecordDef, true);
4943
Mike Stump87c57ac2009-05-16 07:39:55 +00004944 // FIXME: We don't have any representation for explicit instantiations of
4945 // member classes. Such a representation is not needed for compilation, but it
4946 // should be available for clients that want to see all of the declarations in
4947 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004948 return TagD;
4949}
4950
Douglas Gregor450f00842009-09-25 18:43:00 +00004951Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4952 SourceLocation ExternLoc,
4953 SourceLocation TemplateLoc,
4954 Declarator &D) {
4955 // Explicit instantiations always require a name.
4956 DeclarationName Name = GetNameForDeclarator(D);
4957 if (!Name) {
4958 if (!D.isInvalidType())
4959 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4960 diag::err_explicit_instantiation_requires_name)
4961 << D.getDeclSpec().getSourceRange()
4962 << D.getSourceRange();
4963
4964 return true;
4965 }
4966
4967 // The scope passed in may not be a decl scope. Zip up the scope tree until
4968 // we find one that is.
4969 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4970 (S->getFlags() & Scope::TemplateParamScope) != 0)
4971 S = S->getParent();
4972
4973 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00004974 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
4975 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00004976 if (R.isNull())
4977 return true;
4978
4979 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4980 // Cannot explicitly instantiate a typedef.
4981 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4982 << Name;
4983 return true;
4984 }
4985
Douglas Gregor3c74d412009-10-14 20:14:33 +00004986 // C++0x [temp.explicit]p1:
4987 // [...] An explicit instantiation of a function template shall not use the
4988 // inline or constexpr specifiers.
4989 // Presumably, this also applies to member functions of class templates as
4990 // well.
4991 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4992 Diag(D.getDeclSpec().getInlineSpecLoc(),
4993 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00004994 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004995
4996 // FIXME: check for constexpr specifier.
4997
Douglas Gregore47f5a72009-10-14 23:41:34 +00004998 // C++0x [temp.explicit]p2:
4999 // There are two forms of explicit instantiation: an explicit instantiation
5000 // definition and an explicit instantiation declaration. An explicit
5001 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00005002 TemplateSpecializationKind TSK
5003 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5004 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005005
John McCall27b18f82009-11-17 02:14:36 +00005006 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
5007 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00005008
5009 if (!R->isFunctionType()) {
5010 // C++ [temp.explicit]p1:
5011 // A [...] static data member of a class template can be explicitly
5012 // instantiated from the member definition associated with its class
5013 // template.
John McCall27b18f82009-11-17 02:14:36 +00005014 if (Previous.isAmbiguous())
5015 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00005016
John McCall67c00872009-12-02 08:25:40 +00005017 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005018 if (!Prev || !Prev->isStaticDataMember()) {
5019 // We expect to see a data data member here.
5020 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5021 << Name;
5022 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5023 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005024 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005025 return true;
5026 }
5027
5028 if (!Prev->getInstantiatedFromStaticDataMember()) {
5029 // FIXME: Check for explicit specialization?
5030 Diag(D.getIdentifierLoc(),
5031 diag::err_explicit_instantiation_data_member_not_instantiated)
5032 << Prev;
5033 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5034 // FIXME: Can we provide a note showing where this was declared?
5035 return true;
5036 }
5037
Douglas Gregore47f5a72009-10-14 23:41:34 +00005038 // C++0x [temp.explicit]p2:
5039 // If the explicit instantiation is for a member function, a member class
5040 // or a static data member of a class template specialization, the name of
5041 // the class template specialization in the qualified-id for the member
5042 // name shall be a simple-template-id.
5043 //
5044 // C++98 has the same restriction, just worded differently.
5045 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5046 Diag(D.getIdentifierLoc(),
5047 diag::err_explicit_instantiation_without_qualified_id)
5048 << Prev << D.getCXXScopeSpec().getRange();
5049
5050 // Check the scope of this explicit instantiation.
5051 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5052
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005053 // Verify that it is okay to explicitly instantiate here.
5054 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5055 assert(MSInfo && "Missing static data member specialization info?");
5056 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005057 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005058 MSInfo->getTemplateSpecializationKind(),
5059 MSInfo->getPointOfInstantiation(),
5060 SuppressNew))
5061 return true;
5062 if (SuppressNew)
5063 return DeclPtrTy();
5064
Douglas Gregor450f00842009-09-25 18:43:00 +00005065 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005066 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005067 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00005068 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
5069 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00005070
5071 // FIXME: Create an ExplicitInstantiation node?
5072 return DeclPtrTy();
5073 }
5074
Douglas Gregor0e876e02009-09-25 23:53:26 +00005075 // If the declarator is a template-id, translate the parser's template
5076 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005077 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005078 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005079 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5080 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005081 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5082 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005083 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5084 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005085 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005086 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005087 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005088 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005089 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005090
Douglas Gregor450f00842009-09-25 18:43:00 +00005091 // C++ [temp.explicit]p1:
5092 // A [...] function [...] can be explicitly instantiated from its template.
5093 // A member function [...] of a class template can be explicitly
5094 // instantiated from the member definition associated with its class
5095 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005096 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005097 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5098 P != PEnd; ++P) {
5099 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005100 if (!HasExplicitTemplateArgs) {
5101 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5102 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5103 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005104
John McCall58cc69d2010-01-27 01:50:18 +00005105 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005106 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5107 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005108 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005109 }
5110 }
5111
5112 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5113 if (!FunTmpl)
5114 continue;
5115
John McCallbc077cf2010-02-08 23:07:23 +00005116 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005117 FunctionDecl *Specialization = 0;
5118 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005119 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005120 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005121 R, Specialization, Info)) {
5122 // FIXME: Keep track of almost-matches?
5123 (void)TDK;
5124 continue;
5125 }
5126
John McCall58cc69d2010-01-27 01:50:18 +00005127 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005128 }
5129
5130 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005131 UnresolvedSetIterator Result
5132 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005133 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005134 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5135 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5136 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005137
John McCall58cc69d2010-01-27 01:50:18 +00005138 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005139 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005140
5141 // Ignore access control bits, we don't need them for redeclaration checking.
5142 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005143
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005144 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005145 Diag(D.getIdentifierLoc(),
5146 diag::err_explicit_instantiation_member_function_not_instantiated)
5147 << Specialization
5148 << (Specialization->getTemplateSpecializationKind() ==
5149 TSK_ExplicitSpecialization);
5150 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5151 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005152 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005153
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005154 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005155 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5156 PrevDecl = Specialization;
5157
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005158 if (PrevDecl) {
5159 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005160 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005161 PrevDecl,
5162 PrevDecl->getTemplateSpecializationKind(),
5163 PrevDecl->getPointOfInstantiation(),
5164 SuppressNew))
5165 return true;
5166
5167 // FIXME: We may still want to build some representation of this
5168 // explicit specialization.
5169 if (SuppressNew)
5170 return DeclPtrTy();
5171 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005172
5173 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005174
5175 if (TSK == TSK_ExplicitInstantiationDefinition)
5176 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5177 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005178
Douglas Gregore47f5a72009-10-14 23:41:34 +00005179 // C++0x [temp.explicit]p2:
5180 // If the explicit instantiation is for a member function, a member class
5181 // or a static data member of a class template specialization, the name of
5182 // the class template specialization in the qualified-id for the member
5183 // name shall be a simple-template-id.
5184 //
5185 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005186 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005187 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005188 D.getCXXScopeSpec().isSet() &&
5189 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5190 Diag(D.getIdentifierLoc(),
5191 diag::err_explicit_instantiation_without_qualified_id)
5192 << Specialization << D.getCXXScopeSpec().getRange();
5193
5194 CheckExplicitInstantiationScope(*this,
5195 FunTmpl? (NamedDecl *)FunTmpl
5196 : Specialization->getInstantiatedFromMemberFunction(),
5197 D.getIdentifierLoc(),
5198 D.getCXXScopeSpec().isSet());
5199
Douglas Gregor450f00842009-09-25 18:43:00 +00005200 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5201 return DeclPtrTy();
5202}
5203
Douglas Gregor333489b2009-03-27 23:10:48 +00005204Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005205Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5206 const CXXScopeSpec &SS, IdentifierInfo *Name,
5207 SourceLocation TagLoc, SourceLocation NameLoc) {
5208 // This has to hold, because SS is expected to be defined.
5209 assert(Name && "Expected a name in a dependent tag");
5210
5211 NestedNameSpecifier *NNS
5212 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5213 if (!NNS)
5214 return true;
5215
Abramo Bagnara6150c882010-05-11 21:36:43 +00005216 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005217
Douglas Gregorba41d012010-04-24 16:38:41 +00005218 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5219 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005220 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005221 return true;
5222 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005223
5224 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5225 return Context.getDependentNameType(Kwd, NNS, Name).getAsOpaquePtr();
John McCall7f41d982009-09-11 04:59:25 +00005226}
5227
5228Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00005229Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5230 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005231 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005232 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5233 if (!NNS)
5234 return true;
5235
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005236 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005237 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005238 if (T.isNull())
5239 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005240
5241 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5242 if (isa<DependentNameType>(T)) {
5243 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005244 TL.setKeywordLoc(TypenameLoc);
5245 TL.setQualifierRange(SS.getRange());
5246 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005247 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005248 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005249 TL.setKeywordLoc(TypenameLoc);
5250 TL.setQualifierRange(SS.getRange());
5251 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005252 }
5253
5254 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor333489b2009-03-27 23:10:48 +00005255}
5256
Douglas Gregordce2b622009-04-01 00:28:59 +00005257Sema::TypeResult
5258Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5259 SourceLocation TemplateLoc, TypeTy *Ty) {
John McCallf7bcc812010-05-28 23:32:21 +00005260 TypeSourceInfo *InnerTSI = 0;
5261 QualType T = GetTypeFromParser(Ty, &InnerTSI);
Mike Stump11289f42009-09-09 15:08:12 +00005262 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00005263 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
John McCallf7bcc812010-05-28 23:32:21 +00005264
5265 assert(isa<TemplateSpecializationType>(T) &&
5266 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005267
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005268 if (computeDeclContext(SS, false)) {
5269 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005270 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005271 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005272
5273 // Push the inner type, preserving its source locations if possible.
5274 TypeLocBuilder Builder;
5275 if (InnerTSI)
5276 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5277 else
5278 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5279
Abramo Bagnara6150c882010-05-11 21:36:43 +00005280 T = Context.getElaboratedType(ETK_Typename, NNS, T);
John McCallf7bcc812010-05-28 23:32:21 +00005281 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5282 TL.setKeywordLoc(TypenameLoc);
5283 TL.setQualifierRange(SS.getRange());
5284
5285 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCall99b2fe52010-04-29 23:50:39 +00005286 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005287 }
Mike Stump11289f42009-09-09 15:08:12 +00005288
John McCallf7bcc812010-05-28 23:32:21 +00005289 T = Context.getDependentNameType(ETK_Typename, NNS,
5290 cast<TemplateSpecializationType>(T));
John McCall99b2fe52010-04-29 23:50:39 +00005291 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5292 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005293 TL.setKeywordLoc(TypenameLoc);
5294 TL.setQualifierRange(SS.getRange());
5295
5296 // FIXME: the inner type is a template here; remember its full source info
5297 TL.setNameLoc(InnerTSI ? InnerTSI->getTypeLoc().getBeginLoc() : TemplateLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005298 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00005299}
5300
Douglas Gregor333489b2009-03-27 23:10:48 +00005301/// \brief Build the type that describes a C++ typename specifier,
5302/// e.g., "typename T::type".
5303QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005304Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5305 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005306 SourceLocation KeywordLoc, SourceRange NNSRange,
5307 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005308 CXXScopeSpec SS;
5309 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005310 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005311
John McCall0b66eb32010-05-01 00:40:08 +00005312 DeclContext *Ctx = computeDeclContext(SS);
5313 if (!Ctx) {
5314 // If the nested-name-specifier is dependent and couldn't be
5315 // resolved to a type, build a typename type.
5316 assert(NNS->isDependent());
5317 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005318 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005319
John McCall0b66eb32010-05-01 00:40:08 +00005320 // If the nested-name-specifier refers to the current instantiation,
5321 // the "typename" keyword itself is superfluous. In C++03, the
5322 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5323 // allows such extraneous "typename" keywords, and we retroactively
5324 // apply this DR to C++03 code. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005325
John McCall0b66eb32010-05-01 00:40:08 +00005326 if (RequireCompleteDeclContext(SS, Ctx))
5327 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005328
5329 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005330 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005331 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005332 unsigned DiagID = 0;
5333 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005334 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005335 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005336 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005337 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005338
5339 case LookupResult::NotFoundInCurrentInstantiation:
5340 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005341 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005342
5343 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00005344 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005345 // We found a type. Build an ElaboratedType, since the
5346 // typename-specifier was just sugar.
5347 return Context.getElaboratedType(ETK_Typename, NNS,
5348 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005349 }
5350
5351 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005352 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005353 break;
5354
John McCalle61f2ba2009-11-18 02:36:19 +00005355 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005356 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005357 return QualType();
5358
Douglas Gregor333489b2009-03-27 23:10:48 +00005359 case LookupResult::FoundOverloaded:
5360 DiagID = diag::err_typename_nested_not_type;
5361 Referenced = *Result.begin();
5362 break;
5363
John McCall6538c932009-10-10 05:48:19 +00005364 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005365 return QualType();
5366 }
5367
5368 // If we get here, it's because name lookup did not find a
5369 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005370 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5371 IILoc);
5372 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005373 if (Referenced)
5374 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5375 << Name;
5376 return QualType();
5377}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005378
5379namespace {
5380 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005381 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005382 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005383 SourceLocation Loc;
5384 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005385
Douglas Gregor15acfb92009-08-06 16:20:37 +00005386 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005387 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5388
Mike Stump11289f42009-09-09 15:08:12 +00005389 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005390 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005391 DeclarationName Entity)
5392 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005393 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005394
5395 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005396 /// transformed.
5397 ///
5398 /// For the purposes of type reconstruction, a type has already been
5399 /// transformed if it is NULL or if it is not dependent.
5400 bool AlreadyTransformed(QualType T) {
5401 return T.isNull() || !T->isDependentType();
5402 }
Mike Stump11289f42009-09-09 15:08:12 +00005403
5404 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005405 /// rebuilt.
5406 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005407
Douglas Gregor15acfb92009-08-06 16:20:37 +00005408 /// \brief Returns the name of the entity whose type is being rebuilt.
5409 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005410
Douglas Gregoref6ab412009-10-27 06:26:26 +00005411 /// \brief Sets the "base" location and entity when that
5412 /// information is known based on another transformation.
5413 void setBase(SourceLocation Loc, DeclarationName Entity) {
5414 this->Loc = Loc;
5415 this->Entity = Entity;
5416 }
5417
Douglas Gregor15acfb92009-08-06 16:20:37 +00005418 /// \brief Transforms an expression by returning the expression itself
5419 /// (an identity function).
5420 ///
5421 /// FIXME: This is completely unsafe; we will need to actually clone the
5422 /// expressions.
5423 Sema::OwningExprResult TransformExpr(Expr *E) {
Douglas Gregor14cf7522010-04-30 18:55:50 +00005424 return getSema().Owned(E->Retain());
Douglas Gregor15acfb92009-08-06 16:20:37 +00005425 }
Mike Stump11289f42009-09-09 15:08:12 +00005426
Douglas Gregor15acfb92009-08-06 16:20:37 +00005427 /// \brief Transforms a typename type by determining whether the type now
5428 /// refers to a member of the current instantiation, and then
Abramo Bagnara6150c882010-05-11 21:36:43 +00005429 /// type-checking and building an ElaboratedType (when possible).
5430 QualType TransformDependentNameType(TypeLocBuilder &TLB,
5431 DependentNameTypeLoc TL,
5432 QualType ObjectType);
Douglas Gregor15acfb92009-08-06 16:20:37 +00005433 };
5434}
5435
Mike Stump11289f42009-09-09 15:08:12 +00005436QualType
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005437CurrentInstantiationRebuilder::TransformDependentNameType(TypeLocBuilder &TLB,
5438 DependentNameTypeLoc TL,
Douglas Gregorfe17d252010-02-16 19:09:40 +00005439 QualType ObjectType) {
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005440 DependentNameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00005441
Douglas Gregor15acfb92009-08-06 16:20:37 +00005442 NestedNameSpecifier *NNS
5443 = TransformNestedNameSpecifier(T->getQualifier(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00005444 TL.getQualifierRange(),
Douglas Gregorfe17d252010-02-16 19:09:40 +00005445 ObjectType);
Douglas Gregor15acfb92009-08-06 16:20:37 +00005446 if (!NNS)
5447 return QualType();
5448
5449 // If the nested-name-specifier did not change, and we cannot compute the
5450 // context corresponding to the nested-name-specifier, then this
5451 // typename type will not change; exit early.
5452 CXXScopeSpec SS;
Abramo Bagnarad7548482010-05-19 21:37:53 +00005453 SS.setRange(TL.getQualifierRange());
Douglas Gregor15acfb92009-08-06 16:20:37 +00005454 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00005455
5456 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00005457 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00005458 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00005459
5460 // Rebuild the typename type, which will probably turn into a
Abramo Bagnara6150c882010-05-11 21:36:43 +00005461 // ElaboratedType.
John McCall0ad16662009-10-29 08:12:44 +00005462 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00005463 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00005464 = TransformType(QualType(TemplateId, 0));
5465 if (NewTemplateId.isNull())
5466 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005467
Douglas Gregor15acfb92009-08-06 16:20:37 +00005468 if (NNS == T->getQualifier() &&
5469 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00005470 Result = QualType(T, 0);
5471 else
Abramo Bagnarad7548482010-05-19 21:37:53 +00005472 Result = getDerived().RebuildDependentNameType(T->getKeyword(),
Douglas Gregor02085352010-03-31 20:19:30 +00005473 NNS, NewTemplateId);
John McCall0ad16662009-10-29 08:12:44 +00005474 } else
Abramo Bagnarad7548482010-05-19 21:37:53 +00005475 Result = getDerived().RebuildDependentNameType(T->getKeyword(), NNS,
5476 T->getIdentifier(),
5477 TL.getKeywordLoc(),
5478 TL.getQualifierRange(),
5479 TL.getNameLoc());
Mike Stump11289f42009-09-09 15:08:12 +00005480
Douglas Gregor281c4862010-03-07 23:26:22 +00005481 if (Result.isNull())
5482 return QualType();
5483
Abramo Bagnarad7548482010-05-19 21:37:53 +00005484 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
5485 QualType NamedT = ElabT->getNamedType();
5486 if (isa<TemplateSpecializationType>(NamedT)) {
5487 TemplateSpecializationTypeLoc NamedTLoc
5488 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
5489 // FIXME: fill locations
5490 NamedTLoc.initializeLocal(TL.getNameLoc());
5491 } else {
5492 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
5493 }
5494 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5495 NewTL.setKeywordLoc(TL.getKeywordLoc());
5496 NewTL.setQualifierRange(TL.getQualifierRange());
5497 }
5498 else {
5499 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
5500 NewTL.setKeywordLoc(TL.getKeywordLoc());
5501 NewTL.setQualifierRange(TL.getQualifierRange());
5502 NewTL.setNameLoc(TL.getNameLoc());
5503 }
John McCall0ad16662009-10-29 08:12:44 +00005504 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00005505}
5506
5507/// \brief Rebuilds a type within the context of the current instantiation.
5508///
Mike Stump11289f42009-09-09 15:08:12 +00005509/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005510/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005511/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005512/// partial specialization thereof). This routine will rebuild that type now
5513/// that we have entered the declarator's scope, which may produce different
5514/// canonical types, e.g.,
5515///
5516/// \code
5517/// template<typename T>
5518/// struct X {
5519/// typedef T* pointer;
5520/// pointer data();
5521/// };
5522///
5523/// template<typename T>
5524/// typename X<T>::pointer X<T>::data() { ... }
5525/// \endcode
5526///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005527/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005528/// since we do not know that we can look into X<T> when we parsed the type.
5529/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005530/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005531/// as the canonical type of T*, allowing the return types of the out-of-line
5532/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005533TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5534 SourceLocation Loc,
5535 DeclarationName Name) {
5536 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005537 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005538
Douglas Gregor15acfb92009-08-06 16:20:37 +00005539 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5540 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005541}
Douglas Gregorbe999392009-09-15 16:23:51 +00005542
John McCall99b2fe52010-04-29 23:50:39 +00005543bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5544 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005545
5546 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5547 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5548 DeclarationName());
5549 NestedNameSpecifier *Rebuilt =
5550 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005551 if (!Rebuilt) return true;
5552
5553 SS.setScopeRep(Rebuilt);
5554 return false;
John McCall2408e322010-04-27 00:57:59 +00005555}
5556
Douglas Gregorbe999392009-09-15 16:23:51 +00005557/// \brief Produces a formatted string that describes the binding of
5558/// template parameters to template arguments.
5559std::string
5560Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5561 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005562 // FIXME: For variadic templates, we'll need to get the structured list.
5563 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5564 Args.flat_size());
5565}
5566
5567std::string
5568Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5569 const TemplateArgument *Args,
5570 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005571 std::string Result;
5572
Douglas Gregore62e6a02009-11-11 19:13:48 +00005573 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005574 return Result;
5575
5576 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005577 if (I >= NumArgs)
5578 break;
5579
Douglas Gregorbe999392009-09-15 16:23:51 +00005580 if (I == 0)
5581 Result += "[with ";
5582 else
5583 Result += ", ";
5584
5585 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5586 Result += Id->getName();
5587 } else {
5588 Result += '$';
5589 Result += llvm::utostr(I);
5590 }
5591
5592 Result += " = ";
5593
5594 switch (Args[I].getKind()) {
5595 case TemplateArgument::Null:
5596 Result += "<no value>";
5597 break;
5598
5599 case TemplateArgument::Type: {
5600 std::string TypeStr;
5601 Args[I].getAsType().getAsStringInternal(TypeStr,
5602 Context.PrintingPolicy);
5603 Result += TypeStr;
5604 break;
5605 }
5606
5607 case TemplateArgument::Declaration: {
5608 bool Unnamed = true;
5609 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5610 if (ND->getDeclName()) {
5611 Unnamed = false;
5612 Result += ND->getNameAsString();
5613 }
5614 }
5615
5616 if (Unnamed) {
5617 Result += "<anonymous>";
5618 }
5619 break;
5620 }
5621
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005622 case TemplateArgument::Template: {
5623 std::string Str;
5624 llvm::raw_string_ostream OS(Str);
5625 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5626 Result += OS.str();
5627 break;
5628 }
5629
Douglas Gregorbe999392009-09-15 16:23:51 +00005630 case TemplateArgument::Integral: {
5631 Result += Args[I].getAsIntegral()->toString(10);
5632 break;
5633 }
5634
5635 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005636 // FIXME: This is non-optimal, since we're regurgitating the
5637 // expression we were given.
5638 std::string Str;
5639 {
5640 llvm::raw_string_ostream OS(Str);
5641 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5642 Context.PrintingPolicy);
5643 }
5644 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005645 break;
5646 }
5647
5648 case TemplateArgument::Pack:
5649 // FIXME: Format template argument packs
5650 Result += "<template argument pack>";
5651 break;
5652 }
5653 }
5654
5655 Result += ']';
5656 return Result;
5657}