blob: 7e5377ab9a96b399130555ad4b5231700b5b959a [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor72c3f312008-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 Gregor99ebf652009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000011
12#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
John McCall92b7f702010-03-11 07:50:04 +000018#include "clang/AST/DeclFriend.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000020#include "clang/Parse/DeclSpec.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000021#include "clang/Parse/Template.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregor2dd078a2009-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.
John McCallad00b772010-06-16 08:42:20 +000030static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
31 NamedDecl *Orig) {
32 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000033
Douglas Gregor2dd078a2009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
John McCallad00b772010-06-16 08:42:20 +000035 return Orig;
Mike Stump1eb44332009-09-09 15:08:12 +000036
Douglas Gregor2dd078a2009-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 Gregor542b5482009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-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 Stump1eb44332009-09-09 15:08:12 +000058
Douglas Gregor2dd078a2009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump1eb44332009-09-09 15:08:12 +000061
Douglas Gregor2dd078a2009-09-02 22:59:36 +000062 return 0;
63}
64
John McCallf7a1a742009-11-24 19:00:30 +000065static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor01e56ae2010-04-12 20:54:26 +000066 // The set of class templates we've already seen.
67 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCallf7a1a742009-11-24 19:00:30 +000068 LookupResult::Filter filter = R.makeFilter();
69 while (filter.hasNext()) {
70 NamedDecl *Orig = filter.next();
John McCallad00b772010-06-16 08:42:20 +000071 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
John McCallf7a1a742009-11-24 19:00:30 +000072 if (!Repl)
73 filter.erase();
Douglas Gregor01e56ae2010-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 McCallf7a1a742009-11-24 19:00:30 +000092 filter.replace(Repl);
Douglas Gregor01e56ae2010-04-12 20:54:26 +000093 }
John McCallf7a1a742009-11-24 19:00:30 +000094 }
95 filter.done();
96}
97
Douglas Gregor2dd078a2009-09-02 22:59:36 +000098TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +000099 CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000100 UnqualifiedId &Name,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000101 TypeTy *ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000102 bool EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000103 TemplateTy &TemplateResult,
104 bool &MemberOfUnknownSpecialization) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000105 assert(getLangOptions().CPlusPlus && "No template names in C!");
106
Douglas Gregor014e88d2009-11-03 23:16:33 +0000107 DeclarationName TName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000108 MemberOfUnknownSpecialization = false;
Douglas Gregor014e88d2009-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
Sean Hunte6252d12009-11-28 08:58:14 +0000120 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +0000121 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
122 break;
Sean Hunte6252d12009-11-28 08:58:14 +0000123
Douglas Gregor014e88d2009-11-03 23:16:33 +0000124 default:
125 return TNK_Non_template;
126 }
Mike Stump1eb44332009-09-09 15:08:12 +0000127
John McCallf7a1a742009-11-24 19:00:30 +0000128 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Douglas Gregorbfea2392009-12-31 08:11:17 +0000130 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
131 LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +0000132 R.suppressDiagnostics();
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000133 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
134 MemberOfUnknownSpecialization);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000135 if (R.empty() || R.isAmbiguous())
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000136 return TNK_Non_template;
137
John McCall0bd6feb2009-12-02 08:04:21 +0000138 TemplateName Template;
139 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000140
John McCall0bd6feb2009-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 Gregor2dd078a2009-09-02 22:59:36 +0000147 } else {
John McCall0bd6feb2009-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 Gregor2dd078a2009-09-02 22:59:36 +0000164 }
Mike Stump1eb44332009-09-09 15:08:12 +0000165
John McCall0bd6feb2009-12-02 08:04:21 +0000166 TemplateResult = TemplateTy::make(Template);
167 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000168}
169
Douglas Gregor84d0a192010-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 Gregord5ab9b02010-05-21 23:43:39 +0000178 // FIXME: Typo correction?
Douglas Gregor84d0a192010-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 Gregor849b2432010-03-31 17:46:05 +0000188 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor84d0a192010-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 McCallf7a1a742009-11-24 19:00:30 +0000195void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000196 Scope *S, CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +0000197 QualType ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000198 bool EnteringContext,
199 bool &MemberOfUnknownSpecialization) {
John McCallf7a1a742009-11-24 19:00:30 +0000200 // Determine where to perform name lookup
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000201 MemberOfUnknownSpecialization = false;
John McCallf7a1a742009-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 McCall77bb1aa2010-05-01 00:40:08 +0000219 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCallf7a1a742009-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 Gregor2e933882010-01-12 17:06:20 +0000248 // We cannot look into a dependent object type or nested nme
249 // specifier.
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000250 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-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 Gregor2e933882010-01-12 17:06:20 +0000257 if (Found.empty() && !isDependent) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000258 // If we did not find any names, attempt to correct any typos.
259 DeclarationName Name = Found.getLookupName();
Douglas Gregoraaf87162010-04-14 20:04:41 +0000260 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000261 false, CTC_CXXCasts)) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000262 FilterAcceptableTemplateNames(Context, Found);
John McCallad00b772010-06-16 08:42:20 +0000263 if (!Found.empty()) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000264 if (LookupCtx)
265 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
266 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000267 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-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 Gregor849b2432010-03-31 17:46:05 +0000272 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000273 Found.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000274 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
275 Diag(Template->getLocation(), diag::note_previous_decl)
276 << Template->getDeclName();
John McCallad00b772010-06-16 08:42:20 +0000277 }
Douglas Gregorbfea2392009-12-31 08:11:17 +0000278 } else {
279 Found.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000280 Found.setLookupName(Name);
Douglas Gregorbfea2392009-12-31 08:11:17 +0000281 }
282 }
283
John McCallf7a1a742009-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 Gregor01e56ae2010-04-12 20:54:26 +0000298
John McCallf7a1a742009-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
John McCallad00b772010-06-16 08:42:20 +0000306 } else if (!Found.isSuppressingDiagnostics()) {
John McCallf7a1a742009-11-24 19:00:30 +0000307 // - 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 Yasskin21d07e42010-06-05 01:39:57 +0000314 diag::ext_nested_name_member_ref_lookup_ambiguous)
315 << Found.getLookupName()
316 << ObjectType;
John McCallf7a1a742009-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 McCall2f841ba2009-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 McCallf7a1a742009-11-24 19:00:30 +0000333Sema::OwningExprResult
334Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
335 DeclarationName Name,
336 SourceLocation NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +0000337 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000338 const TemplateArgumentListInfo *TemplateArgs) {
339 NestedNameSpecifier *Qualifier
340 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallea1471e2010-05-20 01:18:31 +0000341
342 DeclContext *DC = getFunctionLevelDeclContext();
John McCallf7a1a742009-11-24 19:00:30 +0000343
John McCall2f841ba2009-12-02 03:53:29 +0000344 if (!isAddressOfOperand &&
John McCallea1471e2010-05-20 01:18:31 +0000345 isa<CXXMethodDecl>(DC) &&
346 cast<CXXMethodDecl>(DC)->isInstance()) {
347 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2f841ba2009-12-02 03:53:29 +0000348
John McCallf7a1a742009-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 McCallaa81e162009-12-01 22:10:20 +0000353 return Owned(CXXDependentScopeMemberExpr::Create(Context,
354 /*This*/ 0, ThisType,
355 /*IsArrow*/ true,
John McCallf7a1a742009-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 Gregord6fb7ef2008-12-18 19:37:40 +0000376}
377
Douglas Gregor72c3f312008-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 Gregorf57172b2008-12-08 18:40:42 +0000383 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-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 Stump1eb44332009-09-09 15:08:12 +0000392 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-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 Gregor2943aed2009-03-03 04:44:36 +0000398/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-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 Lattnerb28317a2009-03-28 19:18:32 +0000401TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor13d2d6c2009-10-06 21:27:51 +0000402 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000403 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000404 return Temp;
405 }
406 return 0;
407}
408
Douglas Gregor788cd062009-11-11 01:00:40 +0000409static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
410 const ParsedTemplateArgument &Arg) {
411
412 switch (Arg.getKind()) {
413 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000414 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000415 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
416 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000417 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-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 Yasskin9f61aa92009-12-12 05:05:38 +0000435 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-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 McCalld5532b62009-11-23 01:53:49 +0000441void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
442 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000443 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000444 TemplateArgs.addArgument(translateTemplateArgument(*this,
445 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000446}
447
Douglas Gregor72c3f312008-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
Douglas Gregorefed5c82010-06-16 15:23:05 +0000454/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000455/// If the type parameter has a default argument, it will be added
456/// later via ActOnTypeParameterDefault.
Mike Stump1eb44332009-09-09 15:08:12 +0000457Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson941df7d2009-06-12 19:58:00 +0000458 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000459 SourceLocation KeyLoc,
460 IdentifierInfo *ParamName,
461 SourceLocation ParamNameLoc,
462 unsigned Depth, unsigned Position) {
Mike Stump1eb44332009-09-09 15:08:12 +0000463 assert(S->isTemplateParamScope() &&
464 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000465 bool Invalid = false;
466
467 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000468 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000469 LookupOrdinaryName,
470 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000471 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000472 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000473 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000474 }
475
Douglas Gregorddc29e12009-02-06 22:42:48 +0000476 SourceLocation Loc = ParamNameLoc;
477 if (!ParamName)
478 Loc = KeyLoc;
479
Douglas Gregor72c3f312008-12-05 18:15:24 +0000480 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000481 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
482 Loc, Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000483 Ellipsis);
Douglas Gregor72c3f312008-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 Lattnerb28317a2009-03-28 19:18:32 +0000489 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000490 IdResolver.AddDecl(Param);
491 }
492
Chris Lattnerb28317a2009-03-28 19:18:32 +0000493 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000494}
495
Douglas Gregord684b002009-02-10 19:49:53 +0000496/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump1eb44332009-09-09 15:08:12 +0000497/// Default) to the given template type parameter (TypeParam).
498void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000499 SourceLocation EqualLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000500 SourceLocation DefaultLoc,
Douglas Gregord684b002009-02-10 19:49:53 +0000501 TypeTy *DefaultT) {
Mike Stump1eb44332009-09-09 15:08:12 +0000502 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000503 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall833ca992009-10-29 08:12:44 +0000504
John McCalla93c9342009-12-07 02:54:59 +0000505 TypeSourceInfo *DefaultTInfo;
506 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall833ca992009-10-29 08:12:44 +0000507
John McCalla93c9342009-12-07 02:54:59 +0000508 assert(DefaultTInfo && "expected source information for type");
Douglas Gregord684b002009-02-10 19:49:53 +0000509
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000510 // C++0x [temp.param]p9:
511 // A default template-argument may be specified for any kind of
Mike Stump1eb44332009-09-09 15:08:12 +0000512 // template-parameter that is not a template parameter pack.
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000513 if (Parm->isParameterPack()) {
514 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000515 return;
516 }
Mike Stump1eb44332009-09-09 15:08:12 +0000517
Douglas Gregord684b002009-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 Stump1eb44332009-09-09 15:08:12 +0000521
Douglas Gregord684b002009-02-10 19:49:53 +0000522 // Check the template argument itself.
John McCalla93c9342009-12-07 02:54:59 +0000523 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000524 Parm->setInvalidDecl();
525 return;
526 }
527
John McCalla93c9342009-12-07 02:54:59 +0000528 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000529}
530
Douglas Gregor2943aed2009-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 Stump1eb44332009-09-09 15:08:12 +0000536QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000537Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora481ec42010-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 Gregor2943aed2009-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,
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000552 if (T->isIntegralOrEnumerationType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000553 // -- pointer to object or pointer to function,
554 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000555 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
556 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000557 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-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 Gregor0fddb972010-05-22 16:17:30 +0000576
Douglas Gregor2943aed2009-03-03 04:44:36 +0000577 Diag(Loc, diag::err_template_nontype_parm_bad_type)
578 << T;
579
580 return QualType();
581}
582
Douglas Gregor72c3f312008-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 Lattnerb28317a2009-03-28 19:18:32 +0000587Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump1eb44332009-09-09 15:08:12 +0000588 unsigned Depth,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000589 unsigned Position) {
John McCallbf1a0282010-06-04 23:28:52 +0000590 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
591 QualType T = TInfo->getType();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000592
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000593 assert(S->isTemplateParamScope() &&
594 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000595 bool Invalid = false;
596
597 IdentifierInfo *ParamName = D.getIdentifier();
598 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000599 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000600 LookupOrdinaryName,
601 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000602 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000603 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000604 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000605 }
606
Douglas Gregor2943aed2009-03-03 04:44:36 +0000607 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000608 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000609 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000610 Invalid = true;
611 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000612
Douglas Gregor72c3f312008-12-05 18:15:24 +0000613 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000614 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
615 D.getIdentifierLoc(),
John McCalla93c9342009-12-07 02:54:59 +0000616 Depth, Position, ParamName, T, TInfo);
Douglas Gregor72c3f312008-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 Lattnerb28317a2009-03-28 19:18:32 +0000622 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000623 IdResolver.AddDecl(Param);
624 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000625 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000626}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000627
Douglas Gregord684b002009-02-10 19:49:53 +0000628/// \brief Adds a default argument to the given non-type template
629/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000630void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000631 SourceLocation EqualLoc,
632 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000633 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000634 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000635 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Douglas Gregord684b002009-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 Stump1eb44332009-09-09 15:08:12 +0000640
Douglas Gregord684b002009-02-10 19:49:53 +0000641 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000642 TemplateArgument Converted;
643 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
644 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000645 TemplateParm->setInvalidDecl();
646 return;
647 }
648
Abramo Bagnarad92f7a22010-06-09 09:26:05 +0000649 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>(), false);
Douglas Gregord684b002009-02-10 19:49:53 +0000650}
651
Douglas Gregoraaba5e32009-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 Lattnerb28317a2009-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 Stump1eb44332009-09-09 15:08:12 +0000662 unsigned Position) {
Douglas Gregoraaba5e32009-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 McCall7a9813c2010-01-22 00:28:27 +0000668 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
669 TmpLoc, Depth, Position, Name,
Douglas Gregoraaba5e32009-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 Lattnerb28317a2009-03-28 19:18:32 +0000684 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000685 IdResolver.AddDecl(Param);
686 }
687
Chris Lattnerb28317a2009-03-28 19:18:32 +0000688 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000689}
690
Douglas Gregord684b002009-02-10 19:49:53 +0000691/// \brief Adds a default argument to the given template template
692/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000693void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000694 SourceLocation EqualLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +0000695 const ParsedTemplateArgument &Default) {
Mike Stump1eb44332009-09-09 15:08:12 +0000696 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000697 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor788cd062009-11-11 01:00:40 +0000698
Douglas Gregord684b002009-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 Gregor9148c3f2009-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 Gregor788cd062009-11-11 01:00:40 +0000711 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregor9148c3f2009-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 Gregord684b002009-02-10 19:49:53 +0000715 return;
716 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000717
Abramo Bagnarad92f7a22010-06-09 09:26:05 +0000718 TemplateParm->setDefaultArgument(DefaultArg, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000719}
720
Douglas Gregorc4b4e7b2008-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 Stump1eb44332009-09-09 15:08:12 +0000726 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000727 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000728 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000729 SourceLocation RAngleLoc) {
730 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000731 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000732
Douglas Gregorddc29e12009-02-06 22:42:48 +0000733 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000734 (NamedDecl**)Params, NumParams,
735 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000736}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000737
John McCallb6217662010-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 Gregor212e81c2009-03-25 00:13:59 +0000744Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000745Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000746 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000747 IdentifierInfo *Name, SourceLocation NameLoc,
748 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000749 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000750 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000751 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000752 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000753 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000754 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000755
756 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000757 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000758 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000759
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000760 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
761 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-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 Gregor212e81c2009-03-25 00:13:59 +0000766 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000767 }
768
769 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000770 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000771 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000772 ForRedeclaration);
Douglas Gregor05396e22009-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 Stump1eb44332009-09-09 15:08:12 +0000779
John McCall77bb1aa2010-05-01 00:40:08 +0000780 if (RequireCompleteDeclContext(SS, SemanticContext))
781 return true;
782
John McCalla24dc2e2009-11-17 02:14:36 +0000783 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000784 } else {
785 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000786 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000787 }
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Douglas Gregor57265e32010-04-12 16:00:01 +0000789 if (Previous.isAmbiguous())
790 return true;
791
Douglas Gregorddc29e12009-02-06 22:42:48 +0000792 NamedDecl *PrevDecl = 0;
793 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000794 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000795
Douglas Gregorddc29e12009-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 Stump1eb44332009-09-09 15:08:12 +0000798 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000799 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-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 McCall65c49462009-12-18 11:25:59 +0000816 if (TUK == TUK_Friend) {
John McCalle129d442009-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 Gregorc1c9df72010-04-18 17:37:40 +0000822 if (!SS.isSet()) {
823 DeclContext *OutermostContext = CurContext;
824 while (!OutermostContext->isFileContext())
825 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000826
Douglas Gregorc1c9df72010-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 McCalle129d442009-12-17 23:21:11 +0000838 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000839
John McCalle129d442009-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 Gregor57265e32010-04-12 16:00:01 +0000849
Douglas Gregorddc29e12009-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 Gregorfb898e12009-11-12 16:20:59 +0000854 /*Complain=*/true,
855 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000856 return true;
Douglas Gregorddc29e12009-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 Gregor501c5ce2009-05-14 16:41:31 +0000864 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000865 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000866 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000867 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000868 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000869 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000870 }
871
Douglas Gregorddc29e12009-02-06 22:42:48 +0000872 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000873 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000874 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-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 Gregor212e81c2009-03-25 00:13:59 +0000879 return true;
Douglas Gregorddc29e12009-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 Gregor212e81c2009-03-25 00:13:59 +0000895 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000896 }
897
Douglas Gregord684b002009-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 Gregor5b6d70e2009-11-25 17:50:39 +0000902 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
903 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000904 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Douglas Gregor57265e32010-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 Stump1eb44332009-09-09 15:08:12 +0000915 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000916 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000917 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000918 PrevClassTemplate->getTemplatedDecl() : 0,
919 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000920 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000921
922 ClassTemplateDecl *NewTemplate
923 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
924 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000925 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000926 NewClass->setDescribedClassTemplate(NewTemplate);
927
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000928 // Build the type for the class template declaration now.
John McCall3cb0ebd2010-03-10 03:28:59 +0000929 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
930 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000931 assert(T->isDependentType() && "Class template type is not dependent?");
932 (void)T;
933
Douglas Gregorfd056bc2009-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 Carlsson4cbe82c2009-03-26 01:24:28 +0000940 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000941 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000942 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Douglas Gregorddc29e12009-02-06 22:42:48 +0000944 // Set the lexical context of these templates
945 NewClass->setLexicalDeclContext(CurContext);
946 NewTemplate->setLexicalDeclContext(CurContext);
947
John McCall0f434ec2009-07-31 02:45:11 +0000948 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000949 NewClass->startDefinition();
950
951 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000952 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000953
John McCall05b23ea2009-09-14 21:59:20 +0000954 if (TUK != TUK_Friend)
955 PushOnScopeChains(NewTemplate, S);
956 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000957 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000958 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000959 NewClass->setAccess(PrevClassTemplate->getAccess());
960 }
John McCall05b23ea2009-09-14 21:59:20 +0000961
Douglas Gregord85bea22009-09-26 06:47:28 +0000962 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
963 PrevClassTemplate != NULL);
964
John McCall05b23ea2009-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 Gregord85bea22009-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 McCall05b23ea2009-09-14 21:59:20 +0000980 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000981
Douglas Gregord684b002009-02-10 19:49:53 +0000982 if (Invalid) {
983 NewTemplate->setInvalidDecl();
984 NewClass->setInvalidDecl();
985 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000986 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000987}
988
Douglas Gregor5b6d70e2009-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 Gregord684b002009-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 Gregor5b6d70e2009-11-25 17:50:39 +00001056/// \param TPC Describes the context in which we are checking the given
1057/// template parameter list.
1058///
Douglas Gregord684b002009-02-10 19:49:53 +00001059/// \returns true if an error occurred, false otherwise.
1060bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001061 TemplateParameterList *OldParams,
1062 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001063 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Douglas Gregord684b002009-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 Gregorc15cb382009-02-09 23:23:08 +00001073
Anders Carlsson49d25572009-06-12 23:20:15 +00001074 bool SawParameterPack = false;
1075 SourceLocation ParameterPackLoc;
1076
Mike Stump1a35fde2009-02-11 23:03:27 +00001077 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001078 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-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 Carlsson49d25572009-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 Stump1eb44332009-09-09 15:08:12 +00001097 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001098 diag::err_template_param_pack_must_be_last_template_parameter);
1099 Invalid = true;
1100 }
1101
Douglas Gregord684b002009-02-10 19:49:53 +00001102 if (TemplateTypeParmDecl *NewTypeParm
1103 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-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 Bagnarabd054db2010-05-20 10:00:11 +00001109 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001110 NewTypeParm->removeDefaultArgument();
1111
1112 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001113 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001114 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Anders Carlsson49d25572009-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 Stump1eb44332009-09-09 15:08:12 +00001121 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001122 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-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 McCall833ca992009-10-29 08:12:44 +00001132 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-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 Stumpac5fc7c2009-08-04 21:02:39 +00001140 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001141 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-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);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001148 NewNonTypeParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001149 }
1150
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001151 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001152 NonTypeTemplateParmDecl *OldNonTypeParm
1153 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001154 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-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(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001169 OldNonTypeParm->getDefaultArgument(),
1170 /*Inherited=*/ true);
Douglas Gregord684b002009-02-10 19:49:53 +00001171 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1172 } else if (NewNonTypeParm->hasDefaultArgument()) {
1173 SawDefaultArgument = true;
1174 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1175 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001176 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001177 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001178 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001179 TemplateTemplateParmDecl *NewTemplateParm
1180 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001181 if (NewTemplateParm->hasDefaultArgument() &&
1182 DiagnoseDefaultTemplateArgument(*this, TPC,
1183 NewTemplateParm->getLocation(),
1184 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001185 NewTemplateParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001186
1187 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001188 TemplateTemplateParmDecl *OldTemplateParm
1189 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001190 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001191 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001192 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1193 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001194 SawDefaultArgument = true;
1195 RedundantDefaultArg = true;
1196 PreviousDefaultArgLoc = NewDefaultLoc;
1197 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1198 // Merge the default argument from the old declaration to the
1199 // new declaration.
1200 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001201 // FIXME: We need to create a new kind of "default argument" expression
1202 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001203 NewTemplateParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001204 OldTemplateParm->getDefaultArgument(),
1205 /*Inherited=*/ true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001206 PreviousDefaultArgLoc
1207 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001208 } else if (NewTemplateParm->hasDefaultArgument()) {
1209 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001210 PreviousDefaultArgLoc
1211 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001212 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001213 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001214 }
1215
1216 if (RedundantDefaultArg) {
1217 // C++ [temp.param]p12:
1218 // A template-parameter shall not be given default arguments
1219 // by two different declarations in the same scope.
1220 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1221 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1222 Invalid = true;
1223 } else if (MissingDefaultArg) {
1224 // C++ [temp.param]p11:
1225 // If a template-parameter has a default template-argument,
1226 // all subsequent template-parameters shall have a default
1227 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001228 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001229 diag::err_template_param_default_arg_missing);
1230 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1231 Invalid = true;
1232 }
1233
1234 // If we have an old template parameter list that we're merging
1235 // in, move on to the next parameter.
1236 if (OldParams)
1237 ++OldParam;
1238 }
1239
1240 return Invalid;
1241}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001242
Mike Stump1eb44332009-09-09 15:08:12 +00001243/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001244/// specifier, returning the template parameter list that applies to the
1245/// name.
1246///
1247/// \param DeclStartLoc the start of the declaration that has a scope
1248/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001249///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001250/// \param SS the scope specifier that will be matched to the given template
1251/// parameter lists. This scope specifier precedes a qualified name that is
1252/// being declared.
1253///
1254/// \param ParamLists the template parameter lists, from the outermost to the
1255/// innermost template parameter lists.
1256///
1257/// \param NumParamLists the number of template parameter lists in ParamLists.
1258///
John McCall77e8b112010-04-13 20:37:33 +00001259/// \param IsFriend Whether to apply the slightly different rules for
1260/// matching template parameters to scope specifiers in friend
1261/// declarations.
1262///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001263/// \param IsExplicitSpecialization will be set true if the entity being
1264/// declared is an explicit specialization, false otherwise.
1265///
Mike Stump1eb44332009-09-09 15:08:12 +00001266/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001267/// name that is preceded by the scope specifier @p SS. This template
1268/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001269/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001270/// template specialization), or may be NULL (if we were's declaring isn't
1271/// itself a template).
1272TemplateParameterList *
1273Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1274 const CXXScopeSpec &SS,
1275 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001276 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001277 bool IsFriend,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001278 bool &IsExplicitSpecialization) {
1279 IsExplicitSpecialization = false;
1280
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001281 // Find the template-ids that occur within the nested-name-specifier. These
1282 // template-ids will match up with the template parameter lists.
1283 llvm::SmallVector<const TemplateSpecializationType *, 4>
1284 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001285 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1286 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001287 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1288 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001289 const Type *T = NNS->getAsType();
1290 if (!T) break;
1291
1292 // C++0x [temp.expl.spec]p17:
1293 // A member or a member template may be nested within many
1294 // enclosing class templates. In an explicit specialization for
1295 // such a member, the member declaration shall be preceded by a
1296 // template<> for each enclosing class template that is
1297 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001298 //
1299 // Following the existing practice of GNU and EDG, we allow a typedef of a
1300 // template specialization type.
1301 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1302 T = TT->LookThroughTypedefs().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001303
Mike Stump1eb44332009-09-09 15:08:12 +00001304 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001305 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001306 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1307 if (!Template)
1308 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Ted Kremenek6217b802009-07-29 21:53:49 +00001310 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001311 ClassTemplateSpecializationDecl *SpecDecl
1312 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1313 // If the nested name specifier refers to an explicit specialization,
1314 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001315 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1316 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001317 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001318 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001319 }
Mike Stump1eb44332009-09-09 15:08:12 +00001320
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001321 TemplateIdsInSpecifier.push_back(SpecType);
1322 }
1323 }
Mike Stump1eb44332009-09-09 15:08:12 +00001324
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001325 // Reverse the list of template-ids in the scope specifier, so that we can
1326 // more easily match up the template-ids and the template parameter lists.
1327 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001329 SourceLocation FirstTemplateLoc = DeclStartLoc;
1330 if (NumParamLists)
1331 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001333 // Match the template-ids found in the specifier to the template parameter
1334 // lists.
1335 unsigned Idx = 0;
1336 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1337 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001338 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1339 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001340 if (Idx >= NumParamLists) {
1341 // We have a template-id without a corresponding template parameter
1342 // list.
John McCall77e8b112010-04-13 20:37:33 +00001343
1344 // ...which is fine if this is a friend declaration.
1345 if (IsFriend) {
1346 IsExplicitSpecialization = true;
1347 break;
1348 }
1349
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001350 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001351 // FIXME: the location information here isn't great.
1352 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001353 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001354 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001355 << SS.getRange();
1356 } else {
1357 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1358 << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00001359 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001360 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001361 }
1362 return 0;
1363 }
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001365 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001366 if (DependentTemplateId) {
John McCall31f17ec2010-04-27 00:57:59 +00001367 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00001368
John McCall31f17ec2010-04-27 00:57:59 +00001369 // Are there cases in (e.g.) friends where this won't match?
1370 if (const InjectedClassNameType *Injected
1371 = TemplateId->getAs<InjectedClassNameType>()) {
1372 CXXRecordDecl *Record = Injected->getDecl();
1373 if (ClassTemplatePartialSpecializationDecl *Partial =
1374 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1375 ExpectedTemplateParams = Partial->getTemplateParameters();
1376 else
1377 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1378 ->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001379 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001380
John McCall31f17ec2010-04-27 00:57:59 +00001381 if (ExpectedTemplateParams)
1382 TemplateParameterListsAreEqual(ParamLists[Idx],
1383 ExpectedTemplateParams,
1384 true, TPL_TemplateMatch);
1385
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001386 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregorb88e8882009-07-30 17:40:51 +00001387 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001388 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001389 diag::err_template_param_list_matches_nontemplate)
1390 << TemplateId
1391 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001392 else
1393 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001394 }
Mike Stump1eb44332009-09-09 15:08:12 +00001395
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001396 // If there were at least as many template-ids as there were template
1397 // parameter lists, then there are no template parameter lists remaining for
1398 // the declaration itself.
1399 if (Idx >= NumParamLists)
1400 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001401
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001402 // If there were too many template parameter lists, complain about that now.
1403 if (Idx != NumParamLists - 1) {
1404 while (Idx < NumParamLists - 1) {
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001405 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001406 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001407 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1408 : diag::err_template_spec_extra_headers)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001409 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1410 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001411
1412 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1413 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1414 diag::note_explicit_template_spec_does_not_need_header)
1415 << ExplicitSpecializationsInSpecifier.back();
1416 ExplicitSpecializationsInSpecifier.pop_back();
1417 }
1418
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001419 ++Idx;
1420 }
1421 }
Mike Stump1eb44332009-09-09 15:08:12 +00001422
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001423 // Return the last template parameter list, which corresponds to the
1424 // entity being declared.
1425 return ParamLists[NumParamLists - 1];
1426}
1427
Douglas Gregor7532dc62009-03-30 22:58:21 +00001428QualType Sema::CheckTemplateIdType(TemplateName Name,
1429 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001430 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001431 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001432 if (!Template) {
1433 // The template name does not resolve to a template, so we just
1434 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001435 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001436 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001437
Douglas Gregor40808ce2009-03-09 23:48:35 +00001438 // Check that the template argument list is well-formed for this
1439 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001440 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCalld5532b62009-11-23 01:53:49 +00001441 TemplateArgs.size());
1442 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001443 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001444 return QualType();
1445
Mike Stump1eb44332009-09-09 15:08:12 +00001446 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001447 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001448 "Converted template argument list is too short!");
1449
1450 QualType CanonType;
1451
Douglas Gregorcaddba02009-11-12 18:38:13 +00001452 if (Name.isDependent() ||
1453 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001454 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001455 // This class template specialization is a dependent
1456 // type. Therefore, its canonical type is another class template
1457 // specialization type that contains all of the converted
1458 // arguments in canonical form. This ensures that, e.g., A<T> and
1459 // A<T, T> have identical types when A is declared as:
1460 //
1461 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001462 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001463 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001464 Converted.getFlatArguments(),
1465 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Douglas Gregor1275ae02009-07-28 23:00:59 +00001467 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001468 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001469 // In the future, we need to teach getTemplateSpecializationType to only
1470 // build the canonical type and return that to us.
1471 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001472
1473 // This might work out to be a current instantiation, in which
1474 // case the canonical type needs to be the InjectedClassNameType.
1475 //
1476 // TODO: in theory this could be a simple hashtable lookup; most
1477 // changes to CurContext don't change the set of current
1478 // instantiations.
1479 if (isa<ClassTemplateDecl>(Template)) {
1480 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1481 // If we get out to a namespace, we're done.
1482 if (Ctx->isFileContext()) break;
1483
1484 // If this isn't a record, keep looking.
1485 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1486 if (!Record) continue;
1487
1488 // Look for one of the two cases with InjectedClassNameTypes
1489 // and check whether it's the same template.
1490 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1491 !Record->getDescribedClassTemplate())
1492 continue;
1493
1494 // Fetch the injected class name type and check whether its
1495 // injected type is equal to the type we just built.
1496 QualType ICNT = Context.getTypeDeclType(Record);
1497 QualType Injected = cast<InjectedClassNameType>(ICNT)
1498 ->getInjectedSpecializationType();
1499
1500 if (CanonType != Injected->getCanonicalTypeInternal())
1501 continue;
1502
1503 // If so, the canonical type of this TST is the injected
1504 // class name type of the record we just found.
1505 assert(ICNT.isCanonical());
1506 CanonType = ICNT;
John McCall31f17ec2010-04-27 00:57:59 +00001507 break;
1508 }
1509 }
Mike Stump1eb44332009-09-09 15:08:12 +00001510 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001511 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001512 // Find the class template specialization declaration that
1513 // corresponds to these arguments.
1514 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001515 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001516 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001517 Converted.flatSize(),
1518 Context);
Douglas Gregor40808ce2009-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 Stump1eb44332009-09-09 15:08:12 +00001526 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00001527 ClassTemplate->getTemplatedDecl()->getTagKind(),
1528 ClassTemplate->getDeclContext(),
1529 ClassTemplate->getLocation(),
1530 ClassTemplate,
1531 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001532 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1533 Decl->setLexicalDeclContext(CurContext);
1534 }
1535
1536 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001537 assert(isa<RecordType>(CanonType) &&
1538 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001539 }
Mike Stump1eb44332009-09-09 15:08:12 +00001540
Douglas Gregor40808ce2009-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 McCall71d74bc2010-06-13 09:25:03 +00001544 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001545}
1546
Douglas Gregorcc636682009-02-17 23:15:12 +00001547Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001548Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001549 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001550 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001551 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001552 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001553
Douglas Gregor40808ce2009-03-09 23:48:35 +00001554 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001555 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001556 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001557
John McCalld5532b62009-11-23 01:53:49 +00001558 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001559 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001560
1561 if (Result.isNull())
1562 return true;
1563
John McCalla93c9342009-12-07 02:54:59 +00001564 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001565 TemplateSpecializationTypeLoc TL
1566 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1567 TL.setTemplateNameLoc(TemplateLoc);
1568 TL.setLAngleLoc(LAngleLoc);
1569 TL.setRAngleLoc(RAngleLoc);
1570 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1571 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1572
1573 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCall6b2becf2009-09-08 17:47:29 +00001574}
John McCallf1bbbb42009-09-04 01:14:41 +00001575
John McCall6b2becf2009-09-08 17:47:29 +00001576Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1577 TagUseKind TUK,
1578 DeclSpec::TST TagSpec,
1579 SourceLocation TagLoc) {
1580 if (TypeResult.isInvalid())
1581 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001582
John McCall833ca992009-10-29 08:12:44 +00001583 // FIXME: preserve source info, ideally without copying the DI.
John McCalla93c9342009-12-07 02:54:59 +00001584 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001585 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001586
John McCall6b2becf2009-09-08 17:47:29 +00001587 // Verify the tag specifier.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001588 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001589
John McCall6b2becf2009-09-08 17:47:29 +00001590 if (const RecordType *RT = Type->getAs<RecordType>()) {
1591 RecordDecl *D = RT->getDecl();
1592
1593 IdentifierInfo *Id = D->getIdentifier();
1594 assert(Id && "templated class must have an identifier");
1595
1596 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1597 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001598 << Type
Douglas Gregor849b2432010-03-31 17:46:05 +00001599 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001600 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001601 }
1602 }
1603
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001604 ElaboratedTypeKeyword Keyword
1605 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1606 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCall6b2becf2009-09-08 17:47:29 +00001607
1608 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001609}
1610
John McCallf7a1a742009-11-24 19:00:30 +00001611Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1612 LookupResult &R,
1613 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001614 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001615 // FIXME: Can we do any checking at this point? I guess we could check the
1616 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001617 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001618 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001619
1620 // These should be filtered out by our callers.
1621 assert(!R.empty() && "empty lookup results when building templateid");
1622 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1623
1624 NestedNameSpecifier *Qualifier = 0;
1625 SourceRange QualifierRange;
1626 if (SS.isSet()) {
1627 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1628 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001629 }
John McCallc373d482010-01-27 01:50:18 +00001630
1631 // We don't want lookup warnings at this point.
1632 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001633
John McCallf7a1a742009-11-24 19:00:30 +00001634 bool Dependent
1635 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1636 &TemplateArgs);
1637 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001638 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001639 Qualifier, QualifierRange,
1640 R.getLookupName(), R.getNameLoc(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00001641 RequiresADL, TemplateArgs,
1642 R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001643
1644 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001645}
1646
John McCallf7a1a742009-11-24 19:00:30 +00001647// We actually only call this from template instantiation.
1648Sema::OwningExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001649Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001650 DeclarationName Name,
1651 SourceLocation NameLoc,
1652 const TemplateArgumentListInfo &TemplateArgs) {
1653 DeclContext *DC;
1654 if (!(DC = computeDeclContext(SS, false)) ||
1655 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00001656 RequireCompleteDeclContext(SS, DC))
John McCallf7a1a742009-11-24 19:00:30 +00001657 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001659 bool MemberOfUnknownSpecialization;
John McCallf7a1a742009-11-24 19:00:30 +00001660 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001661 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1662 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00001663
John McCallf7a1a742009-11-24 19:00:30 +00001664 if (R.isAmbiguous())
1665 return ExprError();
1666
1667 if (R.empty()) {
1668 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1669 << Name << SS.getRange();
1670 return ExprError();
1671 }
1672
1673 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1674 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1675 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1676 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1677 return ExprError();
1678 }
1679
1680 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001681}
1682
Douglas Gregorc45c2322009-03-31 00:43:58 +00001683/// \brief Form a dependent template name.
1684///
1685/// This action forms a dependent template name given the template
1686/// name and its (presumably dependent) scope specifier. For
1687/// example, given "MetaFun::template apply", the scope specifier \p
1688/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1689/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001690TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1691 SourceLocation TemplateKWLoc,
1692 CXXScopeSpec &SS,
1693 UnqualifiedId &Name,
1694 TypeTy *ObjectType,
1695 bool EnteringContext,
1696 TemplateTy &Result) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00001697 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1698 !getLangOptions().CPlusPlus0x)
1699 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1700 << FixItHint::CreateRemoval(TemplateKWLoc);
1701
Douglas Gregor0707bc52010-01-19 16:01:07 +00001702 DeclContext *LookupCtx = 0;
1703 if (SS.isSet())
1704 LookupCtx = computeDeclContext(SS, EnteringContext);
1705 if (!LookupCtx && ObjectType)
1706 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1707 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001708 // C++0x [temp.names]p5:
1709 // If a name prefixed by the keyword template is not the name of
1710 // a template, the program is ill-formed. [Note: the keyword
1711 // template may not be applied to non-template members of class
1712 // templates. -end note ] [ Note: as is the case with the
1713 // typename prefix, the template prefix is allowed in cases
1714 // where it is not strictly necessary; i.e., when the
1715 // nested-name-specifier or the expression on the left of the ->
1716 // or . is not dependent on a template-parameter, or the use
1717 // does not appear in the scope of a template. -end note]
1718 //
1719 // Note: C++03 was more strict here, because it banned the use of
1720 // the "template" keyword prior to a template-name that was not a
1721 // dependent name. C++ DR468 relaxed this requirement (the
1722 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregor732281d2010-06-14 22:07:54 +00001723 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001724 bool MemberOfUnknownSpecialization;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001725 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001726 EnteringContext, Result,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001727 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001728 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1729 isa<CXXRecordDecl>(LookupCtx) &&
1730 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord6ab2322010-06-16 23:00:59 +00001731 // This is a dependent template. Handle it below.
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001732 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001733 Diag(Name.getSourceRange().getBegin(),
1734 diag::err_template_kw_refers_to_non_template)
1735 << GetNameFromUnqualifiedId(Name)
Douglas Gregor0278e122010-05-05 05:58:24 +00001736 << Name.getSourceRange()
1737 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001738 return TNK_Non_template;
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001739 } else {
1740 // We found something; return it.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001741 return TNK;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001742 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001743 }
1744
Mike Stump1eb44332009-09-09 15:08:12 +00001745 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001746 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001747
1748 switch (Name.getKind()) {
1749 case UnqualifiedId::IK_Identifier:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001750 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1751 Name.Identifier));
1752 return TNK_Dependent_template_name;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001753
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001754 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001755 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001756 Name.OperatorFunctionId.Operator));
Douglas Gregord6ab2322010-06-16 23:00:59 +00001757 return TNK_Dependent_template_name;
Sean Hunte6252d12009-11-28 08:58:14 +00001758
1759 case UnqualifiedId::IK_LiteralOperatorId:
1760 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1761
Douglas Gregor014e88d2009-11-03 23:16:33 +00001762 default:
1763 break;
1764 }
1765
1766 Diag(Name.getSourceRange().getBegin(),
1767 diag::err_template_kw_refers_to_non_template)
1768 << GetNameFromUnqualifiedId(Name)
Douglas Gregor0278e122010-05-05 05:58:24 +00001769 << Name.getSourceRange()
1770 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001771 return TNK_Non_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001772}
1773
Mike Stump1eb44332009-09-09 15:08:12 +00001774bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001775 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001776 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001777 const TemplateArgument &Arg = AL.getArgument();
1778
Anders Carlsson436b1562009-06-13 00:33:33 +00001779 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001780 switch(Arg.getKind()) {
1781 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00001782 // C++ [temp.arg.type]p1:
1783 // A template-argument for a template-parameter which is a
1784 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001785 break;
1786 case TemplateArgument::Template: {
1787 // We have a template type parameter but the template argument
1788 // is a template without any arguments.
1789 SourceRange SR = AL.getSourceRange();
1790 TemplateName Name = Arg.getAsTemplate();
1791 Diag(SR.getBegin(), diag::err_template_missing_args)
1792 << Name << SR;
1793 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1794 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00001795
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001796 return true;
1797 }
1798 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00001799 // We have a template type parameter but the template argument
1800 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001801 SourceRange SR = AL.getSourceRange();
1802 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001803 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001804
Anders Carlsson436b1562009-06-13 00:33:33 +00001805 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001806 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001807 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001808
John McCalla93c9342009-12-07 02:54:59 +00001809 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001810 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Anders Carlsson436b1562009-06-13 00:33:33 +00001812 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001813 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001814 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001815 return false;
1816}
1817
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001818/// \brief Substitute template arguments into the default template argument for
1819/// the given template type parameter.
1820///
1821/// \param SemaRef the semantic analysis object for which we are performing
1822/// the substitution.
1823///
1824/// \param Template the template that we are synthesizing template arguments
1825/// for.
1826///
1827/// \param TemplateLoc the location of the template name that started the
1828/// template-id we are checking.
1829///
1830/// \param RAngleLoc the location of the right angle bracket ('>') that
1831/// terminates the template-id.
1832///
1833/// \param Param the template template parameter whose default we are
1834/// substituting into.
1835///
1836/// \param Converted the list of template arguments provided for template
1837/// parameters that precede \p Param in the template parameter list.
1838///
1839/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001840static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001841SubstDefaultTemplateArgument(Sema &SemaRef,
1842 TemplateDecl *Template,
1843 SourceLocation TemplateLoc,
1844 SourceLocation RAngleLoc,
1845 TemplateTypeParmDecl *Param,
1846 TemplateArgumentListBuilder &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001847 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001848
1849 // If the argument type is dependent, instantiate it now based
1850 // on the previously-computed template arguments.
1851 if (ArgType->getType()->isDependentType()) {
1852 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1853 /*TakeArgs=*/false);
1854
1855 MultiLevelTemplateArgumentList AllTemplateArgs
1856 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1857
1858 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1859 Template, Converted.getFlatArguments(),
1860 Converted.flatSize(),
1861 SourceRange(TemplateLoc, RAngleLoc));
1862
1863 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1864 Param->getDefaultArgumentLoc(),
1865 Param->getDeclName());
1866 }
1867
1868 return ArgType;
1869}
1870
1871/// \brief Substitute template arguments into the default template argument for
1872/// the given non-type template parameter.
1873///
1874/// \param SemaRef the semantic analysis object for which we are performing
1875/// the substitution.
1876///
1877/// \param Template the template that we are synthesizing template arguments
1878/// for.
1879///
1880/// \param TemplateLoc the location of the template name that started the
1881/// template-id we are checking.
1882///
1883/// \param RAngleLoc the location of the right angle bracket ('>') that
1884/// terminates the template-id.
1885///
Douglas Gregor788cd062009-11-11 01:00:40 +00001886/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001887/// substituting into.
1888///
1889/// \param Converted the list of template arguments provided for template
1890/// parameters that precede \p Param in the template parameter list.
1891///
1892/// \returns the substituted template argument, or NULL if an error occurred.
1893static Sema::OwningExprResult
1894SubstDefaultTemplateArgument(Sema &SemaRef,
1895 TemplateDecl *Template,
1896 SourceLocation TemplateLoc,
1897 SourceLocation RAngleLoc,
1898 NonTypeTemplateParmDecl *Param,
1899 TemplateArgumentListBuilder &Converted) {
1900 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1901 /*TakeArgs=*/false);
1902
1903 MultiLevelTemplateArgumentList AllTemplateArgs
1904 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1905
1906 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1907 Template, Converted.getFlatArguments(),
1908 Converted.flatSize(),
1909 SourceRange(TemplateLoc, RAngleLoc));
1910
1911 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1912}
1913
Douglas Gregor788cd062009-11-11 01:00:40 +00001914/// \brief Substitute template arguments into the default template argument for
1915/// the given template template parameter.
1916///
1917/// \param SemaRef the semantic analysis object for which we are performing
1918/// the substitution.
1919///
1920/// \param Template the template that we are synthesizing template arguments
1921/// for.
1922///
1923/// \param TemplateLoc the location of the template name that started the
1924/// template-id we are checking.
1925///
1926/// \param RAngleLoc the location of the right angle bracket ('>') that
1927/// terminates the template-id.
1928///
1929/// \param Param the template template parameter whose default we are
1930/// substituting into.
1931///
1932/// \param Converted the list of template arguments provided for template
1933/// parameters that precede \p Param in the template parameter list.
1934///
1935/// \returns the substituted template argument, or NULL if an error occurred.
1936static TemplateName
1937SubstDefaultTemplateArgument(Sema &SemaRef,
1938 TemplateDecl *Template,
1939 SourceLocation TemplateLoc,
1940 SourceLocation RAngleLoc,
1941 TemplateTemplateParmDecl *Param,
1942 TemplateArgumentListBuilder &Converted) {
1943 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1944 /*TakeArgs=*/false);
1945
1946 MultiLevelTemplateArgumentList AllTemplateArgs
1947 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1948
1949 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1950 Template, Converted.getFlatArguments(),
1951 Converted.flatSize(),
1952 SourceRange(TemplateLoc, RAngleLoc));
1953
1954 return SemaRef.SubstTemplateName(
1955 Param->getDefaultArgument().getArgument().getAsTemplate(),
1956 Param->getDefaultArgument().getTemplateNameLoc(),
1957 AllTemplateArgs);
1958}
1959
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001960/// \brief If the given template parameter has a default template
1961/// argument, substitute into that default template argument and
1962/// return the corresponding template argument.
1963TemplateArgumentLoc
1964Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1965 SourceLocation TemplateLoc,
1966 SourceLocation RAngleLoc,
1967 Decl *Param,
1968 TemplateArgumentListBuilder &Converted) {
1969 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1970 if (!TypeParm->hasDefaultArgument())
1971 return TemplateArgumentLoc();
1972
John McCalla93c9342009-12-07 02:54:59 +00001973 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001974 TemplateLoc,
1975 RAngleLoc,
1976 TypeParm,
1977 Converted);
1978 if (DI)
1979 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1980
1981 return TemplateArgumentLoc();
1982 }
1983
1984 if (NonTypeTemplateParmDecl *NonTypeParm
1985 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1986 if (!NonTypeParm->hasDefaultArgument())
1987 return TemplateArgumentLoc();
1988
1989 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1990 TemplateLoc,
1991 RAngleLoc,
1992 NonTypeParm,
1993 Converted);
1994 if (Arg.isInvalid())
1995 return TemplateArgumentLoc();
1996
1997 Expr *ArgE = Arg.takeAs<Expr>();
1998 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1999 }
2000
2001 TemplateTemplateParmDecl *TempTempParm
2002 = cast<TemplateTemplateParmDecl>(Param);
2003 if (!TempTempParm->hasDefaultArgument())
2004 return TemplateArgumentLoc();
2005
2006 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2007 TemplateLoc,
2008 RAngleLoc,
2009 TempTempParm,
2010 Converted);
2011 if (TName.isNull())
2012 return TemplateArgumentLoc();
2013
2014 return TemplateArgumentLoc(TemplateArgument(TName),
2015 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2016 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2017}
2018
Douglas Gregore7526412009-11-11 19:31:23 +00002019/// \brief Check that the given template argument corresponds to the given
2020/// template parameter.
2021bool Sema::CheckTemplateArgument(NamedDecl *Param,
2022 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00002023 TemplateDecl *Template,
2024 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002025 SourceLocation RAngleLoc,
Douglas Gregor02024a92010-03-28 02:42:43 +00002026 TemplateArgumentListBuilder &Converted,
2027 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002028 // Check template type parameters.
2029 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002030 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00002031
Douglas Gregord9e15302009-11-11 19:41:09 +00002032 // Check non-type template parameters.
2033 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002034 // Do substitution on the type of the non-type template parameter
2035 // with the template arguments we've seen thus far.
2036 QualType NTTPType = NTTP->getType();
2037 if (NTTPType->isDependentType()) {
2038 // Do substitution on the type of the non-type template parameter.
2039 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2040 NTTP, Converted.getFlatArguments(),
2041 Converted.flatSize(),
2042 SourceRange(TemplateLoc, RAngleLoc));
2043
2044 TemplateArgumentList TemplateArgs(Context, Converted,
2045 /*TakeArgs=*/false);
2046 NTTPType = SubstType(NTTPType,
2047 MultiLevelTemplateArgumentList(TemplateArgs),
2048 NTTP->getLocation(),
2049 NTTP->getDeclName());
2050 // If that worked, check the non-type template parameter type
2051 // for validity.
2052 if (!NTTPType.isNull())
2053 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2054 NTTP->getLocation());
2055 if (NTTPType.isNull())
2056 return true;
2057 }
2058
2059 switch (Arg.getArgument().getKind()) {
2060 case TemplateArgument::Null:
2061 assert(false && "Should never see a NULL template argument here");
2062 return true;
2063
2064 case TemplateArgument::Expression: {
2065 Expr *E = Arg.getArgument().getAsExpr();
2066 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002067 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00002068 return true;
2069
2070 Converted.Append(Result);
2071 break;
2072 }
2073
2074 case TemplateArgument::Declaration:
2075 case TemplateArgument::Integral:
2076 // We've already checked this template argument, so just copy
2077 // it to the list of converted arguments.
2078 Converted.Append(Arg.getArgument());
2079 break;
2080
2081 case TemplateArgument::Template:
2082 // We were given a template template argument. It may not be ill-formed;
2083 // see below.
2084 if (DependentTemplateName *DTN
2085 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2086 // We have a template argument such as \c T::template X, which we
2087 // parsed as a template template argument. However, since we now
2088 // know that we need a non-type template argument, convert this
2089 // template name into an expression.
John McCallf7a1a742009-11-24 19:00:30 +00002090 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2091 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002092 Arg.getTemplateQualifierRange(),
John McCallf7a1a742009-11-24 19:00:30 +00002093 DTN->getIdentifier(),
2094 Arg.getTemplateNameLoc());
Douglas Gregore7526412009-11-11 19:31:23 +00002095
2096 TemplateArgument Result;
2097 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2098 return true;
2099
2100 Converted.Append(Result);
2101 break;
2102 }
2103
2104 // We have a template argument that actually does refer to a class
2105 // template, template alias, or template template parameter, and
2106 // therefore cannot be a non-type template argument.
2107 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2108 << Arg.getSourceRange();
2109
2110 Diag(Param->getLocation(), diag::note_template_param_here);
2111 return true;
2112
2113 case TemplateArgument::Type: {
2114 // We have a non-type template parameter but the template
2115 // argument is a type.
2116
2117 // C++ [temp.arg]p2:
2118 // In a template-argument, an ambiguity between a type-id and
2119 // an expression is resolved to a type-id, regardless of the
2120 // form of the corresponding template-parameter.
2121 //
2122 // We warn specifically about this case, since it can be rather
2123 // confusing for users.
2124 QualType T = Arg.getArgument().getAsType();
2125 SourceRange SR = Arg.getSourceRange();
2126 if (T->isFunctionType())
2127 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2128 else
2129 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2130 Diag(Param->getLocation(), diag::note_template_param_here);
2131 return true;
2132 }
2133
2134 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002135 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002136 break;
2137 }
2138
2139 return false;
2140 }
2141
2142
2143 // Check template template parameters.
2144 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2145
2146 // Substitute into the template parameter list of the template
2147 // template parameter, since previously-supplied template arguments
2148 // may appear within the template template parameter.
2149 {
2150 // Set up a template instantiation context.
2151 LocalInstantiationScope Scope(*this);
2152 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2153 TempParm, Converted.getFlatArguments(),
2154 Converted.flatSize(),
2155 SourceRange(TemplateLoc, RAngleLoc));
2156
2157 TemplateArgumentList TemplateArgs(Context, Converted,
2158 /*TakeArgs=*/false);
2159 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2160 SubstDecl(TempParm, CurContext,
2161 MultiLevelTemplateArgumentList(TemplateArgs)));
2162 if (!TempParm)
2163 return true;
2164
2165 // FIXME: TempParam is leaked.
2166 }
2167
2168 switch (Arg.getArgument().getKind()) {
2169 case TemplateArgument::Null:
2170 assert(false && "Should never see a NULL template argument here");
2171 return true;
2172
2173 case TemplateArgument::Template:
2174 if (CheckTemplateArgument(TempParm, Arg))
2175 return true;
2176
2177 Converted.Append(Arg.getArgument());
2178 break;
2179
2180 case TemplateArgument::Expression:
2181 case TemplateArgument::Type:
2182 // We have a template template parameter but the template
2183 // argument does not refer to a template.
2184 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2185 return true;
2186
2187 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002188 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002189 "Declaration argument with template template parameter");
2190 break;
2191 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002192 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002193 "Integral argument with template template parameter");
2194 break;
2195
2196 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002197 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002198 break;
2199 }
2200
2201 return false;
2202}
2203
Douglas Gregorc15cb382009-02-09 23:23:08 +00002204/// \brief Check that the given template argument list is well-formed
2205/// for specializing the given template.
2206bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2207 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002208 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002209 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002210 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002211 TemplateParameterList *Params = Template->getTemplateParameters();
2212 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002213 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002214 bool Invalid = false;
2215
John McCalld5532b62009-11-23 01:53:49 +00002216 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2217
Mike Stump1eb44332009-09-09 15:08:12 +00002218 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002219 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002221 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002222 (NumArgs < Params->getMinRequiredArguments() &&
2223 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002224 // FIXME: point at either the first arg beyond what we can handle,
2225 // or the '>', depending on whether we have too many or too few
2226 // arguments.
2227 SourceRange Range;
2228 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002229 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002230 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2231 << (NumArgs > NumParams)
2232 << (isa<ClassTemplateDecl>(Template)? 0 :
2233 isa<FunctionTemplateDecl>(Template)? 1 :
2234 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2235 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002236 Diag(Template->getLocation(), diag::note_template_decl_here)
2237 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002238 Invalid = true;
2239 }
Mike Stump1eb44332009-09-09 15:08:12 +00002240
2241 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002242 // [...] The type and form of each template-argument specified in
2243 // a template-id shall match the type and form specified for the
2244 // corresponding parameter declared by the template in its
2245 // template-parameter-list.
2246 unsigned ArgIdx = 0;
2247 for (TemplateParameterList::iterator Param = Params->begin(),
2248 ParamEnd = Params->end();
2249 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002250 if (ArgIdx > NumArgs && PartialTemplateArgs)
2251 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002252
Douglas Gregord9e15302009-11-11 19:41:09 +00002253 // If we have a template parameter pack, check every remaining template
2254 // argument against that template parameter pack.
2255 if ((*Param)->isTemplateParameterPack()) {
2256 Converted.BeginPack();
2257 for (; ArgIdx < NumArgs; ++ArgIdx) {
2258 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2259 TemplateLoc, RAngleLoc, Converted)) {
2260 Invalid = true;
2261 break;
2262 }
2263 }
2264 Converted.EndPack();
2265 continue;
2266 }
2267
Douglas Gregorf35f8282009-11-11 21:54:23 +00002268 if (ArgIdx < NumArgs) {
2269 // Check the template argument we were given.
2270 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2271 TemplateLoc, RAngleLoc, Converted))
2272 return true;
2273
2274 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002275 }
Douglas Gregore7526412009-11-11 19:31:23 +00002276
Douglas Gregorf35f8282009-11-11 21:54:23 +00002277 // We have a default template argument that we will use.
2278 TemplateArgumentLoc Arg;
2279
2280 // Retrieve the default template argument from the template
2281 // parameter. For each kind of template parameter, we substitute the
2282 // template arguments provided thus far and any "outer" template arguments
2283 // (when the template parameter was part of a nested template) into
2284 // the default argument.
2285 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2286 if (!TTP->hasDefaultArgument()) {
2287 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2288 break;
2289 }
2290
John McCalla93c9342009-12-07 02:54:59 +00002291 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002292 Template,
2293 TemplateLoc,
2294 RAngleLoc,
2295 TTP,
2296 Converted);
2297 if (!ArgType)
2298 return true;
2299
2300 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2301 ArgType);
2302 } else if (NonTypeTemplateParmDecl *NTTP
2303 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2304 if (!NTTP->hasDefaultArgument()) {
2305 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2306 break;
2307 }
2308
2309 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2310 TemplateLoc,
2311 RAngleLoc,
2312 NTTP,
2313 Converted);
2314 if (E.isInvalid())
2315 return true;
2316
2317 Expr *Ex = E.takeAs<Expr>();
2318 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2319 } else {
2320 TemplateTemplateParmDecl *TempParm
2321 = cast<TemplateTemplateParmDecl>(*Param);
2322
2323 if (!TempParm->hasDefaultArgument()) {
2324 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2325 break;
2326 }
2327
2328 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2329 TemplateLoc,
2330 RAngleLoc,
2331 TempParm,
2332 Converted);
2333 if (Name.isNull())
2334 return true;
2335
2336 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2337 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2338 TempParm->getDefaultArgument().getTemplateNameLoc());
2339 }
2340
2341 // Introduce an instantiation record that describes where we are using
2342 // the default template argument.
2343 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2344 Converted.getFlatArguments(),
2345 Converted.flatSize(),
2346 SourceRange(TemplateLoc, RAngleLoc));
2347
2348 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002349 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002350 RAngleLoc, Converted))
2351 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002352 }
2353
2354 return Invalid;
2355}
2356
2357/// \brief Check a template argument against its corresponding
2358/// template type parameter.
2359///
2360/// This routine implements the semantics of C++ [temp.arg.type]. It
2361/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002362bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002363 TypeSourceInfo *ArgInfo) {
2364 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002365 QualType Arg = ArgInfo->getType();
2366
Douglas Gregorc15cb382009-02-09 23:23:08 +00002367 // C++ [temp.arg.type]p2:
2368 // A local type, a type with no linkage, an unnamed type or a type
2369 // compounded from any of these types shall not be used as a
2370 // template-argument for a template type-parameter.
2371 //
Douglas Gregor0fddb972010-05-22 16:17:30 +00002372 // FIXME: Perform the unnamed type check.
2373 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002374 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00002375 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002376 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00002377 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002378 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00002379 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002380 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall833ca992009-10-29 08:12:44 +00002381 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2382 << QualType(Tag, 0) << SR;
2383 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00002384 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall833ca992009-10-29 08:12:44 +00002385 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002386 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2387 return true;
Douglas Gregor0fddb972010-05-22 16:17:30 +00002388 } else if (Arg->isVariablyModifiedType()) {
2389 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2390 << Arg;
2391 return true;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002392 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00002393 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002394 }
2395
2396 return false;
2397}
2398
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002399/// \brief Checks whether the given template argument is the address
2400/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002401static bool
2402CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2403 NonTypeTemplateParmDecl *Param,
2404 QualType ParamType,
2405 Expr *ArgIn,
2406 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002407 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002408 Expr *Arg = ArgIn;
2409 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002410
2411 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002412 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002413 Arg = Cast->getSubExpr();
2414
2415 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002416 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002417 // A template-argument for a non-type, non-template
2418 // template-parameter shall be one of: [...]
2419 //
2420 // -- the address of an object or function with external
2421 // linkage, including function templates and function
2422 // template-ids but excluding non-static class members,
2423 // expressed as & id-expression where the & is optional if
2424 // the name refers to a function or array, or if the
2425 // corresponding template-parameter is a reference; or
2426 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002427
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002428 // Ignore (and complain about) any excess parentheses.
2429 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2430 if (!Invalid) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002431 S.Diag(Arg->getSourceRange().getBegin(),
2432 diag::err_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002433 << Arg->getSourceRange();
2434 Invalid = true;
2435 }
2436
2437 Arg = Parens->getSubExpr();
2438 }
2439
Douglas Gregorb7a09262010-04-01 18:32:35 +00002440 bool AddressTaken = false;
2441 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002442 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002443 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002444 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb7a09262010-04-01 18:32:35 +00002445 AddressTaken = true;
2446 AddrOpLoc = UnOp->getOperatorLoc();
2447 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002448 } else
2449 DRE = dyn_cast<DeclRefExpr>(Arg);
2450
Douglas Gregorb7a09262010-04-01 18:32:35 +00002451 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002452 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2453 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002454 S.Diag(Param->getLocation(), diag::note_template_param_here);
2455 return true;
2456 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002457
2458 // Stop checking the precise nature of the argument if it is value dependent,
2459 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002460 if (Arg->isValueDependent()) {
2461 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth038cc392010-01-31 10:01:20 +00002462 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002463 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002464
Douglas Gregorb7a09262010-04-01 18:32:35 +00002465 if (!isa<ValueDecl>(DRE->getDecl())) {
2466 S.Diag(Arg->getSourceRange().getBegin(),
2467 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002468 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002469 S.Diag(Param->getLocation(), diag::note_template_param_here);
2470 return true;
2471 }
2472
2473 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002474
2475 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00002476 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2477 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002478 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002479 S.Diag(Param->getLocation(), diag::note_template_param_here);
2480 return true;
2481 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002482
2483 // Cannot refer to non-static member functions
2484 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00002485 if (!Method->isStatic()) {
2486 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002487 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002488 S.Diag(Param->getLocation(), diag::note_template_param_here);
2489 return true;
2490 }
Mike Stump1eb44332009-09-09 15:08:12 +00002491
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002492 // Functions must have external linkage.
2493 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002494 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002495 S.Diag(Arg->getSourceRange().getBegin(),
2496 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002497 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002498 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002499 << true;
2500 return true;
2501 }
2502
2503 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002504 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002505
Douglas Gregorb7a09262010-04-01 18:32:35 +00002506 // If the template parameter has pointer type, the function decays.
2507 if (ParamType->isPointerType() && !AddressTaken)
2508 ArgType = S.Context.getPointerType(Func->getType());
2509 else if (AddressTaken && ParamType->isReferenceType()) {
2510 // If we originally had an address-of operator, but the
2511 // parameter has reference type, complain and (if things look
2512 // like they will work) drop the address-of operator.
2513 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2514 ParamType.getNonReferenceType())) {
2515 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2516 << ParamType;
2517 S.Diag(Param->getLocation(), diag::note_template_param_here);
2518 return true;
2519 }
2520
2521 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2522 << ParamType
2523 << FixItHint::CreateRemoval(AddrOpLoc);
2524 S.Diag(Param->getLocation(), diag::note_template_param_here);
2525
2526 ArgType = Func->getType();
2527 }
2528 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002529 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002530 S.Diag(Arg->getSourceRange().getBegin(),
2531 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002532 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002533 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002534 << true;
2535 return true;
2536 }
2537
Douglas Gregorb7a09262010-04-01 18:32:35 +00002538 // A value of reference type is not an object.
2539 if (Var->getType()->isReferenceType()) {
2540 S.Diag(Arg->getSourceRange().getBegin(),
2541 diag::err_template_arg_reference_var)
2542 << Var->getType() << Arg->getSourceRange();
2543 S.Diag(Param->getLocation(), diag::note_template_param_here);
2544 return true;
2545 }
2546
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002547 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002548 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002549
2550 // If the template parameter has pointer type, we must have taken
2551 // the address of this object.
2552 if (ParamType->isReferenceType()) {
2553 if (AddressTaken) {
2554 // If we originally had an address-of operator, but the
2555 // parameter has reference type, complain and (if things look
2556 // like they will work) drop the address-of operator.
2557 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2558 ParamType.getNonReferenceType())) {
2559 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2560 << ParamType;
2561 S.Diag(Param->getLocation(), diag::note_template_param_here);
2562 return true;
2563 }
2564
2565 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2566 << ParamType
2567 << FixItHint::CreateRemoval(AddrOpLoc);
2568 S.Diag(Param->getLocation(), diag::note_template_param_here);
2569
2570 ArgType = Var->getType();
2571 }
2572 } else if (!AddressTaken && ParamType->isPointerType()) {
2573 if (Var->getType()->isArrayType()) {
2574 // Array-to-pointer decay.
2575 ArgType = S.Context.getArrayDecayedType(Var->getType());
2576 } else {
2577 // If the template parameter has pointer type but the address of
2578 // this object was not taken, complain and (possibly) recover by
2579 // taking the address of the entity.
2580 ArgType = S.Context.getPointerType(Var->getType());
2581 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2582 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2583 << ParamType;
2584 S.Diag(Param->getLocation(), diag::note_template_param_here);
2585 return true;
2586 }
2587
2588 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2589 << ParamType
2590 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2591
2592 S.Diag(Param->getLocation(), diag::note_template_param_here);
2593 }
2594 }
2595 } else {
2596 // We found something else, but we don't know specifically what it is.
2597 S.Diag(Arg->getSourceRange().getBegin(),
2598 diag::err_template_arg_not_object_or_func)
2599 << Arg->getSourceRange();
2600 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2601 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002602 }
Mike Stump1eb44332009-09-09 15:08:12 +00002603
Douglas Gregorb7a09262010-04-01 18:32:35 +00002604 if (ParamType->isPointerType() &&
2605 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2606 S.IsQualificationConversion(ArgType, ParamType)) {
2607 // For pointer-to-object types, qualification conversions are
2608 // permitted.
2609 } else {
2610 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2611 if (!ParamRef->getPointeeType()->isFunctionType()) {
2612 // C++ [temp.arg.nontype]p5b3:
2613 // For a non-type template-parameter of type reference to
2614 // object, no conversions apply. The type referred to by the
2615 // reference may be more cv-qualified than the (otherwise
2616 // identical) type of the template- argument. The
2617 // template-parameter is bound directly to the
2618 // template-argument, which shall be an lvalue.
2619
2620 // FIXME: Other qualifiers?
2621 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2622 unsigned ArgQuals = ArgType.getCVRQualifiers();
2623
2624 if ((ParamQuals | ArgQuals) != ParamQuals) {
2625 S.Diag(Arg->getSourceRange().getBegin(),
2626 diag::err_template_arg_ref_bind_ignores_quals)
2627 << ParamType << Arg->getType()
2628 << Arg->getSourceRange();
2629 S.Diag(Param->getLocation(), diag::note_template_param_here);
2630 return true;
2631 }
2632 }
2633 }
2634
2635 // At this point, the template argument refers to an object or
2636 // function with external linkage. We now need to check whether the
2637 // argument and parameter types are compatible.
2638 if (!S.Context.hasSameUnqualifiedType(ArgType,
2639 ParamType.getNonReferenceType())) {
2640 // We can't perform this conversion or binding.
2641 if (ParamType->isReferenceType())
2642 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2643 << ParamType << Arg->getType() << Arg->getSourceRange();
2644 else
2645 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2646 << Arg->getType() << ParamType << Arg->getSourceRange();
2647 S.Diag(Param->getLocation(), diag::note_template_param_here);
2648 return true;
2649 }
2650 }
2651
2652 // Create the template argument.
2653 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor77c13e02010-04-24 18:20:53 +00002654 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00002655 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002656}
2657
2658/// \brief Checks whether the given template argument is a pointer to
2659/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002660bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2661 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002662 bool Invalid = false;
2663
2664 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002665 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002666 Arg = Cast->getSubExpr();
2667
2668 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002669 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002670 // A template-argument for a non-type, non-template
2671 // template-parameter shall be one of: [...]
2672 //
2673 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002674 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002675
2676 // Ignore (and complain about) any excess parentheses.
2677 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2678 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002679 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002680 diag::err_template_arg_extra_parens)
2681 << Arg->getSourceRange();
2682 Invalid = true;
2683 }
2684
2685 Arg = Parens->getSubExpr();
2686 }
2687
Douglas Gregorcaddba02009-11-12 18:38:13 +00002688 // A pointer-to-member constant written &Class::member.
2689 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002690 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2691 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2692 if (DRE && !DRE->getQualifier())
2693 DRE = 0;
2694 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002695 }
2696 // A constant of pointer-to-member type.
2697 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2698 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2699 if (VD->getType()->isMemberPointerType()) {
2700 if (isa<NonTypeTemplateParmDecl>(VD) ||
2701 (isa<VarDecl>(VD) &&
2702 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2703 if (Arg->isTypeDependent() || Arg->isValueDependent())
2704 Converted = TemplateArgument(Arg->Retain());
2705 else
2706 Converted = TemplateArgument(VD->getCanonicalDecl());
2707 return Invalid;
2708 }
2709 }
2710 }
2711
2712 DRE = 0;
2713 }
2714
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002715 if (!DRE)
2716 return Diag(Arg->getSourceRange().getBegin(),
2717 diag::err_template_arg_not_pointer_to_member_form)
2718 << Arg->getSourceRange();
2719
2720 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2721 assert((isa<FieldDecl>(DRE->getDecl()) ||
2722 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2723 "Only non-static member pointers can make it here");
2724
2725 // Okay: this is the address of a non-static member, and therefore
2726 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002727 if (Arg->isTypeDependent() || Arg->isValueDependent())
2728 Converted = TemplateArgument(Arg->Retain());
2729 else
2730 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002731 return Invalid;
2732 }
2733
2734 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002735 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002736 diag::err_template_arg_not_pointer_to_member_form)
2737 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002738 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002739 diag::note_template_arg_refers_here);
2740 return true;
2741}
2742
Douglas Gregorc15cb382009-02-09 23:23:08 +00002743/// \brief Check a template argument against its corresponding
2744/// non-type template parameter.
2745///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002746/// This routine implements the semantics of C++ [temp.arg.nontype].
2747/// It returns true if an error occurred, and false otherwise. \p
2748/// InstantiatedParamType is the type of the non-type template
2749/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002750///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002751/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002752bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002753 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00002754 TemplateArgument &Converted,
2755 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002756 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2757
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002758 // If either the parameter has a dependent type or the argument is
2759 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00002760 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2761 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002762 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002763 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002764 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002765
2766 // C++ [temp.arg.nontype]p5:
2767 // The following conversions are performed on each expression used
2768 // as a non-type template-argument. If a non-type
2769 // template-argument cannot be converted to the type of the
2770 // corresponding template-parameter then the program is
2771 // ill-formed.
2772 //
2773 // -- for a non-type template-parameter of integral or
2774 // enumeration type, integral promotions (4.5) and integral
2775 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002776 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002777 QualType ArgType = Arg->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002778 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002779 // C++ [temp.arg.nontype]p1:
2780 // A template-argument for a non-type, non-template
2781 // template-parameter shall be one of:
2782 //
2783 // -- an integral constant-expression of integral or enumeration
2784 // type; or
2785 // -- the name of a non-type template-parameter; or
2786 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002787 llvm::APSInt Value;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002788 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002789 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002790 diag::err_template_arg_not_integral_or_enumeral)
2791 << ArgType << Arg->getSourceRange();
2792 Diag(Param->getLocation(), diag::note_template_param_here);
2793 return true;
2794 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002795 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002796 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2797 << ArgType << Arg->getSourceRange();
2798 return true;
2799 }
2800
Douglas Gregor02024a92010-03-28 02:42:43 +00002801 // From here on out, all we care about are the unqualified forms
2802 // of the parameter and argument types.
2803 ParamType = ParamType.getUnqualifiedType();
2804 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002805
2806 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002807 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002808 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00002809 } else if (CTAK == CTAK_Deduced) {
2810 // C++ [temp.deduct.type]p17:
2811 // If, in the declaration of a function template with a non-type
2812 // template-parameter, the non-type template- parameter is used
2813 // in an expression in the function parameter-list and, if the
2814 // corresponding template-argument is deduced, the
2815 // template-argument type shall match the type of the
2816 // template-parameter exactly, except that a template-argument
2817 // deduced from an array bound may be of any integral type.
2818 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2819 << ArgType << ParamType;
2820 Diag(Param->getLocation(), diag::note_template_param_here);
2821 return true;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002822 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2823 !ParamType->isEnumeralType()) {
2824 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002825 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002826 } else {
2827 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002828 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002829 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002830 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002831 Diag(Param->getLocation(), diag::note_template_param_here);
2832 return true;
2833 }
2834
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002835 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002836 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002837 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002838
2839 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002840 llvm::APSInt OldValue = Value;
2841
2842 // Coerce the template argument's value to the value it will have
2843 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002844 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002845 if (Value.getBitWidth() != AllowedBits)
2846 Value.extOrTrunc(AllowedBits);
2847 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002848
2849 // Complain if an unsigned parameter received a negative value.
2850 if (IntegerType->isUnsignedIntegerType()
2851 && (OldValue.isSigned() && OldValue.isNegative())) {
2852 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2853 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2854 << Arg->getSourceRange();
2855 Diag(Param->getLocation(), diag::note_template_param_here);
2856 }
2857
2858 // Complain if we overflowed the template parameter's type.
2859 unsigned RequiredBits;
2860 if (IntegerType->isUnsignedIntegerType())
2861 RequiredBits = OldValue.getActiveBits();
2862 else if (OldValue.isUnsigned())
2863 RequiredBits = OldValue.getActiveBits() + 1;
2864 else
2865 RequiredBits = OldValue.getMinSignedBits();
2866 if (RequiredBits > AllowedBits) {
2867 Diag(Arg->getSourceRange().getBegin(),
2868 diag::warn_template_arg_too_large)
2869 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2870 << Arg->getSourceRange();
2871 Diag(Param->getLocation(), diag::note_template_param_here);
2872 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002873 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002874
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002875 // Add the value of this argument to the list of converted
2876 // arguments. We use the bitwidth and signedness of the template
2877 // parameter.
2878 if (Arg->isValueDependent()) {
2879 // The argument is value-dependent. Create a new
2880 // TemplateArgument with the converted expression.
2881 Converted = TemplateArgument(Arg);
2882 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002883 }
2884
John McCall833ca992009-10-29 08:12:44 +00002885 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002886 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002887 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002888 return false;
2889 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002890
John McCall6bb80172010-03-30 21:47:33 +00002891 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2892
Douglas Gregorb7a09262010-04-01 18:32:35 +00002893 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2894 // from a template argument of type std::nullptr_t to a non-type
2895 // template parameter of type pointer to object, pointer to
2896 // function, or pointer-to-member, respectively.
2897 if (ArgType->isNullPtrType() &&
2898 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2899 Converted = TemplateArgument((NamedDecl *)0);
2900 return false;
2901 }
2902
Douglas Gregorb86b0572009-02-11 01:18:59 +00002903 // Handle pointer-to-function, reference-to-function, and
2904 // pointer-to-member-function all in (roughly) the same way.
2905 if (// -- For a non-type template-parameter of type pointer to
2906 // function, only the function-to-pointer conversion (4.3) is
2907 // applied. If the template-argument represents a set of
2908 // overloaded functions (or a pointer to such), the matching
2909 // function is selected from the set (13.4).
2910 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002911 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002912 // -- For a non-type template-parameter of type reference to
2913 // function, no conversions apply. If the template-argument
2914 // represents a set of overloaded functions, the matching
2915 // function is selected from the set (13.4).
2916 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002917 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002918 // -- For a non-type template-parameter of type pointer to
2919 // member function, no conversions apply. If the
2920 // template-argument represents a set of overloaded member
2921 // functions, the matching member function is selected from
2922 // the set (13.4).
2923 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002924 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002925 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002926
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002927 if (Arg->getType() == Context.OverloadTy) {
2928 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2929 true,
2930 FoundResult)) {
2931 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2932 return true;
2933
2934 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2935 ArgType = Arg->getType();
2936 } else
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002937 return true;
Douglas Gregora35284b2009-02-11 00:19:33 +00002938 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002939
Douglas Gregorb7a09262010-04-01 18:32:35 +00002940 if (!ParamType->isMemberPointerType())
2941 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2942 ParamType,
2943 Arg, Converted);
2944
2945 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
2946 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2947 Arg->isLvalue(Context) == Expr::LV_Valid);
2948 } else if (!Context.hasSameUnqualifiedType(ArgType,
2949 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002950 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002951 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002952 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002953 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002954 Diag(Param->getLocation(), diag::note_template_param_here);
2955 return true;
2956 }
Mike Stump1eb44332009-09-09 15:08:12 +00002957
Douglas Gregorb7a09262010-04-01 18:32:35 +00002958 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregora35284b2009-02-11 00:19:33 +00002959 }
2960
Chris Lattnerfe90de72009-02-20 21:37:53 +00002961 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002962 // -- for a non-type template-parameter of type pointer to
2963 // object, qualification conversions (4.4) and the
2964 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002965 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002966 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002967 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002968
Douglas Gregorb7a09262010-04-01 18:32:35 +00002969 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2970 ParamType,
2971 Arg, Converted);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002972 }
Mike Stump1eb44332009-09-09 15:08:12 +00002973
Ted Kremenek6217b802009-07-29 21:53:49 +00002974 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002975 // -- For a non-type template-parameter of type reference to
2976 // object, no conversions apply. The type referred to by the
2977 // reference may be more cv-qualified than the (otherwise
2978 // identical) type of the template-argument. The
2979 // template-parameter is bound directly to the
2980 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002981 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002982 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002983
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002984 if (Arg->getType() == Context.OverloadTy) {
2985 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2986 ParamRefType->getPointeeType(),
2987 true,
2988 FoundResult)) {
2989 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2990 return true;
2991
2992 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2993 ArgType = Arg->getType();
2994 } else
Douglas Gregorb7a09262010-04-01 18:32:35 +00002995 return true;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002996 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002997
Douglas Gregorb7a09262010-04-01 18:32:35 +00002998 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2999 ParamType,
3000 Arg, Converted);
Douglas Gregorb86b0572009-02-11 01:18:59 +00003001 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00003002
3003 // -- For a non-type template-parameter of type pointer to data
3004 // member, qualification conversions (4.4) are applied.
3005 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3006
Douglas Gregor8e6563b2009-02-11 18:22:40 +00003007 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00003008 // Types match exactly: nothing more to do here.
3009 } else if (IsQualificationConversion(ArgType, ParamType)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003010 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
3011 Arg->isLvalue(Context) == Expr::LV_Valid);
Douglas Gregor658bbb52009-02-11 16:16:59 +00003012 } else {
3013 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003014 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00003015 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003016 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00003017 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00003018 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00003019 }
3020
Douglas Gregorcaddba02009-11-12 18:38:13 +00003021 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00003022}
3023
3024/// \brief Check a template argument against its corresponding
3025/// template template parameter.
3026///
3027/// This routine implements the semantics of C++ [temp.arg.template].
3028/// It returns true if an error occurred, and false otherwise.
3029bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00003030 const TemplateArgumentLoc &Arg) {
3031 TemplateName Name = Arg.getArgument().getAsTemplate();
3032 TemplateDecl *Template = Name.getAsTemplateDecl();
3033 if (!Template) {
3034 // Any dependent template name is fine.
3035 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3036 return false;
3037 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003038
3039 // C++ [temp.arg.template]p1:
3040 // A template-argument for a template template-parameter shall be
3041 // the name of a class template, expressed as id-expression. Only
3042 // primary class templates are considered when matching the
3043 // template template argument with the corresponding parameter;
3044 // partial specializations are not considered even if their
3045 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003046 //
3047 // Note that we also allow template template parameters here, which
3048 // will happen when we are dealing with, e.g., class template
3049 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00003050 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003051 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003052 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00003053 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00003054 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00003055 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003056 << Template;
3057 }
3058
3059 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3060 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00003061 true,
3062 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00003063 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00003064}
3065
Douglas Gregor02024a92010-03-28 02:42:43 +00003066/// \brief Given a non-type template argument that refers to a
3067/// declaration and the type of its corresponding non-type template
3068/// parameter, produce an expression that properly refers to that
3069/// declaration.
3070Sema::OwningExprResult
3071Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3072 QualType ParamType,
3073 SourceLocation Loc) {
3074 assert(Arg.getKind() == TemplateArgument::Declaration &&
3075 "Only declaration template arguments permitted here");
3076 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3077
3078 if (VD->getDeclContext()->isRecord() &&
3079 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3080 // If the value is a class member, we might have a pointer-to-member.
3081 // Determine whether the non-type template template parameter is of
3082 // pointer-to-member type. If so, we need to build an appropriate
3083 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3084 // would refer to the member itself.
3085 if (ParamType->isMemberPointerType()) {
3086 QualType ClassType
3087 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3088 NestedNameSpecifier *Qualifier
3089 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
3090 CXXScopeSpec SS;
3091 SS.setScopeRep(Qualifier);
3092 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
3093 VD->getType().getNonReferenceType(),
3094 Loc,
3095 &SS);
3096 if (RefExpr.isInvalid())
3097 return ExprError();
3098
3099 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregorc0c83002010-04-30 21:46:38 +00003100
3101 // We might need to perform a trailing qualification conversion, since
3102 // the element type on the parameter could be more qualified than the
3103 // element type in the expression we constructed.
3104 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3105 ParamType.getUnqualifiedType())) {
3106 Expr *RefE = RefExpr.takeAs<Expr>();
3107 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(),
3108 CastExpr::CK_NoOp);
3109 RefExpr = Owned(RefE);
3110 }
3111
Douglas Gregor02024a92010-03-28 02:42:43 +00003112 assert(!RefExpr.isInvalid() &&
3113 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00003114 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00003115 return move(RefExpr);
3116 }
3117 }
3118
3119 QualType T = VD->getType().getNonReferenceType();
3120 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003121 // When the non-type template parameter is a pointer, take the
3122 // address of the declaration.
Douglas Gregor02024a92010-03-28 02:42:43 +00003123 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3124 if (RefExpr.isInvalid())
3125 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003126
3127 if (T->isFunctionType() || T->isArrayType()) {
3128 // Decay functions and arrays.
3129 Expr *RefE = (Expr *)RefExpr.get();
3130 DefaultFunctionArrayConversion(RefE);
3131 if (RefE != RefExpr.get()) {
3132 RefExpr.release();
3133 RefExpr = Owned(RefE);
3134 }
3135
3136 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00003137 }
3138
Douglas Gregorb7a09262010-04-01 18:32:35 +00003139 // Take the address of everything else
3140 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregor02024a92010-03-28 02:42:43 +00003141 }
3142
3143 // If the non-type template parameter has reference type, qualify the
3144 // resulting declaration reference with the extra qualifiers on the
3145 // type that the reference refers to.
3146 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3147 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3148
3149 return BuildDeclRefExpr(VD, T, Loc);
3150}
3151
3152/// \brief Construct a new expression that refers to the given
3153/// integral template argument with the given source-location
3154/// information.
3155///
3156/// This routine takes care of the mapping from an integral template
3157/// argument (which may have any integral type) to the appropriate
3158/// literal value.
3159Sema::OwningExprResult
3160Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3161 SourceLocation Loc) {
3162 assert(Arg.getKind() == TemplateArgument::Integral &&
3163 "Operation is only value for integral template arguments");
3164 QualType T = Arg.getIntegralType();
3165 if (T->isCharType() || T->isWideCharType())
3166 return Owned(new (Context) CharacterLiteral(
3167 Arg.getAsIntegral()->getZExtValue(),
3168 T->isWideCharType(),
3169 T,
3170 Loc));
3171 if (T->isBooleanType())
3172 return Owned(new (Context) CXXBoolLiteralExpr(
3173 Arg.getAsIntegral()->getBoolValue(),
3174 T,
3175 Loc));
3176
3177 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3178}
3179
3180
Douglas Gregorddc29e12009-02-06 22:42:48 +00003181/// \brief Determine whether the given template parameter lists are
3182/// equivalent.
3183///
Mike Stump1eb44332009-09-09 15:08:12 +00003184/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00003185/// source code as part of a new template declaration.
3186///
3187/// \param Old The old template parameter list, typically found via
3188/// name lookup of the template declared with this template parameter
3189/// list.
3190///
3191/// \param Complain If true, this routine will produce a diagnostic if
3192/// the template parameter lists are not equivalent.
3193///
Douglas Gregorfb898e12009-11-12 16:20:59 +00003194/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00003195///
3196/// \param TemplateArgLoc If this source location is valid, then we
3197/// are actually checking the template parameter list of a template
3198/// argument (New) against the template parameter list of its
3199/// corresponding template template parameter (Old). We produce
3200/// slightly different diagnostics in this scenario.
3201///
Douglas Gregorddc29e12009-02-06 22:42:48 +00003202/// \returns True if the template parameter lists are equal, false
3203/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003204bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00003205Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3206 TemplateParameterList *Old,
3207 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003208 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003209 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003210 if (Old->size() != New->size()) {
3211 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003212 unsigned NextDiag = diag::err_template_param_list_different_arity;
3213 if (TemplateArgLoc.isValid()) {
3214 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3215 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00003216 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003217 Diag(New->getTemplateLoc(), NextDiag)
3218 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00003219 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003220 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00003221 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003222 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003223 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3224 }
3225
3226 return false;
3227 }
3228
3229 for (TemplateParameterList::iterator OldParm = Old->begin(),
3230 OldParmEnd = Old->end(), NewParm = New->begin();
3231 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3232 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003233 if (Complain) {
3234 unsigned NextDiag = diag::err_template_param_different_kind;
3235 if (TemplateArgLoc.isValid()) {
3236 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3237 NextDiag = diag::note_template_param_different_kind;
3238 }
3239 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003240 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003241 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003242 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00003243 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003244 return false;
3245 }
3246
Douglas Gregora417b872010-06-04 08:34:32 +00003247 if (TemplateTypeParmDecl *OldTTP
3248 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3249 // Template type parameters are equivalent if either both are template
3250 // type parameter packs or neither are (since we know we're at the same
3251 // index).
3252 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3253 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3254 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3255 // allow one to match a template parameter pack in the template
3256 // parameter list of a template template parameter to one or more
3257 // template parameters in the template parameter list of the
3258 // corresponding template template argument.
3259 if (Complain) {
3260 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3261 if (TemplateArgLoc.isValid()) {
3262 Diag(TemplateArgLoc,
3263 diag::err_template_arg_template_params_mismatch);
3264 NextDiag = diag::note_template_parameter_pack_non_pack;
3265 }
3266 Diag(NewTTP->getLocation(), NextDiag)
3267 << 0 << NewTTP->isParameterPack();
3268 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3269 << 0 << OldTTP->isParameterPack();
3270 }
3271 return false;
3272 }
Mike Stump1eb44332009-09-09 15:08:12 +00003273 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003274 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3275 // The types of non-type template parameters must agree.
3276 NonTypeTemplateParmDecl *NewNTTP
3277 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00003278
3279 // If we are matching a template template argument to a template
3280 // template parameter and one of the non-type template parameter types
3281 // is dependent, then we must wait until template instantiation time
3282 // to actually compare the arguments.
3283 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3284 (OldNTTP->getType()->isDependentType() ||
3285 NewNTTP->getType()->isDependentType()))
3286 continue;
3287
Douglas Gregorddc29e12009-02-06 22:42:48 +00003288 if (Context.getCanonicalType(OldNTTP->getType()) !=
3289 Context.getCanonicalType(NewNTTP->getType())) {
3290 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003291 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3292 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003293 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003294 diag::err_template_arg_template_params_mismatch);
3295 NextDiag = diag::note_template_nontype_parm_different_type;
3296 }
3297 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003298 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00003299 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00003300 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00003301 diag::note_template_nontype_parm_prev_declaration)
3302 << OldNTTP->getType();
3303 }
3304 return false;
3305 }
3306 } else {
3307 // The template parameter lists of template template
3308 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00003309 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00003310 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00003311 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003312 = cast<TemplateTemplateParmDecl>(*OldParm);
3313 TemplateTemplateParmDecl *NewTTP
3314 = cast<TemplateTemplateParmDecl>(*NewParm);
3315 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3316 OldTTP->getTemplateParameters(),
3317 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003318 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00003319 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003320 return false;
3321 }
3322 }
3323
3324 return true;
3325}
3326
3327/// \brief Check whether a template can be declared within this scope.
3328///
3329/// If the template declaration is valid in this scope, returns
3330/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003331bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003332Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003333 // Find the nearest enclosing declaration scope.
3334 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3335 (S->getFlags() & Scope::TemplateParamScope) != 0)
3336 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003337
Douglas Gregorddc29e12009-02-06 22:42:48 +00003338 // C++ [temp]p2:
3339 // A template-declaration can appear only as a namespace scope or
3340 // class scope declaration.
3341 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003342 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3343 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003344 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003345 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003346
Eli Friedman1503f772009-07-31 01:43:05 +00003347 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003348 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003349
3350 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3351 return false;
3352
Mike Stump1eb44332009-09-09 15:08:12 +00003353 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003354 diag::err_template_outside_namespace_or_class_scope)
3355 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003356}
Douglas Gregorcc636682009-02-17 23:15:12 +00003357
Douglas Gregord5cb8762009-10-07 00:13:32 +00003358/// \brief Determine what kind of template specialization the given declaration
3359/// is.
3360static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3361 if (!D)
3362 return TSK_Undeclared;
3363
Douglas Gregorf6b11852009-10-08 15:14:33 +00003364 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3365 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003366 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3367 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003368 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3369 return Var->getTemplateSpecializationKind();
3370
Douglas Gregord5cb8762009-10-07 00:13:32 +00003371 return TSK_Undeclared;
3372}
3373
Douglas Gregor9302da62009-10-14 23:50:59 +00003374/// \brief Check whether a specialization is well-formed in the current
3375/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003376///
Douglas Gregor9302da62009-10-14 23:50:59 +00003377/// This routine determines whether a template specialization can be declared
3378/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003379///
3380/// \param S the semantic analysis object for which this check is being
3381/// performed.
3382///
3383/// \param Specialized the entity being specialized or instantiated, which
3384/// may be a kind of template (class template, function template, etc.) or
3385/// a member of a class template (member function, static data member,
3386/// member class).
3387///
3388/// \param PrevDecl the previous declaration of this entity, if any.
3389///
3390/// \param Loc the location of the explicit specialization or instantiation of
3391/// this entity.
3392///
3393/// \param IsPartialSpecialization whether this is a partial specialization of
3394/// a class template.
3395///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003396/// \returns true if there was an error that we cannot recover from, false
3397/// otherwise.
3398static bool CheckTemplateSpecializationScope(Sema &S,
3399 NamedDecl *Specialized,
3400 NamedDecl *PrevDecl,
3401 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003402 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003403 // Keep these "kind" numbers in sync with the %select statements in the
3404 // various diagnostics emitted by this routine.
3405 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003406 bool isTemplateSpecialization = false;
3407 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003408 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003409 isTemplateSpecialization = true;
3410 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003411 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003412 isTemplateSpecialization = true;
3413 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003414 EntityKind = 3;
3415 else if (isa<VarDecl>(Specialized))
3416 EntityKind = 4;
3417 else if (isa<RecordDecl>(Specialized))
3418 EntityKind = 5;
3419 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003420 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3421 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003422 return true;
3423 }
3424
Douglas Gregor88b70942009-02-25 22:02:03 +00003425 // C++ [temp.expl.spec]p2:
3426 // An explicit specialization shall be declared in the namespace
3427 // of which the template is a member, or, for member templates, in
3428 // the namespace of which the enclosing class or enclosing class
3429 // template is a member. An explicit specialization of a member
3430 // function, member class or static data member of a class
3431 // template shall be declared in the namespace of which the class
3432 // template is a member. Such a declaration may also be a
3433 // definition. If the declaration is not a definition, the
3434 // specialization may be defined later in the name- space in which
3435 // the explicit specialization was declared, or in a namespace
3436 // that encloses the one in which the explicit specialization was
3437 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003438 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3439 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003440 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003441 return true;
3442 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003443
Douglas Gregor0a407472009-10-07 17:30:37 +00003444 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3445 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003446 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003447 return true;
3448 }
3449
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003450 // C++ [temp.class.spec]p6:
3451 // A class template partial specialization may be declared or redeclared
3452 // in any namespace scope in which its definition may be defined (14.5.1
3453 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003454 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003455 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003456 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003457 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003458 if ((!PrevDecl ||
3459 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3460 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3461 // There is no prior declaration of this entity, so this
3462 // specialization must be in the same context as the template
3463 // itself.
3464 if (!DC->Equals(SpecializedContext)) {
3465 if (isa<TranslationUnitDecl>(SpecializedContext))
3466 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3467 << EntityKind << Specialized;
3468 else if (isa<NamespaceDecl>(SpecializedContext))
3469 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3470 << EntityKind << Specialized
3471 << cast<NamedDecl>(SpecializedContext);
3472
3473 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3474 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003475 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003476 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003477
3478 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003479 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003480 // Note that HandleDeclarator() performs this check for explicit
3481 // specializations of function templates, static data members, and member
3482 // functions, so we skip the check here for those kinds of entities.
3483 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003484 // Should we refactor that check, so that it occurs later?
3485 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003486 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3487 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003488 if (isa<TranslationUnitDecl>(SpecializedContext))
3489 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3490 << EntityKind << Specialized;
3491 else if (isa<NamespaceDecl>(SpecializedContext))
3492 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3493 << EntityKind << Specialized
3494 << cast<NamedDecl>(SpecializedContext);
3495
Douglas Gregor9302da62009-10-14 23:50:59 +00003496 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003497 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003498
3499 // FIXME: check for specialization-after-instantiation errors and such.
3500
Douglas Gregor88b70942009-02-25 22:02:03 +00003501 return false;
3502}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003503
Douglas Gregore94866f2009-06-12 21:21:02 +00003504/// \brief Check the non-type template arguments of a class template
3505/// partial specialization according to C++ [temp.class.spec]p9.
3506///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003507/// \param TemplateParams the template parameters of the primary class
3508/// template.
3509///
3510/// \param TemplateArg the template arguments of the class template
3511/// partial specialization.
3512///
3513/// \param MirrorsPrimaryTemplate will be set true if the class
3514/// template partial specialization arguments are identical to the
3515/// implicit template arguments of the primary template. This is not
3516/// necessarily an error (C++0x), and it is left to the caller to diagnose
3517/// this condition when it is an error.
3518///
Douglas Gregore94866f2009-06-12 21:21:02 +00003519/// \returns true if there was an error, false otherwise.
3520bool Sema::CheckClassTemplatePartialSpecializationArgs(
3521 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00003522 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003523 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003524 // FIXME: the interface to this function will have to change to
3525 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003526 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003527
Anders Carlssonfb250522009-06-23 01:26:57 +00003528 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00003529
Douglas Gregore94866f2009-06-12 21:21:02 +00003530 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003531 // Determine whether the template argument list of the partial
3532 // specialization is identical to the implicit argument list of
3533 // the primary template. The caller may need to diagnostic this as
3534 // an error per C++ [temp.class.spec]p9b3.
3535 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003536 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003537 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3538 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003539 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003540 MirrorsPrimaryTemplate = false;
3541 } else if (TemplateTemplateParmDecl *TTP
3542 = dyn_cast<TemplateTemplateParmDecl>(
3543 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003544 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003545 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003546 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003547 if (!ArgDecl ||
3548 ArgDecl->getIndex() != TTP->getIndex() ||
3549 ArgDecl->getDepth() != TTP->getDepth())
3550 MirrorsPrimaryTemplate = false;
3551 }
3552 }
3553
Mike Stump1eb44332009-09-09 15:08:12 +00003554 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003555 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003556 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003557 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003558 }
3559
Anders Carlsson6360be72009-06-13 18:20:51 +00003560 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003561 if (!ArgExpr) {
3562 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003563 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003564 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003565
3566 // C++ [temp.class.spec]p8:
3567 // A non-type argument is non-specialized if it is the name of a
3568 // non-type parameter. All other non-type arguments are
3569 // specialized.
3570 //
3571 // Below, we check the two conditions that only apply to
3572 // specialized non-type arguments, so skip any non-specialized
3573 // arguments.
3574 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003575 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003576 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003577 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003578 (Param->getIndex() != NTTP->getIndex() ||
3579 Param->getDepth() != NTTP->getDepth()))
3580 MirrorsPrimaryTemplate = false;
3581
Douglas Gregore94866f2009-06-12 21:21:02 +00003582 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003583 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003584
3585 // C++ [temp.class.spec]p9:
3586 // Within the argument list of a class template partial
3587 // specialization, the following restrictions apply:
3588 // -- A partially specialized non-type argument expression
3589 // shall not involve a template parameter of the partial
3590 // specialization except when the argument expression is a
3591 // simple identifier.
3592 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003593 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003594 diag::err_dependent_non_type_arg_in_partial_spec)
3595 << ArgExpr->getSourceRange();
3596 return true;
3597 }
3598
3599 // -- The type of a template parameter corresponding to a
3600 // specialized non-type argument shall not be dependent on a
3601 // parameter of the specialization.
3602 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003603 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003604 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3605 << Param->getType()
3606 << ArgExpr->getSourceRange();
3607 Diag(Param->getLocation(), diag::note_template_param_here);
3608 return true;
3609 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003610
3611 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003612 }
3613
3614 return false;
3615}
3616
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003617/// \brief Retrieve the previous declaration of the given declaration.
3618static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3619 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3620 return VD->getPreviousDeclaration();
3621 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3622 return FD->getPreviousDeclaration();
3623 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3624 return TD->getPreviousDeclaration();
3625 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3626 return TD->getPreviousDeclaration();
3627 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3628 return FTD->getPreviousDeclaration();
3629 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3630 return CTD->getPreviousDeclaration();
3631 return 0;
3632}
3633
Douglas Gregor212e81c2009-03-25 00:13:59 +00003634Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003635Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3636 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00003637 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003638 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003639 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00003640 SourceLocation TemplateNameLoc,
3641 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00003642 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00003643 SourceLocation RAngleLoc,
3644 AttributeList *Attr,
3645 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003646 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00003647
Douglas Gregorcc636682009-02-17 23:15:12 +00003648 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00003649 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003650 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00003651 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3652
3653 if (!ClassTemplate) {
3654 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3655 << (Name.getAsTemplateDecl() &&
3656 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3657 return true;
3658 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003659
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003660 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003661 bool isPartialSpecialization = false;
3662
Douglas Gregor88b70942009-02-25 22:02:03 +00003663 // Check the validity of the template headers that introduce this
3664 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003665 // FIXME: We probably shouldn't complain about these headers for
3666 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00003667 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00003668 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3669 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003670 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00003671 TUK == TUK_Friend,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003672 isExplicitSpecialization);
Abramo Bagnara9b934882010-06-12 08:15:14 +00003673 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3674 if (TemplateParams)
3675 --NumMatchedTemplateParamLists;
3676
Douglas Gregor05396e22009-08-25 17:23:04 +00003677 if (TemplateParams && TemplateParams->size() > 0) {
3678 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003679
Douglas Gregor05396e22009-08-25 17:23:04 +00003680 // C++ [temp.class.spec]p10:
3681 // The template parameter list of a specialization shall not
3682 // contain default template argument values.
3683 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3684 Decl *Param = TemplateParams->getParam(I);
3685 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3686 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003687 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003688 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00003689 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003690 }
3691 } else if (NonTypeTemplateParmDecl *NTTP
3692 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3693 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003694 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003695 diag::err_default_arg_in_partial_spec)
3696 << DefArg->getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00003697 NTTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003698 DefArg->Destroy(Context);
3699 }
3700 } else {
3701 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003702 if (TTP->hasDefaultArgument()) {
3703 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003704 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003705 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00003706 TTP->removeDefaultArgument();
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003707 }
3708 }
3709 }
Douglas Gregora735b202009-10-13 14:39:41 +00003710 } else if (TemplateParams) {
3711 if (TUK == TUK_Friend)
3712 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00003713 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00003714 SourceRange(TemplateParams->getTemplateLoc(),
3715 TemplateParams->getRAngleLoc()))
3716 << SourceRange(LAngleLoc, RAngleLoc);
3717 else
3718 isExplicitSpecialization = true;
3719 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003720 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00003721 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003722 isExplicitSpecialization = true;
3723 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003724
Douglas Gregorcc636682009-02-17 23:15:12 +00003725 // Check that the specialization uses the same tag kind as the
3726 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003727 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3728 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003729 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003730 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003731 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003732 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003733 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00003734 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003735 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003736 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003737 diag::note_previous_use);
3738 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3739 }
3740
Douglas Gregor40808ce2009-03-09 23:48:35 +00003741 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00003742 TemplateArgumentListInfo TemplateArgs;
3743 TemplateArgs.setLAngleLoc(LAngleLoc);
3744 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00003745 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003746
Douglas Gregorcc636682009-02-17 23:15:12 +00003747 // Check that the template argument list is well-formed for this
3748 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003749 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3750 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00003751 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3752 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003753 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003754
Mike Stump1eb44332009-09-09 15:08:12 +00003755 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003756 ClassTemplate->getTemplateParameters()->size()) &&
3757 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003758
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003759 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003760 // corresponds to these arguments.
3761 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003762 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003763 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003764 if (CheckClassTemplatePartialSpecializationArgs(
3765 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003766 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003767 return true;
3768
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003769 if (MirrorsPrimaryTemplate) {
3770 // C++ [temp.class.spec]p9b3:
3771 //
Mike Stump1eb44332009-09-09 15:08:12 +00003772 // -- The argument list of the specialization shall not be identical
3773 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003774 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003775 << (TUK == TUK_Definition)
Douglas Gregor849b2432010-03-31 17:46:05 +00003776 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003777 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003778 ClassTemplate->getIdentifier(),
3779 TemplateNameLoc,
3780 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003781 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003782 AS_none);
3783 }
3784
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003785 // FIXME: Diagnose friend partial specializations
3786
Douglas Gregorde090962010-02-09 00:37:32 +00003787 if (!Name.isDependent() &&
3788 !TemplateSpecializationType::anyDependentTemplateArguments(
3789 TemplateArgs.getArgumentArray(),
3790 TemplateArgs.size())) {
3791 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3792 << ClassTemplate->getDeclName();
3793 isPartialSpecialization = false;
3794 } else {
3795 // FIXME: Template parameter list matters, too
3796 ClassTemplatePartialSpecializationDecl::Profile(ID,
3797 Converted.getFlatArguments(),
3798 Converted.flatSize(),
3799 Context);
3800 }
3801 }
3802
3803 if (!isPartialSpecialization)
Anders Carlsson1c5976e2009-06-05 03:43:12 +00003804 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003805 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003806 Converted.flatSize(),
3807 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00003808 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003809 ClassTemplateSpecializationDecl *PrevDecl = 0;
3810
3811 if (isPartialSpecialization)
3812 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00003813 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003814 InsertPos);
3815 else
3816 PrevDecl
3817 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003818
3819 ClassTemplateSpecializationDecl *Specialization = 0;
3820
Douglas Gregor88b70942009-02-25 22:02:03 +00003821 // Check whether we can declare a class template specialization in
3822 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003823 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003824 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003825 TemplateNameLoc,
3826 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003827 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003828
Douglas Gregorb88e8882009-07-30 17:40:51 +00003829 // The canonical type
3830 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003831 if (PrevDecl &&
3832 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00003833 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003834 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003835 // arguments was referenced but not declared, or we're only
3836 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003837 // declaration node as our own, updating its source location to
3838 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003839 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003840 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003841 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003842 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003843 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003844 // Build the canonical type that describes the converted template
3845 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00003846 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3847 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb88e8882009-07-30 17:40:51 +00003848 Converted.getFlatArguments(),
3849 Converted.flatSize());
3850
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003851 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003852 ClassTemplatePartialSpecializationDecl *PrevPartial
3853 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00003854 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
3855 : ClassTemplate->getPartialSpecializations().size();
Mike Stump1eb44332009-09-09 15:08:12 +00003856 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00003857 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003858 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003859 TemplateNameLoc,
3860 TemplateParams,
3861 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003862 Converted,
John McCalld5532b62009-11-23 01:53:49 +00003863 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00003864 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00003865 PrevPartial,
3866 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00003867 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara9b934882010-06-12 08:15:14 +00003868 if (NumMatchedTemplateParamLists > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00003869 Partial->setTemplateParameterListsInfo(Context,
3870 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00003871 (TemplateParameterList**) TemplateParameterLists.release());
3872 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003873
3874 if (PrevPartial) {
3875 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3876 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3877 } else {
3878 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3879 }
3880 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003881
Douglas Gregored9c0f92009-10-29 00:04:11 +00003882 // If we are providing an explicit specialization of a member class
3883 // template specialization, make a note of that.
3884 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3885 PrevPartial->setMemberSpecialization();
3886
Douglas Gregor031a5882009-06-13 00:26:55 +00003887 // Check that all of the template parameters of the class template
3888 // partial specialization are deducible from the template
3889 // arguments. If not, this class template partial specialization
3890 // will never be used.
3891 llvm::SmallVector<bool, 8> DeducibleParams;
3892 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003893 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003894 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003895 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003896 unsigned NumNonDeducible = 0;
3897 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3898 if (!DeducibleParams[I])
3899 ++NumNonDeducible;
3900
3901 if (NumNonDeducible) {
3902 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3903 << (NumNonDeducible > 1)
3904 << SourceRange(TemplateNameLoc, RAngleLoc);
3905 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3906 if (!DeducibleParams[I]) {
3907 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3908 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003909 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003910 diag::note_partial_spec_unused_parameter)
3911 << Param->getDeclName();
3912 else
Mike Stump1eb44332009-09-09 15:08:12 +00003913 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003914 diag::note_partial_spec_unused_parameter)
3915 << std::string("<anonymous>");
3916 }
3917 }
3918 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003919 } else {
3920 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003921 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003922 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00003923 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00003924 ClassTemplate->getDeclContext(),
3925 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003926 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003927 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003928 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00003929 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara9b934882010-06-12 08:15:14 +00003930 if (NumMatchedTemplateParamLists > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00003931 Specialization->setTemplateParameterListsInfo(Context,
3932 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00003933 (TemplateParameterList**) TemplateParameterLists.release());
3934 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003935
3936 if (PrevDecl) {
3937 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3938 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3939 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003940 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00003941 InsertPos);
3942 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00003943
3944 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003945 }
3946
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003947 // C++ [temp.expl.spec]p6:
3948 // If a template, a member template or the member of a class template is
3949 // explicitly specialized then that specialization shall be declared
3950 // before the first use of that specialization that would cause an implicit
3951 // instantiation to take place, in every translation unit in which such a
3952 // use occurs; no diagnostic is required.
3953 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003954 bool Okay = false;
3955 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3956 // Is there any previous explicit specialization declaration?
3957 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3958 Okay = true;
3959 break;
3960 }
3961 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003962
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003963 if (!Okay) {
3964 SourceRange Range(TemplateNameLoc, RAngleLoc);
3965 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3966 << Context.getTypeDeclType(Specialization) << Range;
3967
3968 Diag(PrevDecl->getPointOfInstantiation(),
3969 diag::note_instantiation_required_here)
3970 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003971 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003972 return true;
3973 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003974 }
3975
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003976 // If this is not a friend, note that this is an explicit specialization.
3977 if (TUK != TUK_Friend)
3978 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003979
3980 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003981 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00003982 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003983 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003984 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003985 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003986 Diag(Def->getLocation(), diag::note_previous_definition);
3987 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003988 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003989 }
3990 }
3991
Douglas Gregorfc705b82009-02-26 22:19:44 +00003992 // Build the fully-sugared type for this class template
3993 // specialization as the user wrote in the specialization
3994 // itself. This means that we'll pretty-print the type retrieved
3995 // from the specialization's declaration the way that the user
3996 // actually wrote the specialization, rather than formatting the
3997 // name based on the "canonical" representation used to store the
3998 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00003999 TypeSourceInfo *WrittenTy
4000 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4001 TemplateArgs, CanonType);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004002 if (TUK != TUK_Friend) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004003 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004004 Specialization->setTemplateKeywordLoc(KWLoc);
4005 }
Douglas Gregor40808ce2009-03-09 23:48:35 +00004006 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00004007
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004008 // C++ [temp.expl.spec]p9:
4009 // A template explicit specialization is in the scope of the
4010 // namespace in which the template was defined.
4011 //
4012 // We actually implement this paragraph where we set the semantic
4013 // context (in the creation of the ClassTemplateSpecializationDecl),
4014 // but we also maintain the lexical context where the actual
4015 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00004016 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004017
Douglas Gregorcc636682009-02-17 23:15:12 +00004018 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004019 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00004020 Specialization->startDefinition();
4021
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004022 if (TUK == TUK_Friend) {
4023 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4024 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00004025 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004026 /*FIXME:*/KWLoc);
4027 Friend->setAccess(AS_public);
4028 CurContext->addDecl(Friend);
4029 } else {
4030 // Add the specialization into its lexical context, so that it can
4031 // be seen when iterating through the list of declarations in that
4032 // context. However, specializations are not found by name lookup.
4033 CurContext->addDecl(Specialization);
4034 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00004035 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004036}
Douglas Gregord57959a2009-03-27 23:10:48 +00004037
Mike Stump1eb44332009-09-09 15:08:12 +00004038Sema::DeclPtrTy
4039Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00004040 MultiTemplateParamsArg TemplateParameterLists,
4041 Declarator &D) {
4042 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4043}
4044
Mike Stump1eb44332009-09-09 15:08:12 +00004045Sema::DeclPtrTy
4046Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00004047 MultiTemplateParamsArg TemplateParameterLists,
4048 Declarator &D) {
4049 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4050 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4051 "Not a function declarator!");
4052 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00004053
Douglas Gregor52591bf2009-06-24 00:54:41 +00004054 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00004055 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00004056 }
Mike Stump1eb44332009-09-09 15:08:12 +00004057
Douglas Gregor52591bf2009-06-24 00:54:41 +00004058 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004059
4060 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00004061 move(TemplateParameterLists),
4062 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004063 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00004064 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00004065 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00004066 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00004067 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
4068 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00004069 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00004070}
4071
John McCall75042392010-02-11 01:33:53 +00004072/// \brief Strips various properties off an implicit instantiation
4073/// that has just been explicitly specialized.
4074static void StripImplicitInstantiation(NamedDecl *D) {
4075 D->invalidateAttrs();
4076
4077 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4078 FD->setInlineSpecified(false);
4079 }
4080}
4081
Douglas Gregor454885e2009-10-15 15:54:05 +00004082/// \brief Diagnose cases where we have an explicit template specialization
4083/// before/after an explicit template instantiation, producing diagnostics
4084/// for those cases where they are required and determining whether the
4085/// new specialization/instantiation will have any effect.
4086///
Douglas Gregor454885e2009-10-15 15:54:05 +00004087/// \param NewLoc the location of the new explicit specialization or
4088/// instantiation.
4089///
4090/// \param NewTSK the kind of the new explicit specialization or instantiation.
4091///
4092/// \param PrevDecl the previous declaration of the entity.
4093///
4094/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4095///
4096/// \param PrevPointOfInstantiation if valid, indicates where the previus
4097/// declaration was instantiated (either implicitly or explicitly).
4098///
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004099/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregor454885e2009-10-15 15:54:05 +00004100/// specialization or instantiation has no effect and should be ignored.
4101///
4102/// \returns true if there was an error that should prevent the introduction of
4103/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00004104bool
4105Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4106 TemplateSpecializationKind NewTSK,
4107 NamedDecl *PrevDecl,
4108 TemplateSpecializationKind PrevTSK,
4109 SourceLocation PrevPointOfInstantiation,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004110 bool &HasNoEffect) {
4111 HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00004112
4113 switch (NewTSK) {
4114 case TSK_Undeclared:
4115 case TSK_ImplicitInstantiation:
4116 assert(false && "Don't check implicit instantiations here");
4117 return false;
4118
4119 case TSK_ExplicitSpecialization:
4120 switch (PrevTSK) {
4121 case TSK_Undeclared:
4122 case TSK_ExplicitSpecialization:
4123 // Okay, we're just specializing something that is either already
4124 // explicitly specialized or has merely been mentioned without any
4125 // instantiation.
4126 return false;
4127
4128 case TSK_ImplicitInstantiation:
4129 if (PrevPointOfInstantiation.isInvalid()) {
4130 // The declaration itself has not actually been instantiated, so it is
4131 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00004132 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00004133 return false;
4134 }
4135 // Fall through
4136
4137 case TSK_ExplicitInstantiationDeclaration:
4138 case TSK_ExplicitInstantiationDefinition:
4139 assert((PrevTSK == TSK_ImplicitInstantiation ||
4140 PrevPointOfInstantiation.isValid()) &&
4141 "Explicit instantiation without point of instantiation?");
4142
4143 // C++ [temp.expl.spec]p6:
4144 // If a template, a member template or the member of a class template
4145 // is explicitly specialized then that specialization shall be declared
4146 // before the first use of that specialization that would cause an
4147 // implicit instantiation to take place, in every translation unit in
4148 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004149 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4150 // Is there any previous explicit specialization declaration?
4151 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4152 return false;
4153 }
4154
Douglas Gregor0d035142009-10-27 18:42:08 +00004155 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00004156 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004157 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00004158 << (PrevTSK != TSK_ImplicitInstantiation);
4159
4160 return true;
4161 }
4162 break;
4163
4164 case TSK_ExplicitInstantiationDeclaration:
4165 switch (PrevTSK) {
4166 case TSK_ExplicitInstantiationDeclaration:
4167 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004168 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004169 return false;
4170
4171 case TSK_Undeclared:
4172 case TSK_ImplicitInstantiation:
4173 // We're explicitly instantiating something that may have already been
4174 // implicitly instantiated; that's fine.
4175 return false;
4176
4177 case TSK_ExplicitSpecialization:
4178 // C++0x [temp.explicit]p4:
4179 // For a given set of template parameters, if an explicit instantiation
4180 // of a template appears after a declaration of an explicit
4181 // specialization for that template, the explicit instantiation has no
4182 // effect.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004183 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004184 return false;
4185
4186 case TSK_ExplicitInstantiationDefinition:
4187 // C++0x [temp.explicit]p10:
4188 // If an entity is the subject of both an explicit instantiation
4189 // declaration and an explicit instantiation definition in the same
4190 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00004191 Diag(NewLoc,
4192 diag::err_explicit_instantiation_declaration_after_definition);
4193 Diag(PrevPointOfInstantiation,
4194 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00004195 assert(PrevPointOfInstantiation.isValid() &&
4196 "Explicit instantiation without point of instantiation?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004197 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004198 return false;
4199 }
4200 break;
4201
4202 case TSK_ExplicitInstantiationDefinition:
4203 switch (PrevTSK) {
4204 case TSK_Undeclared:
4205 case TSK_ImplicitInstantiation:
4206 // We're explicitly instantiating something that may have already been
4207 // implicitly instantiated; that's fine.
4208 return false;
4209
4210 case TSK_ExplicitSpecialization:
4211 // C++ DR 259, C++0x [temp.explicit]p4:
4212 // For a given set of template parameters, if an explicit
4213 // instantiation of a template appears after a declaration of
4214 // an explicit specialization for that template, the explicit
4215 // instantiation has no effect.
4216 //
4217 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00004218 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00004219 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00004220 if (!getLangOptions().CPlusPlus0x) {
4221 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00004222 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004223 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00004224 diag::note_previous_template_specialization);
4225 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004226 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004227 return false;
4228
4229 case TSK_ExplicitInstantiationDeclaration:
4230 // We're explicity instantiating a definition for something for which we
4231 // were previously asked to suppress instantiations. That's fine.
4232 return false;
4233
4234 case TSK_ExplicitInstantiationDefinition:
4235 // C++0x [temp.spec]p5:
4236 // For a given template and a given set of template-arguments,
4237 // - an explicit instantiation definition shall appear at most once
4238 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00004239 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00004240 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004241 Diag(PrevPointOfInstantiation,
4242 diag::note_previous_explicit_instantiation);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004243 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004244 return false;
4245 }
4246 break;
4247 }
4248
4249 assert(false && "Missing specialization/instantiation case?");
4250
4251 return false;
4252}
4253
John McCallaf2094e2010-04-08 09:05:18 +00004254/// \brief Perform semantic analysis for the given dependent function
4255/// template specialization. The only possible way to get a dependent
4256/// function template specialization is with a friend declaration,
4257/// like so:
4258///
4259/// template <class T> void foo(T);
4260/// template <class T> class A {
4261/// friend void foo<>(T);
4262/// };
4263///
4264/// There really isn't any useful analysis we can do here, so we
4265/// just store the information.
4266bool
4267Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4268 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4269 LookupResult &Previous) {
4270 // Remove anything from Previous that isn't a function template in
4271 // the correct context.
4272 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4273 LookupResult::Filter F = Previous.makeFilter();
4274 while (F.hasNext()) {
4275 NamedDecl *D = F.next()->getUnderlyingDecl();
4276 if (!isa<FunctionTemplateDecl>(D) ||
4277 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4278 F.erase();
4279 }
4280 F.done();
4281
4282 // Should this be diagnosed here?
4283 if (Previous.empty()) return true;
4284
4285 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4286 ExplicitTemplateArgs);
4287 return false;
4288}
4289
Abramo Bagnarae03db982010-05-20 15:32:11 +00004290/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004291/// specialization.
4292///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004293/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004294/// explicit function template specialization. On successful completion,
4295/// the function declaration \p FD will become a function template
4296/// specialization.
4297///
4298/// \param FD the function declaration, which will be updated to become a
4299/// function template specialization.
4300///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004301/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4302/// if any. Note that this may be valid info even when 0 arguments are
4303/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4304/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004305///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004306/// \param PrevDecl the set of declarations that may be specialized by
4307/// this function specialization.
4308bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004309Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004310 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004311 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004312 // The set of function template specializations that could match this
4313 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004314 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004315
4316 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall68263142009-11-18 22:49:29 +00004317 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4318 I != E; ++I) {
4319 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4320 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004321 // Only consider templates found within the same semantic lookup scope as
4322 // FD.
4323 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4324 continue;
4325
4326 // C++ [temp.expl.spec]p11:
4327 // A trailing template-argument can be left unspecified in the
4328 // template-id naming an explicit function template specialization
4329 // provided it can be deduced from the function argument type.
4330 // Perform template argument deduction to determine whether we may be
4331 // specializing this template.
4332 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004333 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004334 FunctionDecl *Specialization = 0;
4335 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004336 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004337 FD->getType(),
4338 Specialization,
4339 Info)) {
4340 // FIXME: Template argument deduction failed; record why it failed, so
4341 // that we can provide nifty diagnostics.
4342 (void)TDK;
4343 continue;
4344 }
4345
4346 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004347 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004348 }
4349 }
4350
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004351 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004352 UnresolvedSetIterator Result
4353 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4354 TPOC_Other, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004355 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004356 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004357 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004358 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004359 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004360 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004361 return true;
John McCallc373d482010-01-27 01:50:18 +00004362
4363 // Ignore access information; it doesn't figure into redeclaration checking.
4364 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorc42b6522010-04-09 21:02:29 +00004365 Specialization->setLocation(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004366
4367 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004368 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004369
4370 // If this is a friend declaration, then we're not really declaring
4371 // an explicit specialization.
4372 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004373
Douglas Gregord5cb8762009-10-07 00:13:32 +00004374 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004375 if (!isFriend &&
4376 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004377 Specialization->getPrimaryTemplate(),
4378 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004379 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004380 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004381
4382 // C++ [temp.expl.spec]p6:
4383 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004384 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004385 // before the first use of that specialization that would cause an implicit
4386 // instantiation to take place, in every translation unit in which such a
4387 // use occurs; no diagnostic is required.
4388 FunctionTemplateSpecializationInfo *SpecInfo
4389 = Specialization->getTemplateSpecializationInfo();
4390 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004391
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004392 bool HasNoEffect = false;
John McCall7ad650f2010-03-24 07:46:06 +00004393 if (!isFriend &&
4394 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004395 TSK_ExplicitSpecialization,
4396 Specialization,
4397 SpecInfo->getTemplateSpecializationKind(),
4398 SpecInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004399 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004400 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004401
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004402 // Mark the prior declaration as an explicit specialization, so that later
4403 // clients know that this is an explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004404 if (!isFriend)
4405 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004406
4407 // Turn the given function declaration into a function template
4408 // specialization, with the template arguments from the previous
4409 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00004410 // Take copies of (semantic and syntactic) template argument lists.
4411 const TemplateArgumentList* TemplArgs = new (Context)
4412 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4413 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4414 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregor838db382010-02-11 01:19:42 +00004415 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00004416 TemplArgs, /*InsertPos=*/0,
4417 SpecInfo->getTemplateSpecializationKind(),
4418 TemplArgsAsWritten);
4419
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004420 // The "previous declaration" for this function template specialization is
4421 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004422 Previous.clear();
4423 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004424 return false;
4425}
4426
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004427/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004428/// specialization.
4429///
4430/// This routine performs all of the semantic analysis required for an
4431/// explicit member function specialization. On successful completion,
4432/// the function declaration \p FD will become a member function
4433/// specialization.
4434///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004435/// \param Member the member declaration, which will be updated to become a
4436/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004437///
John McCall68263142009-11-18 22:49:29 +00004438/// \param Previous the set of declarations, one of which may be specialized
4439/// by this function specialization; the set will be modified to contain the
4440/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004441bool
John McCall68263142009-11-18 22:49:29 +00004442Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004443 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00004444
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004445 // Try to find the member we are instantiating.
4446 NamedDecl *Instantiation = 0;
4447 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004448 MemberSpecializationInfo *MSInfo = 0;
4449
John McCall68263142009-11-18 22:49:29 +00004450 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004451 // Nowhere to look anyway.
4452 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004453 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4454 I != E; ++I) {
4455 NamedDecl *D = (*I)->getUnderlyingDecl();
4456 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004457 if (Context.hasSameType(Function->getType(), Method->getType())) {
4458 Instantiation = Method;
4459 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004460 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004461 break;
4462 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004463 }
4464 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004465 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004466 VarDecl *PrevVar;
4467 if (Previous.isSingleResult() &&
4468 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004469 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004470 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004471 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004472 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004473 }
4474 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004475 CXXRecordDecl *PrevRecord;
4476 if (Previous.isSingleResult() &&
4477 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4478 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004479 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004480 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004481 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004482 }
4483
4484 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004485 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004486 // specializations are always out-of-line, the caller will complain about
4487 // this mismatch later.
4488 return false;
4489 }
John McCall77e8b112010-04-13 20:37:33 +00004490
4491 // If this is a friend, just bail out here before we start turning
4492 // things into explicit specializations.
4493 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4494 // Preserve instantiation information.
4495 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4496 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4497 cast<CXXMethodDecl>(InstantiatedFrom),
4498 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4499 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4500 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4501 cast<CXXRecordDecl>(InstantiatedFrom),
4502 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4503 }
4504
4505 Previous.clear();
4506 Previous.addDecl(Instantiation);
4507 return false;
4508 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004509
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004510 // Make sure that this is a specialization of a member.
4511 if (!InstantiatedFrom) {
4512 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4513 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004514 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4515 return true;
4516 }
4517
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004518 // C++ [temp.expl.spec]p6:
4519 // If a template, a member template or the member of a class template is
4520 // explicitly specialized then that spe- cialization shall be declared
4521 // before the first use of that specialization that would cause an implicit
4522 // instantiation to take place, in every translation unit in which such a
4523 // use occurs; no diagnostic is required.
4524 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004525
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004526 bool HasNoEffect = false;
John McCall75042392010-02-11 01:33:53 +00004527 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4528 TSK_ExplicitSpecialization,
4529 Instantiation,
4530 MSInfo->getTemplateSpecializationKind(),
4531 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004532 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004533 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004534
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004535 // Check the scope of this explicit specialization.
4536 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004537 InstantiatedFrom,
4538 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004539 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004540 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004541
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004542 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004543 // the original declaration to note that it is an explicit specialization
4544 // (if it was previously an implicit instantiation). This latter step
4545 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004546 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004547 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4548 if (InstantiationFunction->getTemplateSpecializationKind() ==
4549 TSK_ImplicitInstantiation) {
4550 InstantiationFunction->setTemplateSpecializationKind(
4551 TSK_ExplicitSpecialization);
4552 InstantiationFunction->setLocation(Member->getLocation());
4553 }
4554
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004555 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4556 cast<CXXMethodDecl>(InstantiatedFrom),
4557 TSK_ExplicitSpecialization);
4558 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004559 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4560 if (InstantiationVar->getTemplateSpecializationKind() ==
4561 TSK_ImplicitInstantiation) {
4562 InstantiationVar->setTemplateSpecializationKind(
4563 TSK_ExplicitSpecialization);
4564 InstantiationVar->setLocation(Member->getLocation());
4565 }
4566
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004567 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4568 cast<VarDecl>(InstantiatedFrom),
4569 TSK_ExplicitSpecialization);
4570 } else {
4571 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004572 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4573 if (InstantiationClass->getTemplateSpecializationKind() ==
4574 TSK_ImplicitInstantiation) {
4575 InstantiationClass->setTemplateSpecializationKind(
4576 TSK_ExplicitSpecialization);
4577 InstantiationClass->setLocation(Member->getLocation());
4578 }
4579
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004580 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004581 cast<CXXRecordDecl>(InstantiatedFrom),
4582 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004583 }
4584
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004585 // Save the caller the trouble of having to figure out which declaration
4586 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004587 Previous.clear();
4588 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004589 return false;
4590}
4591
Douglas Gregor558c0322009-10-14 23:41:34 +00004592/// \brief Check the scope of an explicit instantiation.
4593static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4594 SourceLocation InstLoc,
4595 bool WasQualifiedName) {
4596 DeclContext *ExpectedContext
4597 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4598 DeclContext *CurContext = S.CurContext->getLookupContext();
4599
4600 // C++0x [temp.explicit]p2:
4601 // An explicit instantiation shall appear in an enclosing namespace of its
4602 // template.
4603 //
4604 // This is DR275, which we do not retroactively apply to C++98/03.
4605 if (S.getLangOptions().CPlusPlus0x &&
4606 !CurContext->Encloses(ExpectedContext)) {
4607 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregor2166beb2010-05-11 17:39:34 +00004608 S.Diag(InstLoc,
4609 S.getLangOptions().CPlusPlus0x?
4610 diag::err_explicit_instantiation_out_of_scope
4611 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004612 << D << NS;
4613 else
Douglas Gregor2166beb2010-05-11 17:39:34 +00004614 S.Diag(InstLoc,
4615 S.getLangOptions().CPlusPlus0x?
4616 diag::err_explicit_instantiation_must_be_global
4617 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004618 << D;
4619 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4620 return;
4621 }
4622
4623 // C++0x [temp.explicit]p2:
4624 // If the name declared in the explicit instantiation is an unqualified
4625 // name, the explicit instantiation shall appear in the namespace where
4626 // its template is declared or, if that namespace is inline (7.3.1), any
4627 // namespace from its enclosing namespace set.
4628 if (WasQualifiedName)
4629 return;
4630
4631 if (CurContext->Equals(ExpectedContext))
4632 return;
4633
Douglas Gregor2166beb2010-05-11 17:39:34 +00004634 S.Diag(InstLoc,
4635 S.getLangOptions().CPlusPlus0x?
4636 diag::err_explicit_instantiation_unqualified_wrong_namespace
4637 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004638 << D << ExpectedContext;
4639 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4640}
4641
4642/// \brief Determine whether the given scope specifier has a template-id in it.
4643static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4644 if (!SS.isSet())
4645 return false;
4646
4647 // C++0x [temp.explicit]p2:
4648 // If the explicit instantiation is for a member function, a member class
4649 // or a static data member of a class template specialization, the name of
4650 // the class template specialization in the qualified-id for the member
4651 // name shall be a simple-template-id.
4652 //
4653 // C++98 has the same restriction, just worded differently.
4654 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4655 NNS; NNS = NNS->getPrefix())
4656 if (Type *T = NNS->getAsType())
4657 if (isa<TemplateSpecializationType>(T))
4658 return true;
4659
4660 return false;
4661}
4662
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004663// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004664Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004665Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004666 SourceLocation ExternLoc,
4667 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004668 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004669 SourceLocation KWLoc,
4670 const CXXScopeSpec &SS,
4671 TemplateTy TemplateD,
4672 SourceLocation TemplateNameLoc,
4673 SourceLocation LAngleLoc,
4674 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004675 SourceLocation RAngleLoc,
4676 AttributeList *Attr) {
4677 // Find the class template we're specializing
4678 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004679 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004680 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4681
4682 // Check that the specialization uses the same tag kind as the
4683 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004684 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4685 assert(Kind != TTK_Enum &&
4686 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004687 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004688 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004689 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004690 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004691 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004692 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004693 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004694 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004695 diag::note_previous_use);
4696 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4697 }
4698
Douglas Gregor558c0322009-10-14 23:41:34 +00004699 // C++0x [temp.explicit]p2:
4700 // There are two forms of explicit instantiation: an explicit instantiation
4701 // definition and an explicit instantiation declaration. An explicit
4702 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00004703 TemplateSpecializationKind TSK
4704 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4705 : TSK_ExplicitInstantiationDeclaration;
4706
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004707 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004708 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004709 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004710
4711 // Check that the template argument list is well-formed for this
4712 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00004713 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4714 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00004715 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4716 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004717 return true;
4718
Mike Stump1eb44332009-09-09 15:08:12 +00004719 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004720 ClassTemplate->getTemplateParameters()->size()) &&
4721 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004722
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004723 // Find the class template specialization declaration that
4724 // corresponds to these arguments.
4725 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00004726 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00004727 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00004728 Converted.flatSize(),
4729 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004730 void *InsertPos = 0;
4731 ClassTemplateSpecializationDecl *PrevDecl
4732 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4733
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004734 TemplateSpecializationKind PrevDecl_TSK
4735 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4736
Douglas Gregord5cb8762009-10-07 00:13:32 +00004737 // C++0x [temp.explicit]p2:
4738 // [...] An explicit instantiation shall appear in an enclosing
4739 // namespace of its template. [...]
4740 //
4741 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004742 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4743 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00004744
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004745 ClassTemplateSpecializationDecl *Specialization = 0;
4746
Douglas Gregord78f5982009-11-25 06:01:46 +00004747 bool ReusedDecl = false;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004748 bool HasNoEffect = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004749 if (PrevDecl) {
Douglas Gregor0d035142009-10-27 18:42:08 +00004750 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004751 PrevDecl, PrevDecl_TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004752 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004753 HasNoEffect))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004754 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004755
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004756 // Even though HasNoEffect == true means that this explicit instantiation
4757 // has no effect on semantics, we go on to put its syntax in the AST.
4758
4759 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4760 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor52604ab2009-09-11 21:19:12 +00004761 // Since the only prior class template specialization with these
4762 // arguments was referenced but not declared, reuse that
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004763 // declaration node as our own, updating the source location
4764 // for the template name to reflect our new declaration.
4765 // (Other source locations will be updated later.)
Douglas Gregor52604ab2009-09-11 21:19:12 +00004766 Specialization = PrevDecl;
4767 Specialization->setLocation(TemplateNameLoc);
4768 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00004769 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00004770 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004771 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004772
Douglas Gregor52604ab2009-09-11 21:19:12 +00004773 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004774 // Create a new class template specialization declaration node for
4775 // this explicit specialization.
4776 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00004777 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004778 ClassTemplate->getDeclContext(),
4779 TemplateNameLoc,
4780 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00004781 Converted, PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004782 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004783
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004784 if (!HasNoEffect) {
4785 if (PrevDecl) {
4786 // Remove the previous declaration from the folding set, since we want
4787 // to introduce a new declaration.
4788 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4789 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4790 }
4791 // Insert the new specialization.
4792 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
4793 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004794 }
4795
4796 // Build the fully-sugared type for this explicit instantiation as
4797 // the user wrote in the explicit instantiation itself. This means
4798 // that we'll pretty-print the type retrieved from the
4799 // specialization's declaration the way that the user actually wrote
4800 // the explicit instantiation, rather than formatting the name based
4801 // on the "canonical" representation used to store the template
4802 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004803 TypeSourceInfo *WrittenTy
4804 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4805 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004806 Context.getTypeDeclType(Specialization));
4807 Specialization->setTypeAsWritten(WrittenTy);
4808 TemplateArgsIn.release();
4809
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004810 // Set source locations for keywords.
4811 Specialization->setExternLoc(ExternLoc);
4812 Specialization->setTemplateKeywordLoc(TemplateLoc);
4813
4814 // Add the explicit instantiation into its lexical context. However,
4815 // since explicit instantiations are never found by name lookup, we
4816 // just put it into the declaration context directly.
4817 Specialization->setLexicalDeclContext(CurContext);
4818 CurContext->addDecl(Specialization);
4819
4820 // Syntax is now OK, so return if it has no other effect on semantics.
4821 if (HasNoEffect) {
4822 // Set the template specialization kind.
4823 Specialization->setTemplateSpecializationKind(TSK);
4824 return DeclPtrTy::make(Specialization);
Douglas Gregord78f5982009-11-25 06:01:46 +00004825 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004826
4827 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004828 // A definition of a class template or class member template
4829 // shall be in scope at the point of the explicit instantiation of
4830 // the class template or class member template.
4831 //
4832 // This check comes when we actually try to perform the
4833 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004834 ClassTemplateSpecializationDecl *Def
4835 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004836 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004837 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004838 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004839 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004840 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004841 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
4842 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004843
Douglas Gregor0d035142009-10-27 18:42:08 +00004844 // Instantiate the members of this class template specialization.
4845 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004846 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004847 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00004848 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4849
4850 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4851 // TSK_ExplicitInstantiationDefinition
4852 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4853 TSK == TSK_ExplicitInstantiationDefinition)
4854 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004855
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004856 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004857 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004858
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004859 // Set the template specialization kind.
4860 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004861 return DeclPtrTy::make(Specialization);
4862}
4863
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004864// Explicit instantiation of a member class of a class template.
4865Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004866Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004867 SourceLocation ExternLoc,
4868 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004869 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004870 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004871 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004872 IdentifierInfo *Name,
4873 SourceLocation NameLoc,
4874 AttributeList *Attr) {
4875
Douglas Gregor402abb52009-05-28 23:31:59 +00004876 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004877 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00004878 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004879 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00004880 MultiTemplateParamsArg(*this, 0, 0),
4881 Owned, IsDependent);
4882 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4883
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004884 if (!TagD)
4885 return true;
4886
4887 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4888 if (Tag->isEnum()) {
4889 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4890 << Context.getTypeDeclType(Tag);
4891 return true;
4892 }
4893
Douglas Gregord0c87372009-05-27 17:30:49 +00004894 if (Tag->isInvalidDecl())
4895 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004896
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004897 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4898 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4899 if (!Pattern) {
4900 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4901 << Context.getTypeDeclType(Record);
4902 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4903 return true;
4904 }
4905
Douglas Gregor558c0322009-10-14 23:41:34 +00004906 // C++0x [temp.explicit]p2:
4907 // If the explicit instantiation is for a class or member class, the
4908 // elaborated-type-specifier in the declaration shall include a
4909 // simple-template-id.
4910 //
4911 // C++98 has the same restriction, just worded differently.
4912 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregora2dd8282010-06-16 16:26:47 +00004913 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00004914 << Record << SS.getRange();
4915
4916 // C++0x [temp.explicit]p2:
4917 // There are two forms of explicit instantiation: an explicit instantiation
4918 // definition and an explicit instantiation declaration. An explicit
4919 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004920 TemplateSpecializationKind TSK
4921 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4922 : TSK_ExplicitInstantiationDeclaration;
4923
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004924 // C++0x [temp.explicit]p2:
4925 // [...] An explicit instantiation shall appear in an enclosing
4926 // namespace of its template. [...]
4927 //
4928 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004929 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004930
4931 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004932 CXXRecordDecl *PrevDecl
4933 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00004934 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00004935 PrevDecl = Record;
4936 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004937 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004938 bool HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00004939 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004940 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004941 PrevDecl,
4942 MSInfo->getTemplateSpecializationKind(),
4943 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004944 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00004945 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004946 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00004947 return TagD;
4948 }
4949
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004950 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00004951 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004952 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004953 // C++ [temp.explicit]p3:
4954 // A definition of a member class of a class template shall be in scope
4955 // at the point of an explicit instantiation of the member class.
4956 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00004957 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004958 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004959 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4960 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004961 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4962 << Pattern;
4963 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004964 } else {
4965 if (InstantiateClass(NameLoc, Record, Def,
4966 getTemplateInstantiationArgs(Record),
4967 TSK))
4968 return true;
4969
Douglas Gregor952b0172010-02-11 01:04:33 +00004970 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00004971 if (!RecordDef)
4972 return true;
4973 }
4974 }
4975
4976 // Instantiate all of the members of the class.
4977 InstantiateClassMembers(NameLoc, RecordDef,
4978 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004979
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004980 if (TSK == TSK_ExplicitInstantiationDefinition)
4981 MarkVTableUsed(NameLoc, RecordDef, true);
4982
Mike Stump390b4cc2009-05-16 07:39:55 +00004983 // FIXME: We don't have any representation for explicit instantiations of
4984 // member classes. Such a representation is not needed for compilation, but it
4985 // should be available for clients that want to see all of the declarations in
4986 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004987 return TagD;
4988}
4989
Douglas Gregord5a423b2009-09-25 18:43:00 +00004990Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4991 SourceLocation ExternLoc,
4992 SourceLocation TemplateLoc,
4993 Declarator &D) {
4994 // Explicit instantiations always require a name.
4995 DeclarationName Name = GetNameForDeclarator(D);
4996 if (!Name) {
4997 if (!D.isInvalidType())
4998 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4999 diag::err_explicit_instantiation_requires_name)
5000 << D.getDeclSpec().getSourceRange()
5001 << D.getSourceRange();
5002
5003 return true;
5004 }
5005
5006 // The scope passed in may not be a decl scope. Zip up the scope tree until
5007 // we find one that is.
5008 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5009 (S->getFlags() & Scope::TemplateParamScope) != 0)
5010 S = S->getParent();
5011
5012 // Determine the type of the declaration.
John McCallbf1a0282010-06-04 23:28:52 +00005013 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5014 QualType R = T->getType();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005015 if (R.isNull())
5016 return true;
5017
5018 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5019 // Cannot explicitly instantiate a typedef.
5020 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5021 << Name;
5022 return true;
5023 }
5024
Douglas Gregor663b5a02009-10-14 20:14:33 +00005025 // C++0x [temp.explicit]p1:
5026 // [...] An explicit instantiation of a function template shall not use the
5027 // inline or constexpr specifiers.
5028 // Presumably, this also applies to member functions of class templates as
5029 // well.
5030 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5031 Diag(D.getDeclSpec().getInlineSpecLoc(),
5032 diag::err_explicit_instantiation_inline)
Douglas Gregor849b2432010-03-31 17:46:05 +00005033 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00005034
5035 // FIXME: check for constexpr specifier.
5036
Douglas Gregor558c0322009-10-14 23:41:34 +00005037 // C++0x [temp.explicit]p2:
5038 // There are two forms of explicit instantiation: an explicit instantiation
5039 // definition and an explicit instantiation declaration. An explicit
5040 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00005041 TemplateSpecializationKind TSK
5042 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5043 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00005044
John McCalla24dc2e2009-11-17 02:14:36 +00005045 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
5046 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005047
5048 if (!R->isFunctionType()) {
5049 // C++ [temp.explicit]p1:
5050 // A [...] static data member of a class template can be explicitly
5051 // instantiated from the member definition associated with its class
5052 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00005053 if (Previous.isAmbiguous())
5054 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005055
John McCall1bcee0a2009-12-02 08:25:40 +00005056 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005057 if (!Prev || !Prev->isStaticDataMember()) {
5058 // We expect to see a data data member here.
5059 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5060 << Name;
5061 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5062 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00005063 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005064 return true;
5065 }
5066
5067 if (!Prev->getInstantiatedFromStaticDataMember()) {
5068 // FIXME: Check for explicit specialization?
5069 Diag(D.getIdentifierLoc(),
5070 diag::err_explicit_instantiation_data_member_not_instantiated)
5071 << Prev;
5072 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5073 // FIXME: Can we provide a note showing where this was declared?
5074 return true;
5075 }
5076
Douglas Gregor558c0322009-10-14 23:41:34 +00005077 // C++0x [temp.explicit]p2:
5078 // If the explicit instantiation is for a member function, a member class
5079 // or a static data member of a class template specialization, the name of
5080 // the class template specialization in the qualified-id for the member
5081 // name shall be a simple-template-id.
5082 //
5083 // C++98 has the same restriction, just worded differently.
5084 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5085 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005086 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005087 << Prev << D.getCXXScopeSpec().getRange();
5088
5089 // Check the scope of this explicit instantiation.
5090 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5091
Douglas Gregor454885e2009-10-15 15:54:05 +00005092 // Verify that it is okay to explicitly instantiate here.
5093 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5094 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005095 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005096 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00005097 MSInfo->getTemplateSpecializationKind(),
5098 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005099 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005100 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005101 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00005102 return DeclPtrTy();
5103
Douglas Gregord5a423b2009-09-25 18:43:00 +00005104 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005105 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005106 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00005107 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
5108 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005109
5110 // FIXME: Create an ExplicitInstantiation node?
5111 return DeclPtrTy();
5112 }
5113
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005114 // If the declarator is a template-id, translate the parser's template
5115 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00005116 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00005117 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005118 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5119 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00005120 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5121 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00005122 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5123 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00005124 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00005125 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00005126 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00005127 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00005128 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005129
Douglas Gregord5a423b2009-09-25 18:43:00 +00005130 // C++ [temp.explicit]p1:
5131 // A [...] function [...] can be explicitly instantiated from its template.
5132 // A member function [...] of a class template can be explicitly
5133 // instantiated from the member definition associated with its class
5134 // template.
John McCallc373d482010-01-27 01:50:18 +00005135 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005136 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5137 P != PEnd; ++P) {
5138 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00005139 if (!HasExplicitTemplateArgs) {
5140 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5141 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5142 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00005143
John McCallc373d482010-01-27 01:50:18 +00005144 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00005145 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5146 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00005147 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00005148 }
5149 }
5150
5151 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5152 if (!FunTmpl)
5153 continue;
5154
John McCall5769d612010-02-08 23:07:23 +00005155 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005156 FunctionDecl *Specialization = 0;
5157 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00005158 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00005159 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00005160 R, Specialization, Info)) {
5161 // FIXME: Keep track of almost-matches?
5162 (void)TDK;
5163 continue;
5164 }
5165
John McCallc373d482010-01-27 01:50:18 +00005166 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005167 }
5168
5169 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005170 UnresolvedSetIterator Result
5171 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregord5a423b2009-09-25 18:43:00 +00005172 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005173 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5174 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5175 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00005176
John McCallc373d482010-01-27 01:50:18 +00005177 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00005178 return true;
John McCallc373d482010-01-27 01:50:18 +00005179
5180 // Ignore access control bits, we don't need them for redeclaration checking.
5181 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005182
Douglas Gregor0a897e32009-10-15 17:21:20 +00005183 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005184 Diag(D.getIdentifierLoc(),
5185 diag::err_explicit_instantiation_member_function_not_instantiated)
5186 << Specialization
5187 << (Specialization->getTemplateSpecializationKind() ==
5188 TSK_ExplicitSpecialization);
5189 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5190 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005191 }
Douglas Gregor558c0322009-10-14 23:41:34 +00005192
Douglas Gregor0a897e32009-10-15 17:21:20 +00005193 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00005194 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5195 PrevDecl = Specialization;
5196
Douglas Gregor0a897e32009-10-15 17:21:20 +00005197 if (PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005198 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005199 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00005200 PrevDecl,
5201 PrevDecl->getTemplateSpecializationKind(),
5202 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005203 HasNoEffect))
Douglas Gregor0a897e32009-10-15 17:21:20 +00005204 return true;
5205
5206 // FIXME: We may still want to build some representation of this
5207 // explicit specialization.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005208 if (HasNoEffect)
Douglas Gregor0a897e32009-10-15 17:21:20 +00005209 return DeclPtrTy();
5210 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00005211
5212 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00005213
5214 if (TSK == TSK_ExplicitInstantiationDefinition)
5215 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5216 false, /*DefinitionRequired=*/true);
Douglas Gregor0a897e32009-10-15 17:21:20 +00005217
Douglas Gregor558c0322009-10-14 23:41:34 +00005218 // C++0x [temp.explicit]p2:
5219 // If the explicit instantiation is for a member function, a member class
5220 // or a static data member of a class template specialization, the name of
5221 // the class template specialization in the qualified-id for the member
5222 // name shall be a simple-template-id.
5223 //
5224 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005225 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005226 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00005227 D.getCXXScopeSpec().isSet() &&
5228 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5229 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005230 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005231 << Specialization << D.getCXXScopeSpec().getRange();
5232
5233 CheckExplicitInstantiationScope(*this,
5234 FunTmpl? (NamedDecl *)FunTmpl
5235 : Specialization->getInstantiatedFromMemberFunction(),
5236 D.getIdentifierLoc(),
5237 D.getCXXScopeSpec().isSet());
5238
Douglas Gregord5a423b2009-09-25 18:43:00 +00005239 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5240 return DeclPtrTy();
5241}
5242
Douglas Gregord57959a2009-03-27 23:10:48 +00005243Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00005244Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5245 const CXXScopeSpec &SS, IdentifierInfo *Name,
5246 SourceLocation TagLoc, SourceLocation NameLoc) {
5247 // This has to hold, because SS is expected to be defined.
5248 assert(Name && "Expected a name in a dependent tag");
5249
5250 NestedNameSpecifier *NNS
5251 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5252 if (!NNS)
5253 return true;
5254
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005255 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005256
Douglas Gregor48c89f42010-04-24 16:38:41 +00005257 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5258 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005259 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00005260 return true;
5261 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005262
5263 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5264 return Context.getDependentNameType(Kwd, NNS, Name).getAsOpaquePtr();
John McCallc4e70192009-09-11 04:59:25 +00005265}
5266
5267Sema::TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005268Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5269 const CXXScopeSpec &SS, const IdentifierInfo &II,
5270 SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005271 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00005272 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5273 if (!NNS)
5274 return true;
5275
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005276 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5277 !getLangOptions().CPlusPlus0x)
5278 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5279 << FixItHint::CreateRemoval(TypenameLoc);
5280
Douglas Gregor107de902010-04-24 15:35:55 +00005281 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005282 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00005283 if (T.isNull())
5284 return true;
John McCall63b43852010-04-29 23:50:39 +00005285
5286 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5287 if (isa<DependentNameType>(T)) {
5288 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005289 TL.setKeywordLoc(TypenameLoc);
5290 TL.setQualifierRange(SS.getRange());
5291 TL.setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005292 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005293 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005294 TL.setKeywordLoc(TypenameLoc);
5295 TL.setQualifierRange(SS.getRange());
5296 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005297 }
5298
5299 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregord57959a2009-03-27 23:10:48 +00005300}
5301
Douglas Gregor17343172009-04-01 00:28:59 +00005302Sema::TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005303Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5304 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
5305 TypeTy *Ty) {
5306 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5307 !getLangOptions().CPlusPlus0x)
5308 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5309 << FixItHint::CreateRemoval(TypenameLoc);
5310
John McCall4e449832010-05-28 23:32:21 +00005311 TypeSourceInfo *InnerTSI = 0;
5312 QualType T = GetTypeFromParser(Ty, &InnerTSI);
Mike Stump1eb44332009-09-09 15:08:12 +00005313 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00005314 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
John McCall4e449832010-05-28 23:32:21 +00005315
5316 assert(isa<TemplateSpecializationType>(T) &&
5317 "Expected a template specialization type");
Douglas Gregor17343172009-04-01 00:28:59 +00005318
Douglas Gregor6946baf2009-09-02 13:05:45 +00005319 if (computeDeclContext(SS, false)) {
5320 // If we can compute a declaration context, then the "typename"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005321 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor6946baf2009-09-02 13:05:45 +00005322 // track of the nested-name-specifier.
John McCall4e449832010-05-28 23:32:21 +00005323
5324 // Push the inner type, preserving its source locations if possible.
5325 TypeLocBuilder Builder;
5326 if (InnerTSI)
5327 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5328 else
5329 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5330
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005331 T = Context.getElaboratedType(ETK_Typename, NNS, T);
John McCall4e449832010-05-28 23:32:21 +00005332 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5333 TL.setKeywordLoc(TypenameLoc);
5334 TL.setQualifierRange(SS.getRange());
5335
5336 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCall63b43852010-04-29 23:50:39 +00005337 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor6946baf2009-09-02 13:05:45 +00005338 }
Mike Stump1eb44332009-09-09 15:08:12 +00005339
John McCall33500952010-06-11 00:33:02 +00005340 // TODO: it's really silly that we make a template specialization
5341 // type earlier only to drop it again here.
5342 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5343 DependentTemplateName *DTN =
5344 TST->getTemplateName().getAsDependentTemplateName();
5345 assert(DTN && "dependent template has non-dependent name?");
5346 T = Context.getDependentTemplateSpecializationType(ETK_Typename, NNS,
5347 DTN->getIdentifier(),
5348 TST->getNumArgs(),
5349 TST->getArgs());
John McCall63b43852010-04-29 23:50:39 +00005350 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCall33500952010-06-11 00:33:02 +00005351 DependentTemplateSpecializationTypeLoc TL =
5352 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5353 if (InnerTSI) {
5354 TemplateSpecializationTypeLoc TSTL =
5355 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5356 TL.setLAngleLoc(TSTL.getLAngleLoc());
5357 TL.setRAngleLoc(TSTL.getRAngleLoc());
5358 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5359 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5360 } else {
5361 TL.initializeLocal(SourceLocation());
5362 }
John McCall4e449832010-05-28 23:32:21 +00005363 TL.setKeywordLoc(TypenameLoc);
5364 TL.setQualifierRange(SS.getRange());
John McCall63b43852010-04-29 23:50:39 +00005365 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00005366}
5367
Douglas Gregord57959a2009-03-27 23:10:48 +00005368/// \brief Build the type that describes a C++ typename specifier,
5369/// e.g., "typename T::type".
5370QualType
Douglas Gregor107de902010-04-24 15:35:55 +00005371Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5372 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005373 SourceLocation KeywordLoc, SourceRange NNSRange,
5374 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00005375 CXXScopeSpec SS;
5376 SS.setScopeRep(NNS);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005377 SS.setRange(NNSRange);
Douglas Gregord57959a2009-03-27 23:10:48 +00005378
John McCall77bb1aa2010-05-01 00:40:08 +00005379 DeclContext *Ctx = computeDeclContext(SS);
5380 if (!Ctx) {
5381 // If the nested-name-specifier is dependent and couldn't be
5382 // resolved to a type, build a typename type.
5383 assert(NNS->isDependent());
5384 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00005385 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005386
John McCall77bb1aa2010-05-01 00:40:08 +00005387 // If the nested-name-specifier refers to the current instantiation,
5388 // the "typename" keyword itself is superfluous. In C++03, the
5389 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5390 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregor732281d2010-06-14 22:07:54 +00005391 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00005392
John McCall77bb1aa2010-05-01 00:40:08 +00005393 if (RequireCompleteDeclContext(SS, Ctx))
5394 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00005395
5396 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005397 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005398 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005399 unsigned DiagID = 0;
5400 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005401 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005402 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005403 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005404 break;
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005405
5406 case LookupResult::NotFoundInCurrentInstantiation:
5407 // Okay, it's a member of an unknown instantiation.
Douglas Gregor107de902010-04-24 15:35:55 +00005408 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00005409
5410 case LookupResult::Found:
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005411 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005412 // We found a type. Build an ElaboratedType, since the
5413 // typename-specifier was just sugar.
5414 return Context.getElaboratedType(ETK_Typename, NNS,
5415 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00005416 }
5417
5418 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00005419 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00005420 break;
5421
John McCall7ba107a2009-11-18 02:36:19 +00005422 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005423 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00005424 return QualType();
5425
Douglas Gregord57959a2009-03-27 23:10:48 +00005426 case LookupResult::FoundOverloaded:
5427 DiagID = diag::err_typename_nested_not_type;
5428 Referenced = *Result.begin();
5429 break;
5430
John McCall6e247262009-10-10 05:48:19 +00005431 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00005432 return QualType();
5433 }
5434
5435 // If we get here, it's because name lookup did not find a
5436 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005437 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5438 IILoc);
5439 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00005440 if (Referenced)
5441 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5442 << Name;
5443 return QualType();
5444}
Douglas Gregor4a959d82009-08-06 16:20:37 +00005445
5446namespace {
5447 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00005448 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00005449 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00005450 SourceLocation Loc;
5451 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00005452
Douglas Gregor4a959d82009-08-06 16:20:37 +00005453 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00005454 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5455
Mike Stump1eb44332009-09-09 15:08:12 +00005456 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005457 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005458 DeclarationName Entity)
5459 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00005460 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00005461
5462 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00005463 /// transformed.
5464 ///
5465 /// For the purposes of type reconstruction, a type has already been
5466 /// transformed if it is NULL or if it is not dependent.
5467 bool AlreadyTransformed(QualType T) {
5468 return T.isNull() || !T->isDependentType();
5469 }
Mike Stump1eb44332009-09-09 15:08:12 +00005470
5471 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00005472 /// rebuilt.
5473 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00005474
Douglas Gregor4a959d82009-08-06 16:20:37 +00005475 /// \brief Returns the name of the entity whose type is being rebuilt.
5476 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00005477
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005478 /// \brief Sets the "base" location and entity when that
5479 /// information is known based on another transformation.
5480 void setBase(SourceLocation Loc, DeclarationName Entity) {
5481 this->Loc = Loc;
5482 this->Entity = Entity;
5483 }
5484
Douglas Gregor4a959d82009-08-06 16:20:37 +00005485 /// \brief Transforms an expression by returning the expression itself
5486 /// (an identity function).
5487 ///
5488 /// FIXME: This is completely unsafe; we will need to actually clone the
5489 /// expressions.
5490 Sema::OwningExprResult TransformExpr(Expr *E) {
Douglas Gregor895162d2010-04-30 18:55:50 +00005491 return getSema().Owned(E->Retain());
Douglas Gregor4a959d82009-08-06 16:20:37 +00005492 }
Douglas Gregor4a959d82009-08-06 16:20:37 +00005493 };
5494}
5495
Douglas Gregor4a959d82009-08-06 16:20:37 +00005496/// \brief Rebuilds a type within the context of the current instantiation.
5497///
Mike Stump1eb44332009-09-09 15:08:12 +00005498/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00005499/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00005500/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00005501/// partial specialization thereof). This routine will rebuild that type now
5502/// that we have entered the declarator's scope, which may produce different
5503/// canonical types, e.g.,
5504///
5505/// \code
5506/// template<typename T>
5507/// struct X {
5508/// typedef T* pointer;
5509/// pointer data();
5510/// };
5511///
5512/// template<typename T>
5513/// typename X<T>::pointer X<T>::data() { ... }
5514/// \endcode
5515///
Douglas Gregor4714c122010-03-31 17:34:00 +00005516/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005517/// since we do not know that we can look into X<T> when we parsed the type.
5518/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005519/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00005520/// as the canonical type of T*, allowing the return types of the out-of-line
5521/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00005522TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5523 SourceLocation Loc,
5524 DeclarationName Name) {
5525 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00005526 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00005527
Douglas Gregor4a959d82009-08-06 16:20:37 +00005528 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5529 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00005530}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005531
John McCall63b43852010-04-29 23:50:39 +00005532bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5533 if (SS.isInvalid()) return true;
John McCall31f17ec2010-04-27 00:57:59 +00005534
5535 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5536 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5537 DeclarationName());
5538 NestedNameSpecifier *Rebuilt =
5539 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall63b43852010-04-29 23:50:39 +00005540 if (!Rebuilt) return true;
5541
5542 SS.setScopeRep(Rebuilt);
5543 return false;
John McCall31f17ec2010-04-27 00:57:59 +00005544}
5545
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005546/// \brief Produces a formatted string that describes the binding of
5547/// template parameters to template arguments.
5548std::string
5549Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5550 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005551 // FIXME: For variadic templates, we'll need to get the structured list.
5552 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5553 Args.flat_size());
5554}
5555
5556std::string
5557Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5558 const TemplateArgument *Args,
5559 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005560 std::string Result;
5561
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005562 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005563 return Result;
5564
5565 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005566 if (I >= NumArgs)
5567 break;
5568
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005569 if (I == 0)
5570 Result += "[with ";
5571 else
5572 Result += ", ";
5573
5574 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5575 Result += Id->getName();
5576 } else {
5577 Result += '$';
5578 Result += llvm::utostr(I);
5579 }
5580
5581 Result += " = ";
5582
5583 switch (Args[I].getKind()) {
5584 case TemplateArgument::Null:
5585 Result += "<no value>";
5586 break;
5587
5588 case TemplateArgument::Type: {
5589 std::string TypeStr;
5590 Args[I].getAsType().getAsStringInternal(TypeStr,
5591 Context.PrintingPolicy);
5592 Result += TypeStr;
5593 break;
5594 }
5595
5596 case TemplateArgument::Declaration: {
5597 bool Unnamed = true;
5598 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5599 if (ND->getDeclName()) {
5600 Unnamed = false;
5601 Result += ND->getNameAsString();
5602 }
5603 }
5604
5605 if (Unnamed) {
5606 Result += "<anonymous>";
5607 }
5608 break;
5609 }
5610
Douglas Gregor788cd062009-11-11 01:00:40 +00005611 case TemplateArgument::Template: {
5612 std::string Str;
5613 llvm::raw_string_ostream OS(Str);
5614 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5615 Result += OS.str();
5616 break;
5617 }
5618
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005619 case TemplateArgument::Integral: {
5620 Result += Args[I].getAsIntegral()->toString(10);
5621 break;
5622 }
5623
5624 case TemplateArgument::Expression: {
Douglas Gregor77e2c672010-04-29 04:55:13 +00005625 // FIXME: This is non-optimal, since we're regurgitating the
5626 // expression we were given.
5627 std::string Str;
5628 {
5629 llvm::raw_string_ostream OS(Str);
5630 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5631 Context.PrintingPolicy);
5632 }
5633 Result += Str;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005634 break;
5635 }
5636
5637 case TemplateArgument::Pack:
5638 // FIXME: Format template argument packs
5639 Result += "<template argument pack>";
5640 break;
5641 }
5642 }
5643
5644 Result += ']';
5645 return Result;
5646}