blob: 3537b93e9083e40cd47e80ccaf92c75360571291 [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
John McCall2d887082010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Lookup.h"
John McCall5f1e0942010-08-24 08:50:51 +000014#include "clang/Sema/Scope.h"
John McCall7cd088e2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000016#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000017#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000019#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000020#include "clang/AST/ExprCXX.h"
John McCall92b7f702010-03-11 07:50:04 +000021#include "clang/AST/DeclFriend.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000022#include "clang/AST/DeclTemplate.h"
John McCall19510852010-08-20 18:27:03 +000023#include "clang/Sema/DeclSpec.h"
24#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000025#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000026#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000027#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000028using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000029using namespace sema;
Douglas Gregor72c3f312008-12-05 18:15:24 +000030
Douglas Gregor2dd078a2009-09-02 22:59:36 +000031/// \brief Determine whether the declaration found is acceptable as the name
32/// of a template and, if so, return that template declaration. Otherwise,
33/// returns NULL.
John McCallad00b772010-06-16 08:42:20 +000034static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
35 NamedDecl *Orig) {
36 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000037
Douglas Gregor2dd078a2009-09-02 22:59:36 +000038 if (isa<TemplateDecl>(D))
John McCallad00b772010-06-16 08:42:20 +000039 return Orig;
Mike Stump1eb44332009-09-09 15:08:12 +000040
Douglas Gregor2dd078a2009-09-02 22:59:36 +000041 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
42 // C++ [temp.local]p1:
43 // Like normal (non-template) classes, class templates have an
44 // injected-class-name (Clause 9). The injected-class-name
45 // can be used with or without a template-argument-list. When
46 // it is used without a template-argument-list, it is
47 // equivalent to the injected-class-name followed by the
48 // template-parameters of the class template enclosed in
49 // <>. When it is used with a template-argument-list, it
50 // refers to the specified class template specialization,
51 // which could be the current specialization or another
52 // specialization.
53 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000054 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000055 if (Record->getDescribedClassTemplate())
56 return Record->getDescribedClassTemplate();
57
58 if (ClassTemplateSpecializationDecl *Spec
59 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
60 return Spec->getSpecializedTemplate();
61 }
Mike Stump1eb44332009-09-09 15:08:12 +000062
Douglas Gregor2dd078a2009-09-02 22:59:36 +000063 return 0;
64 }
Mike Stump1eb44332009-09-09 15:08:12 +000065
Douglas Gregor2dd078a2009-09-02 22:59:36 +000066 return 0;
67}
68
John McCallf7a1a742009-11-24 19:00:30 +000069static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor01e56ae2010-04-12 20:54:26 +000070 // The set of class templates we've already seen.
71 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCallf7a1a742009-11-24 19:00:30 +000072 LookupResult::Filter filter = R.makeFilter();
73 while (filter.hasNext()) {
74 NamedDecl *Orig = filter.next();
John McCallad00b772010-06-16 08:42:20 +000075 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
John McCallf7a1a742009-11-24 19:00:30 +000076 if (!Repl)
77 filter.erase();
Douglas Gregor01e56ae2010-04-12 20:54:26 +000078 else if (Repl != Orig) {
79
80 // C++ [temp.local]p3:
81 // A lookup that finds an injected-class-name (10.2) can result in an
82 // ambiguity in certain cases (for example, if it is found in more than
83 // one base class). If all of the injected-class-names that are found
84 // refer to specializations of the same class template, and if the name
85 // is followed by a template-argument-list, the reference refers to the
86 // class template itself and not a specialization thereof, and is not
87 // ambiguous.
88 //
89 // FIXME: Will we eventually have to do the same for alias templates?
90 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
91 if (!ClassTemplates.insert(ClassTmpl)) {
92 filter.erase();
93 continue;
94 }
John McCall8ba66912010-08-13 07:02:08 +000095
96 // FIXME: we promote access to public here as a workaround to
97 // the fact that LookupResult doesn't let us remember that we
98 // found this template through a particular injected class name,
99 // which means we end up doing nasty things to the invariants.
100 // Pretending that access is public is *much* safer.
101 filter.replace(Repl, AS_public);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000102 }
John McCallf7a1a742009-11-24 19:00:30 +0000103 }
104 filter.done();
105}
106
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000107TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000108 CXXScopeSpec &SS,
Abramo Bagnara7c153532010-08-06 12:11:11 +0000109 bool hasTemplateKeyword,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000110 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +0000111 ParsedType ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000112 bool EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000113 TemplateTy &TemplateResult,
114 bool &MemberOfUnknownSpecialization) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000115 assert(getLangOptions().CPlusPlus && "No template names in C!");
116
Douglas Gregor014e88d2009-11-03 23:16:33 +0000117 DeclarationName TName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000118 MemberOfUnknownSpecialization = false;
Douglas Gregor014e88d2009-11-03 23:16:33 +0000119
120 switch (Name.getKind()) {
121 case UnqualifiedId::IK_Identifier:
122 TName = DeclarationName(Name.Identifier);
123 break;
124
125 case UnqualifiedId::IK_OperatorFunctionId:
126 TName = Context.DeclarationNames.getCXXOperatorName(
127 Name.OperatorFunctionId.Operator);
128 break;
129
Sean Hunte6252d12009-11-28 08:58:14 +0000130 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +0000131 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
132 break;
Sean Hunte6252d12009-11-28 08:58:14 +0000133
Douglas Gregor014e88d2009-11-03 23:16:33 +0000134 default:
135 return TNK_Non_template;
136 }
Mike Stump1eb44332009-09-09 15:08:12 +0000137
John McCallb3d87482010-08-24 05:47:05 +0000138 QualType ObjectType = ObjectTypePtr.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Douglas Gregorbfea2392009-12-31 08:11:17 +0000140 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
141 LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000142 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
143 MemberOfUnknownSpecialization);
John McCall67d22fb2010-08-28 20:17:00 +0000144 if (R.empty()) return TNK_Non_template;
145 if (R.isAmbiguous()) {
146 // Suppress diagnostics; we'll redo this lookup later.
John McCallb8592062010-08-13 02:23:42 +0000147 R.suppressDiagnostics();
John McCall67d22fb2010-08-28 20:17:00 +0000148
149 // FIXME: we might have ambiguous templates, in which case we
150 // should at least parse them properly!
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000151 return TNK_Non_template;
John McCallb8592062010-08-13 02:23:42 +0000152 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000153
John McCall0bd6feb2009-12-02 08:04:21 +0000154 TemplateName Template;
155 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000156
John McCall0bd6feb2009-12-02 08:04:21 +0000157 unsigned ResultCount = R.end() - R.begin();
158 if (ResultCount > 1) {
159 // We assume that we'll preserve the qualifier from a function
160 // template name in other ways.
161 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
162 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000163
164 // We'll do this lookup again later.
165 R.suppressDiagnostics();
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000166 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000167 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
168
169 if (SS.isSet() && !SS.isInvalid()) {
170 NestedNameSpecifier *Qualifier
171 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c153532010-08-06 12:11:11 +0000172 Template = Context.getQualifiedTemplateName(Qualifier,
173 hasTemplateKeyword, TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000174 } else {
175 Template = TemplateName(TD);
176 }
177
John McCallb8592062010-08-13 02:23:42 +0000178 if (isa<FunctionTemplateDecl>(TD)) {
John McCall0bd6feb2009-12-02 08:04:21 +0000179 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000180
181 // We'll do this lookup again later.
182 R.suppressDiagnostics();
183 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000184 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
185 TemplateKind = TNK_Type_template;
186 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000187 }
Mike Stump1eb44332009-09-09 15:08:12 +0000188
John McCall0bd6feb2009-12-02 08:04:21 +0000189 TemplateResult = TemplateTy::make(Template);
190 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000191}
192
Douglas Gregor84d0a192010-01-12 21:28:44 +0000193bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
194 SourceLocation IILoc,
195 Scope *S,
196 const CXXScopeSpec *SS,
197 TemplateTy &SuggestedTemplate,
198 TemplateNameKind &SuggestedKind) {
199 // We can't recover unless there's a dependent scope specifier preceding the
200 // template name.
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000201 // FIXME: Typo correction?
Douglas Gregor84d0a192010-01-12 21:28:44 +0000202 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
203 computeDeclContext(*SS))
204 return false;
205
206 // The code is missing a 'template' keyword prior to the dependent template
207 // name.
208 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
209 Diag(IILoc, diag::err_template_kw_missing)
210 << Qualifier << II.getName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000211 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor84d0a192010-01-12 21:28:44 +0000212 SuggestedTemplate
213 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
214 SuggestedKind = TNK_Dependent_template_name;
215 return true;
216}
217
John McCallf7a1a742009-11-24 19:00:30 +0000218void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000219 Scope *S, CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +0000220 QualType ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000221 bool EnteringContext,
222 bool &MemberOfUnknownSpecialization) {
John McCallf7a1a742009-11-24 19:00:30 +0000223 // Determine where to perform name lookup
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000224 MemberOfUnknownSpecialization = false;
John McCallf7a1a742009-11-24 19:00:30 +0000225 DeclContext *LookupCtx = 0;
226 bool isDependent = false;
227 if (!ObjectType.isNull()) {
228 // This nested-name-specifier occurs in a member access expression, e.g.,
229 // x->B::f, and we are looking into the type of the object.
230 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
231 LookupCtx = computeDeclContext(ObjectType);
232 isDependent = ObjectType->isDependentType();
233 assert((isDependent || !ObjectType->isIncompleteType()) &&
234 "Caller should have completed object type");
235 } else if (SS.isSet()) {
236 // This nested-name-specifier occurs after another nested-name-specifier,
237 // so long into the context associated with the prior nested-name-specifier.
238 LookupCtx = computeDeclContext(SS, EnteringContext);
239 isDependent = isDependentScopeSpecifier(SS);
240
241 // The declaration context must be complete.
John McCall77bb1aa2010-05-01 00:40:08 +0000242 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCallf7a1a742009-11-24 19:00:30 +0000243 return;
244 }
245
246 bool ObjectTypeSearchedInScope = false;
247 if (LookupCtx) {
248 // Perform "qualified" name lookup into the declaration context we
249 // computed, which is either the type of the base of a member access
250 // expression or the declaration context associated with a prior
251 // nested-name-specifier.
252 LookupQualifiedName(Found, LookupCtx);
253
254 if (!ObjectType.isNull() && Found.empty()) {
255 // C++ [basic.lookup.classref]p1:
256 // In a class member access expression (5.2.5), if the . or -> token is
257 // immediately followed by an identifier followed by a <, the
258 // identifier must be looked up to determine whether the < is the
259 // beginning of a template argument list (14.2) or a less-than operator.
260 // The identifier is first looked up in the class of the object
261 // expression. If the identifier is not found, it is then looked up in
262 // the context of the entire postfix-expression and shall name a class
263 // or function template.
John McCallf7a1a742009-11-24 19:00:30 +0000264 if (S) LookupName(Found, S);
265 ObjectTypeSearchedInScope = true;
266 }
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000267 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregor2e933882010-01-12 17:06:20 +0000268 // We cannot look into a dependent object type or nested nme
269 // specifier.
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000270 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000271 return;
272 } else {
273 // Perform unqualified name lookup in the current scope.
274 LookupName(Found, S);
275 }
276
Douglas Gregor2e933882010-01-12 17:06:20 +0000277 if (Found.empty() && !isDependent) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000278 // If we did not find any names, attempt to correct any typos.
279 DeclarationName Name = Found.getLookupName();
Douglas Gregoraaf87162010-04-14 20:04:41 +0000280 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000281 false, CTC_CXXCasts)) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000282 FilterAcceptableTemplateNames(Context, Found);
John McCallad00b772010-06-16 08:42:20 +0000283 if (!Found.empty()) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000284 if (LookupCtx)
285 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
286 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000287 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000288 Found.getLookupName().getAsString());
289 else
290 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
291 << Name << Found.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000292 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000293 Found.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000294 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
295 Diag(Template->getLocation(), diag::note_previous_decl)
296 << Template->getDeclName();
John McCallad00b772010-06-16 08:42:20 +0000297 }
Douglas Gregorbfea2392009-12-31 08:11:17 +0000298 } else {
299 Found.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000300 Found.setLookupName(Name);
Douglas Gregorbfea2392009-12-31 08:11:17 +0000301 }
302 }
303
John McCallf7a1a742009-11-24 19:00:30 +0000304 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000305 if (Found.empty()) {
306 if (isDependent)
307 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000308 return;
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000309 }
John McCallf7a1a742009-11-24 19:00:30 +0000310
311 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
312 // C++ [basic.lookup.classref]p1:
313 // [...] If the lookup in the class of the object expression finds a
314 // template, the name is also looked up in the context of the entire
315 // postfix-expression and [...]
316 //
317 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
318 LookupOrdinaryName);
319 LookupName(FoundOuter, S);
320 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000321
John McCallf7a1a742009-11-24 19:00:30 +0000322 if (FoundOuter.empty()) {
323 // - if the name is not found, the name found in the class of the
324 // object expression is used, otherwise
325 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
326 // - if the name is found in the context of the entire
327 // postfix-expression and does not name a class template, the name
328 // found in the class of the object expression is used, otherwise
John McCallad00b772010-06-16 08:42:20 +0000329 } else if (!Found.isSuppressingDiagnostics()) {
John McCallf7a1a742009-11-24 19:00:30 +0000330 // - if the name found is a class template, it must refer to the same
331 // entity as the one found in the class of the object expression,
332 // otherwise the program is ill-formed.
333 if (!Found.isSingleResult() ||
334 Found.getFoundDecl()->getCanonicalDecl()
335 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
336 Diag(Found.getNameLoc(),
Jeffrey Yasskin21d07e42010-06-05 01:39:57 +0000337 diag::ext_nested_name_member_ref_lookup_ambiguous)
338 << Found.getLookupName()
339 << ObjectType;
John McCallf7a1a742009-11-24 19:00:30 +0000340 Diag(Found.getRepresentativeDecl()->getLocation(),
341 diag::note_ambig_member_ref_object_type)
342 << ObjectType;
343 Diag(FoundOuter.getFoundDecl()->getLocation(),
344 diag::note_ambig_member_ref_scope);
345
346 // Recover by taking the template that we found in the object
347 // expression's type.
348 }
349 }
350 }
351}
352
John McCall2f841ba2009-12-02 03:53:29 +0000353/// ActOnDependentIdExpression - Handle a dependent id-expression that
354/// was just parsed. This is only possible with an explicit scope
355/// specifier naming a dependent type.
John McCall60d7b3a2010-08-24 06:29:42 +0000356ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000357Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000358 const DeclarationNameInfo &NameInfo,
John McCall2f841ba2009-12-02 03:53:29 +0000359 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000360 const TemplateArgumentListInfo *TemplateArgs) {
361 NestedNameSpecifier *Qualifier
362 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallea1471e2010-05-20 01:18:31 +0000363
364 DeclContext *DC = getFunctionLevelDeclContext();
John McCallf7a1a742009-11-24 19:00:30 +0000365
John McCall2f841ba2009-12-02 03:53:29 +0000366 if (!isAddressOfOperand &&
John McCallea1471e2010-05-20 01:18:31 +0000367 isa<CXXMethodDecl>(DC) &&
368 cast<CXXMethodDecl>(DC)->isInstance()) {
369 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2f841ba2009-12-02 03:53:29 +0000370
John McCallf7a1a742009-11-24 19:00:30 +0000371 // Since the 'this' expression is synthesized, we don't need to
372 // perform the double-lookup check.
373 NamedDecl *FirstQualifierInScope = 0;
374
John McCallaa81e162009-12-01 22:10:20 +0000375 return Owned(CXXDependentScopeMemberExpr::Create(Context,
376 /*This*/ 0, ThisType,
377 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000378 /*Op*/ SourceLocation(),
379 Qualifier, SS.getRange(),
380 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +0000381 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000382 TemplateArgs));
383 }
384
Abramo Bagnara25777432010-08-11 22:01:17 +0000385 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +0000386}
387
John McCall60d7b3a2010-08-24 06:29:42 +0000388ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000389Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000390 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000391 const TemplateArgumentListInfo *TemplateArgs) {
392 return Owned(DependentScopeDeclRefExpr::Create(Context,
393 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
394 SS.getRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +0000395 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000396 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000397}
398
Douglas Gregor72c3f312008-12-05 18:15:24 +0000399/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
400/// that the template parameter 'PrevDecl' is being shadowed by a new
401/// declaration at location Loc. Returns true to indicate that this is
402/// an error, and false otherwise.
403bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000404 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000405
406 // Microsoft Visual C++ permits template parameters to be shadowed.
407 if (getLangOptions().Microsoft)
408 return false;
409
410 // C++ [temp.local]p4:
411 // A template-parameter shall not be redeclared within its
412 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000413 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000414 << cast<NamedDecl>(PrevDecl)->getDeclName();
415 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
416 return true;
417}
418
Douglas Gregor2943aed2009-03-03 04:44:36 +0000419/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000420/// the parameter D to reference the templated declaration and return a pointer
421/// to the template declaration. Otherwise, do nothing to D and return null.
John McCalld226f652010-08-21 09:40:31 +0000422TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
423 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
424 D = Temp->getTemplatedDecl();
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000425 return Temp;
426 }
427 return 0;
428}
429
Douglas Gregor788cd062009-11-11 01:00:40 +0000430static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
431 const ParsedTemplateArgument &Arg) {
432
433 switch (Arg.getKind()) {
434 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000435 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000436 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
437 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000438 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000439 return TemplateArgumentLoc(TemplateArgument(T), DI);
440 }
441
442 case ParsedTemplateArgument::NonType: {
443 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
444 return TemplateArgumentLoc(TemplateArgument(E), E);
445 }
446
447 case ParsedTemplateArgument::Template: {
John McCall2b5289b2010-08-23 07:28:44 +0000448 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor788cd062009-11-11 01:00:40 +0000449 return TemplateArgumentLoc(TemplateArgument(Template),
450 Arg.getScopeSpec().getRange(),
451 Arg.getLocation());
452 }
453 }
454
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000455 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000456 return TemplateArgumentLoc();
457}
458
459/// \brief Translates template arguments as provided by the parser
460/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000461void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
462 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000463 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000464 TemplateArgs.addArgument(translateTemplateArgument(*this,
465 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000466}
467
Douglas Gregor72c3f312008-12-05 18:15:24 +0000468/// ActOnTypeParameter - Called when a C++ template type parameter
469/// (e.g., "typename T") has been parsed. Typename specifies whether
470/// the keyword "typename" was used to declare the type parameter
471/// (otherwise, "class" was used), and KeyLoc is the location of the
472/// "class" or "typename" keyword. ParamName is the name of the
473/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregorefed5c82010-06-16 15:23:05 +0000474/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000475/// If the type parameter has a default argument, it will be added
476/// later via ActOnTypeParameterDefault.
John McCalld226f652010-08-21 09:40:31 +0000477Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
478 SourceLocation EllipsisLoc,
479 SourceLocation KeyLoc,
480 IdentifierInfo *ParamName,
481 SourceLocation ParamNameLoc,
482 unsigned Depth, unsigned Position,
483 SourceLocation EqualLoc,
John McCallb3d87482010-08-24 05:47:05 +0000484 ParsedType DefaultArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000485 assert(S->isTemplateParamScope() &&
486 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000487 bool Invalid = false;
488
489 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000490 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000491 LookupOrdinaryName,
492 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000493 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000494 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000495 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000496 }
497
Douglas Gregorddc29e12009-02-06 22:42:48 +0000498 SourceLocation Loc = ParamNameLoc;
499 if (!ParamName)
500 Loc = KeyLoc;
501
Douglas Gregor72c3f312008-12-05 18:15:24 +0000502 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000503 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
504 Loc, Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000505 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000506 if (Invalid)
507 Param->setInvalidDecl();
508
509 if (ParamName) {
510 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000511 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000512 IdResolver.AddDecl(Param);
513 }
514
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000515 // Handle the default argument, if provided.
516 if (DefaultArg) {
517 TypeSourceInfo *DefaultTInfo;
518 GetTypeFromParser(DefaultArg, &DefaultTInfo);
519
520 assert(DefaultTInfo && "expected source information for type");
521
522 // C++0x [temp.param]p9:
523 // A default template-argument may be specified for any kind of
524 // template-parameter that is not a template parameter pack.
525 if (Ellipsis) {
526 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
John McCalld226f652010-08-21 09:40:31 +0000527 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000528 }
529
530 // Check the template argument itself.
531 if (CheckTemplateArgument(Param, DefaultTInfo)) {
532 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000533 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000534 }
535
536 Param->setDefaultArgument(DefaultTInfo, false);
537 }
538
John McCalld226f652010-08-21 09:40:31 +0000539 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000540}
541
Douglas Gregor2943aed2009-03-03 04:44:36 +0000542/// \brief Check that the type of a non-type template parameter is
543/// well-formed.
544///
545/// \returns the (possibly-promoted) parameter type if valid;
546/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000547QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000548Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora481ec42010-05-23 19:57:01 +0000549 // We don't allow variably-modified types as the type of non-type template
550 // parameters.
551 if (T->isVariablyModifiedType()) {
552 Diag(Loc, diag::err_variably_modified_nontype_template_param)
553 << T;
554 return QualType();
555 }
556
Douglas Gregor2943aed2009-03-03 04:44:36 +0000557 // C++ [temp.param]p4:
558 //
559 // A non-type template-parameter shall have one of the following
560 // (optionally cv-qualified) types:
561 //
562 // -- integral or enumeration type,
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000563 if (T->isIntegralOrEnumerationType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000564 // -- pointer to object or pointer to function,
Eli Friedman13578692010-08-05 02:49:48 +0000565 T->isPointerType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000566 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000567 T->isReferenceType() ||
568 // -- pointer to member.
569 T->isMemberPointerType() ||
570 // If T is a dependent type, we can't do the check now, so we
571 // assume that it is well-formed.
572 T->isDependentType())
573 return T;
574 // C++ [temp.param]p8:
575 //
576 // A non-type template-parameter of type "array of T" or
577 // "function returning T" is adjusted to be of type "pointer to
578 // T" or "pointer to function returning T", respectively.
579 else if (T->isArrayType())
580 // FIXME: Keep the type prior to promotion?
581 return Context.getArrayDecayedType(T);
582 else if (T->isFunctionType())
583 // FIXME: Keep the type prior to promotion?
584 return Context.getPointerType(T);
Douglas Gregor0fddb972010-05-22 16:17:30 +0000585
Douglas Gregor2943aed2009-03-03 04:44:36 +0000586 Diag(Loc, diag::err_template_nontype_parm_bad_type)
587 << T;
588
589 return QualType();
590}
591
John McCalld226f652010-08-21 09:40:31 +0000592Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
593 unsigned Depth,
594 unsigned Position,
595 SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000596 Expr *Default) {
John McCallbf1a0282010-06-04 23:28:52 +0000597 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
598 QualType T = TInfo->getType();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000599
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000600 assert(S->isTemplateParamScope() &&
601 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000602 bool Invalid = false;
603
604 IdentifierInfo *ParamName = D.getIdentifier();
605 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000606 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000607 LookupOrdinaryName,
608 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000609 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000610 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000611 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000612 }
613
Douglas Gregor2943aed2009-03-03 04:44:36 +0000614 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000615 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000616 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000617 Invalid = true;
618 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000619
Douglas Gregor72c3f312008-12-05 18:15:24 +0000620 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000621 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
622 D.getIdentifierLoc(),
John McCalla93c9342009-12-07 02:54:59 +0000623 Depth, Position, ParamName, T, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000624 if (Invalid)
625 Param->setInvalidDecl();
626
627 if (D.getIdentifier()) {
628 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000629 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000630 IdResolver.AddDecl(Param);
631 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000632
633 // Check the well-formedness of the default template argument, if provided.
John McCall9ae2f072010-08-23 23:25:46 +0000634 if (Default) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000635 TemplateArgument Converted;
636 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
637 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000638 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000639 }
640
John McCall9ae2f072010-08-23 23:25:46 +0000641 Param->setDefaultArgument(Default, false);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000642 }
643
John McCalld226f652010-08-21 09:40:31 +0000644 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000645}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000646
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000647/// ActOnTemplateTemplateParameter - Called when a C++ template template
648/// parameter (e.g. T in template <template <typename> class T> class array)
649/// has been parsed. S is the current scope.
John McCalld226f652010-08-21 09:40:31 +0000650Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
651 SourceLocation TmpLoc,
652 TemplateParamsTy *Params,
653 IdentifierInfo *Name,
654 SourceLocation NameLoc,
655 unsigned Depth,
656 unsigned Position,
657 SourceLocation EqualLoc,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000658 const ParsedTemplateArgument &Default) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000659 assert(S->isTemplateParamScope() &&
660 "Template template parameter not in template parameter scope!");
661
662 // Construct the parameter object.
663 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000664 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000665 NameLoc.isInvalid()? TmpLoc : NameLoc,
666 Depth, Position, Name,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000667 (TemplateParameterList*)Params);
668
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000669 // If the template template parameter has a name, then link the identifier
670 // into the scope and lookup mechanisms.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000671 if (Name) {
John McCalld226f652010-08-21 09:40:31 +0000672 S->AddDecl(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000673 IdResolver.AddDecl(Param);
674 }
675
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000676 if (!Default.isInvalid()) {
677 // Check only that we have a template template argument. We don't want to
678 // try to check well-formedness now, because our template template parameter
679 // might have dependent types in its template parameters, which we wouldn't
680 // be able to match now.
681 //
682 // If none of the template template parameter's template arguments mention
683 // other template parameters, we could actually perform more checking here.
684 // However, it isn't worth doing.
685 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
686 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
687 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
688 << DefaultArg.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +0000689 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000690 }
691
692 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000693 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000694
John McCalld226f652010-08-21 09:40:31 +0000695 return Param;
Douglas Gregord684b002009-02-10 19:49:53 +0000696}
697
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000698/// ActOnTemplateParameterList - Builds a TemplateParameterList that
699/// contains the template parameters in Params/NumParams.
700Sema::TemplateParamsTy *
701Sema::ActOnTemplateParameterList(unsigned Depth,
702 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000703 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000704 SourceLocation LAngleLoc,
John McCalld226f652010-08-21 09:40:31 +0000705 Decl **Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000706 SourceLocation RAngleLoc) {
707 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000708 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000709
Douglas Gregorddc29e12009-02-06 22:42:48 +0000710 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000711 (NamedDecl**)Params, NumParams,
712 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000713}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000714
John McCallb6217662010-03-15 10:12:16 +0000715static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
716 if (SS.isSet())
717 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
718 SS.getRange());
719}
720
John McCallf312b1e2010-08-26 23:41:50 +0000721DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000722Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000723 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000724 IdentifierInfo *Name, SourceLocation NameLoc,
725 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000726 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000727 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000728 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000729 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000730 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000731 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000732
733 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000734 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000735 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000736
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000737 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
738 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000739
740 // There is no such thing as an unnamed class template.
741 if (!Name) {
742 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000743 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000744 }
745
746 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000747 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000748 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000749 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000750 if (SS.isNotEmpty() && !SS.isInvalid()) {
751 SemanticContext = computeDeclContext(SS, true);
752 if (!SemanticContext) {
753 // FIXME: Produce a reasonable diagnostic here
754 return true;
755 }
Mike Stump1eb44332009-09-09 15:08:12 +0000756
John McCall77bb1aa2010-05-01 00:40:08 +0000757 if (RequireCompleteDeclContext(SS, SemanticContext))
758 return true;
759
John McCalla24dc2e2009-11-17 02:14:36 +0000760 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000761 } else {
762 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000763 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000764 }
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Douglas Gregor57265e32010-04-12 16:00:01 +0000766 if (Previous.isAmbiguous())
767 return true;
768
Douglas Gregorddc29e12009-02-06 22:42:48 +0000769 NamedDecl *PrevDecl = 0;
770 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000771 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000772
Douglas Gregorddc29e12009-02-06 22:42:48 +0000773 // If there is a previous declaration with the same name, check
774 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000775 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000776 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000777
778 // We may have found the injected-class-name of a class template,
779 // class template partial specialization, or class template specialization.
780 // In these cases, grab the template that is being defined or specialized.
781 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
782 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
783 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
784 PrevClassTemplate
785 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
786 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
787 PrevClassTemplate
788 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
789 ->getSpecializedTemplate();
790 }
791 }
792
John McCall65c49462009-12-18 11:25:59 +0000793 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000794 // C++ [namespace.memdef]p3:
795 // [...] When looking for a prior declaration of a class or a function
796 // declared as a friend, and when the name of the friend class or
797 // function is neither a qualified name nor a template-id, scopes outside
798 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000799 if (!SS.isSet()) {
800 DeclContext *OutermostContext = CurContext;
801 while (!OutermostContext->isFileContext())
802 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000803
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000804 if (PrevDecl &&
805 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
806 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
807 SemanticContext = PrevDecl->getDeclContext();
808 } else {
809 // Declarations in outer scopes don't matter. However, the outermost
810 // context we computed is the semantic context for our new
811 // declaration.
812 PrevDecl = PrevClassTemplate = 0;
813 SemanticContext = OutermostContext;
814 }
John McCalle129d442009-12-17 23:21:11 +0000815 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000816
John McCalle129d442009-12-17 23:21:11 +0000817 if (CurContext->isDependentContext()) {
818 // If this is a dependent context, we don't want to link the friend
819 // class template to the template in scope, because that would perform
820 // checking of the template parameter lists that can't be performed
821 // until the outer context is instantiated.
822 PrevDecl = PrevClassTemplate = 0;
823 }
824 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
825 PrevDecl = PrevClassTemplate = 0;
Douglas Gregor57265e32010-04-12 16:00:01 +0000826
Douglas Gregorddc29e12009-02-06 22:42:48 +0000827 if (PrevClassTemplate) {
828 // Ensure that the template parameter lists are compatible.
829 if (!TemplateParameterListsAreEqual(TemplateParams,
830 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000831 /*Complain=*/true,
832 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000833 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000834
835 // C++ [temp.class]p4:
836 // In a redeclaration, partial specialization, explicit
837 // specialization or explicit instantiation of a class template,
838 // the class-key shall agree in kind with the original class
839 // template declaration (7.1.5.3).
840 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000841 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000842 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000843 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000844 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000845 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000846 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000847 }
848
Douglas Gregorddc29e12009-02-06 22:42:48 +0000849 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000850 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000851 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000852 Diag(NameLoc, diag::err_redefinition) << Name;
853 Diag(Def->getLocation(), diag::note_previous_definition);
854 // FIXME: Would it make sense to try to "forget" the previous
855 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000856 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000857 }
858 }
859 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
860 // Maybe we will complain about the shadowed template parameter.
861 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
862 // Just pretend that we didn't see the previous declaration.
863 PrevDecl = 0;
864 } else if (PrevDecl) {
865 // C++ [temp]p5:
866 // A class template shall not have the same name as any other
867 // template, class, function, object, enumeration, enumerator,
868 // namespace, or type in the same scope (3.3), except as specified
869 // in (14.5.4).
870 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
871 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000872 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000873 }
874
Douglas Gregord684b002009-02-10 19:49:53 +0000875 // Check the template parameter list of this declaration, possibly
876 // merging in the template parameter list from the previous class
877 // template declaration.
878 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000879 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
880 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000881 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Douglas Gregor57265e32010-04-12 16:00:01 +0000883 if (SS.isSet()) {
884 // If the name of the template was qualified, we must be defining the
885 // template out-of-line.
886 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
887 !(TUK == TUK_Friend && CurContext->isDependentContext()))
888 Diag(NameLoc, diag::err_member_def_does_not_match)
889 << Name << SemanticContext << SS.getRange();
890 }
891
Mike Stump1eb44332009-09-09 15:08:12 +0000892 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000893 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000894 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000895 PrevClassTemplate->getTemplatedDecl() : 0,
896 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000897 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000898
899 ClassTemplateDecl *NewTemplate
900 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
901 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000902 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000903 NewClass->setDescribedClassTemplate(NewTemplate);
904
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000905 // Build the type for the class template declaration now.
Douglas Gregor24bae922010-07-08 18:37:38 +0000906 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCall3cb0ebd2010-03-10 03:28:59 +0000907 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000908 assert(T->isDependentType() && "Class template type is not dependent?");
909 (void)T;
910
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000911 // If we are providing an explicit specialization of a member that is a
912 // class template, make a note of that.
913 if (PrevClassTemplate &&
914 PrevClassTemplate->getInstantiatedFromMemberTemplate())
915 PrevClassTemplate->setMemberSpecialization();
916
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000917 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000918 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000919 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Douglas Gregorddc29e12009-02-06 22:42:48 +0000921 // Set the lexical context of these templates
922 NewClass->setLexicalDeclContext(CurContext);
923 NewTemplate->setLexicalDeclContext(CurContext);
924
John McCall0f434ec2009-07-31 02:45:11 +0000925 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000926 NewClass->startDefinition();
927
928 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000929 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000930
John McCall05b23ea2009-09-14 21:59:20 +0000931 if (TUK != TUK_Friend)
932 PushOnScopeChains(NewTemplate, S);
933 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000934 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000935 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000936 NewClass->setAccess(PrevClassTemplate->getAccess());
937 }
John McCall05b23ea2009-09-14 21:59:20 +0000938
Douglas Gregord85bea22009-09-26 06:47:28 +0000939 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
940 PrevClassTemplate != NULL);
941
John McCall05b23ea2009-09-14 21:59:20 +0000942 // Friend templates are visible in fairly strange ways.
943 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +0000944 DeclContext *DC = SemanticContext->getRedeclContext();
John McCall05b23ea2009-09-14 21:59:20 +0000945 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
946 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
947 PushOnScopeChains(NewTemplate, EnclosingScope,
948 /* AddToContext = */ false);
949 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000950
951 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
952 NewClass->getLocation(),
953 NewTemplate,
954 /*FIXME:*/NewClass->getLocation());
955 Friend->setAccess(AS_public);
956 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000957 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000958
Douglas Gregord684b002009-02-10 19:49:53 +0000959 if (Invalid) {
960 NewTemplate->setInvalidDecl();
961 NewClass->setInvalidDecl();
962 }
John McCalld226f652010-08-21 09:40:31 +0000963 return NewTemplate;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000964}
965
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000966/// \brief Diagnose the presence of a default template argument on a
967/// template parameter, which is ill-formed in certain contexts.
968///
969/// \returns true if the default template argument should be dropped.
970static bool DiagnoseDefaultTemplateArgument(Sema &S,
971 Sema::TemplateParamListContext TPC,
972 SourceLocation ParamLoc,
973 SourceRange DefArgRange) {
974 switch (TPC) {
975 case Sema::TPC_ClassTemplate:
976 return false;
977
978 case Sema::TPC_FunctionTemplate:
979 // C++ [temp.param]p9:
980 // A default template-argument shall not be specified in a
981 // function template declaration or a function template
982 // definition [...]
983 // (This sentence is not in C++0x, per DR226).
984 if (!S.getLangOptions().CPlusPlus0x)
985 S.Diag(ParamLoc,
986 diag::err_template_parameter_default_in_function_template)
987 << DefArgRange;
988 return false;
989
990 case Sema::TPC_ClassTemplateMember:
991 // C++0x [temp.param]p9:
992 // A default template-argument shall not be specified in the
993 // template-parameter-lists of the definition of a member of a
994 // class template that appears outside of the member's class.
995 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
996 << DefArgRange;
997 return true;
998
999 case Sema::TPC_FriendFunctionTemplate:
1000 // C++ [temp.param]p9:
1001 // A default template-argument shall not be specified in a
1002 // friend template declaration.
1003 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1004 << DefArgRange;
1005 return true;
1006
1007 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1008 // for friend function templates if there is only a single
1009 // declaration (and it is a definition). Strange!
1010 }
1011
1012 return false;
1013}
1014
Douglas Gregord684b002009-02-10 19:49:53 +00001015/// \brief Checks the validity of a template parameter list, possibly
1016/// considering the template parameter list from a previous
1017/// declaration.
1018///
1019/// If an "old" template parameter list is provided, it must be
1020/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1021/// template parameter list.
1022///
1023/// \param NewParams Template parameter list for a new template
1024/// declaration. This template parameter list will be updated with any
1025/// default arguments that are carried through from the previous
1026/// template parameter list.
1027///
1028/// \param OldParams If provided, template parameter list from a
1029/// previous declaration of the same template. Default template
1030/// arguments will be merged from the old template parameter list to
1031/// the new template parameter list.
1032///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001033/// \param TPC Describes the context in which we are checking the given
1034/// template parameter list.
1035///
Douglas Gregord684b002009-02-10 19:49:53 +00001036/// \returns true if an error occurred, false otherwise.
1037bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001038 TemplateParameterList *OldParams,
1039 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001040 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Douglas Gregord684b002009-02-10 19:49:53 +00001042 // C++ [temp.param]p10:
1043 // The set of default template-arguments available for use with a
1044 // template declaration or definition is obtained by merging the
1045 // default arguments from the definition (if in scope) and all
1046 // declarations in scope in the same way default function
1047 // arguments are (8.3.6).
1048 bool SawDefaultArgument = false;
1049 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001050
Anders Carlsson49d25572009-06-12 23:20:15 +00001051 bool SawParameterPack = false;
1052 SourceLocation ParameterPackLoc;
1053
Mike Stump1a35fde2009-02-11 23:03:27 +00001054 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001055 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001056 if (OldParams)
1057 OldParam = OldParams->begin();
1058
1059 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1060 NewParamEnd = NewParams->end();
1061 NewParam != NewParamEnd; ++NewParam) {
1062 // Variables used to diagnose redundant default arguments
1063 bool RedundantDefaultArg = false;
1064 SourceLocation OldDefaultLoc;
1065 SourceLocation NewDefaultLoc;
1066
1067 // Variables used to diagnose missing default arguments
1068 bool MissingDefaultArg = false;
1069
Anders Carlsson49d25572009-06-12 23:20:15 +00001070 // C++0x [temp.param]p11:
1071 // If a template parameter of a class template is a template parameter pack,
1072 // it must be the last template parameter.
1073 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001074 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001075 diag::err_template_param_pack_must_be_last_template_parameter);
1076 Invalid = true;
1077 }
1078
Douglas Gregord684b002009-02-10 19:49:53 +00001079 if (TemplateTypeParmDecl *NewTypeParm
1080 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001081 // Check the presence of a default argument here.
1082 if (NewTypeParm->hasDefaultArgument() &&
1083 DiagnoseDefaultTemplateArgument(*this, TPC,
1084 NewTypeParm->getLocation(),
1085 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001086 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001087 NewTypeParm->removeDefaultArgument();
1088
1089 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001090 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001091 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Anders Carlsson49d25572009-06-12 23:20:15 +00001093 if (NewTypeParm->isParameterPack()) {
1094 assert(!NewTypeParm->hasDefaultArgument() &&
1095 "Parameter packs can't have a default argument!");
1096 SawParameterPack = true;
1097 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001098 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001099 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001100 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1101 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1102 SawDefaultArgument = true;
1103 RedundantDefaultArg = true;
1104 PreviousDefaultArgLoc = NewDefaultLoc;
1105 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1106 // Merge the default argument from the old declaration to the
1107 // new declaration.
1108 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001109 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001110 true);
1111 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1112 } else if (NewTypeParm->hasDefaultArgument()) {
1113 SawDefaultArgument = true;
1114 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1115 } else if (SawDefaultArgument)
1116 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001117 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001118 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001119 // Check the presence of a default argument here.
1120 if (NewNonTypeParm->hasDefaultArgument() &&
1121 DiagnoseDefaultTemplateArgument(*this, TPC,
1122 NewNonTypeParm->getLocation(),
1123 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001124 NewNonTypeParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001125 }
1126
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001127 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001128 NonTypeTemplateParmDecl *OldNonTypeParm
1129 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001130 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001131 NewNonTypeParm->hasDefaultArgument()) {
1132 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1133 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1134 SawDefaultArgument = true;
1135 RedundantDefaultArg = true;
1136 PreviousDefaultArgLoc = NewDefaultLoc;
1137 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1138 // Merge the default argument from the old declaration to the
1139 // new declaration.
1140 SawDefaultArgument = true;
1141 // FIXME: We need to create a new kind of "default argument"
1142 // expression that points to a previous template template
1143 // parameter.
1144 NewNonTypeParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001145 OldNonTypeParm->getDefaultArgument(),
1146 /*Inherited=*/ true);
Douglas Gregord684b002009-02-10 19:49:53 +00001147 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1148 } else if (NewNonTypeParm->hasDefaultArgument()) {
1149 SawDefaultArgument = true;
1150 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1151 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001152 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001153 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001154 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001155 TemplateTemplateParmDecl *NewTemplateParm
1156 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001157 if (NewTemplateParm->hasDefaultArgument() &&
1158 DiagnoseDefaultTemplateArgument(*this, TPC,
1159 NewTemplateParm->getLocation(),
1160 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001161 NewTemplateParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001162
1163 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001164 TemplateTemplateParmDecl *OldTemplateParm
1165 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001166 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001167 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001168 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1169 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001170 SawDefaultArgument = true;
1171 RedundantDefaultArg = true;
1172 PreviousDefaultArgLoc = NewDefaultLoc;
1173 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1174 // Merge the default argument from the old declaration to the
1175 // new declaration.
1176 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001177 // FIXME: We need to create a new kind of "default argument" expression
1178 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001179 NewTemplateParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001180 OldTemplateParm->getDefaultArgument(),
1181 /*Inherited=*/ true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001182 PreviousDefaultArgLoc
1183 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001184 } else if (NewTemplateParm->hasDefaultArgument()) {
1185 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001186 PreviousDefaultArgLoc
1187 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001188 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001189 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001190 }
1191
1192 if (RedundantDefaultArg) {
1193 // C++ [temp.param]p12:
1194 // A template-parameter shall not be given default arguments
1195 // by two different declarations in the same scope.
1196 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1197 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1198 Invalid = true;
1199 } else if (MissingDefaultArg) {
1200 // C++ [temp.param]p11:
1201 // If a template-parameter has a default template-argument,
1202 // all subsequent template-parameters shall have a default
1203 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001204 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001205 diag::err_template_param_default_arg_missing);
1206 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1207 Invalid = true;
1208 }
1209
1210 // If we have an old template parameter list that we're merging
1211 // in, move on to the next parameter.
1212 if (OldParams)
1213 ++OldParam;
1214 }
1215
1216 return Invalid;
1217}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001218
Mike Stump1eb44332009-09-09 15:08:12 +00001219/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001220/// specifier, returning the template parameter list that applies to the
1221/// name.
1222///
1223/// \param DeclStartLoc the start of the declaration that has a scope
1224/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001225///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001226/// \param SS the scope specifier that will be matched to the given template
1227/// parameter lists. This scope specifier precedes a qualified name that is
1228/// being declared.
1229///
1230/// \param ParamLists the template parameter lists, from the outermost to the
1231/// innermost template parameter lists.
1232///
1233/// \param NumParamLists the number of template parameter lists in ParamLists.
1234///
John McCall77e8b112010-04-13 20:37:33 +00001235/// \param IsFriend Whether to apply the slightly different rules for
1236/// matching template parameters to scope specifiers in friend
1237/// declarations.
1238///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001239/// \param IsExplicitSpecialization will be set true if the entity being
1240/// declared is an explicit specialization, false otherwise.
1241///
Mike Stump1eb44332009-09-09 15:08:12 +00001242/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001243/// name that is preceded by the scope specifier @p SS. This template
1244/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001245/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001246/// template specialization), or may be NULL (if we were's declaring isn't
1247/// itself a template).
1248TemplateParameterList *
1249Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1250 const CXXScopeSpec &SS,
1251 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001252 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001253 bool IsFriend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001254 bool &IsExplicitSpecialization,
1255 bool &Invalid) {
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001256 IsExplicitSpecialization = false;
1257
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001258 // Find the template-ids that occur within the nested-name-specifier. These
1259 // template-ids will match up with the template parameter lists.
1260 llvm::SmallVector<const TemplateSpecializationType *, 4>
1261 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001262 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1263 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001264 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1265 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001266 const Type *T = NNS->getAsType();
1267 if (!T) break;
1268
1269 // C++0x [temp.expl.spec]p17:
1270 // A member or a member template may be nested within many
1271 // enclosing class templates. In an explicit specialization for
1272 // such a member, the member declaration shall be preceded by a
1273 // template<> for each enclosing class template that is
1274 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001275 //
1276 // Following the existing practice of GNU and EDG, we allow a typedef of a
1277 // template specialization type.
1278 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1279 T = TT->LookThroughTypedefs().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001280
Mike Stump1eb44332009-09-09 15:08:12 +00001281 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001282 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001283 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1284 if (!Template)
1285 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Ted Kremenek6217b802009-07-29 21:53:49 +00001287 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001288 ClassTemplateSpecializationDecl *SpecDecl
1289 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1290 // If the nested name specifier refers to an explicit specialization,
1291 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001292 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1293 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001294 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001295 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001296 }
Mike Stump1eb44332009-09-09 15:08:12 +00001297
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001298 TemplateIdsInSpecifier.push_back(SpecType);
1299 }
1300 }
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001302 // Reverse the list of template-ids in the scope specifier, so that we can
1303 // more easily match up the template-ids and the template parameter lists.
1304 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001305
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001306 SourceLocation FirstTemplateLoc = DeclStartLoc;
1307 if (NumParamLists)
1308 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001310 // Match the template-ids found in the specifier to the template parameter
1311 // lists.
1312 unsigned Idx = 0;
1313 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1314 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001315 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1316 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001317 if (Idx >= NumParamLists) {
1318 // We have a template-id without a corresponding template parameter
1319 // list.
John McCall77e8b112010-04-13 20:37:33 +00001320
1321 // ...which is fine if this is a friend declaration.
1322 if (IsFriend) {
1323 IsExplicitSpecialization = true;
1324 break;
1325 }
1326
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001327 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001328 // FIXME: the location information here isn't great.
1329 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001330 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001331 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001332 << SS.getRange();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001333 Invalid = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001334 } else {
1335 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1336 << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00001337 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001338 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001339 }
1340 return 0;
1341 }
Mike Stump1eb44332009-09-09 15:08:12 +00001342
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001343 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001344 if (DependentTemplateId) {
John McCall31f17ec2010-04-27 00:57:59 +00001345 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00001346
John McCall31f17ec2010-04-27 00:57:59 +00001347 // Are there cases in (e.g.) friends where this won't match?
1348 if (const InjectedClassNameType *Injected
1349 = TemplateId->getAs<InjectedClassNameType>()) {
1350 CXXRecordDecl *Record = Injected->getDecl();
1351 if (ClassTemplatePartialSpecializationDecl *Partial =
1352 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1353 ExpectedTemplateParams = Partial->getTemplateParameters();
1354 else
1355 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1356 ->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001357 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001358
John McCall31f17ec2010-04-27 00:57:59 +00001359 if (ExpectedTemplateParams)
1360 TemplateParameterListsAreEqual(ParamLists[Idx],
1361 ExpectedTemplateParams,
1362 true, TPL_TemplateMatch);
1363
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001364 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregorb88e8882009-07-30 17:40:51 +00001365 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001366 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001367 diag::err_template_param_list_matches_nontemplate)
1368 << TemplateId
1369 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001370 else
1371 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001372 }
Mike Stump1eb44332009-09-09 15:08:12 +00001373
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001374 // If there were at least as many template-ids as there were template
1375 // parameter lists, then there are no template parameter lists remaining for
1376 // the declaration itself.
Douglas Gregor72c4c152010-08-20 03:26:10 +00001377 if (Idx >= NumParamLists)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001378 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001379
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001380 // If there were too many template parameter lists, complain about that now.
1381 if (Idx != NumParamLists - 1) {
1382 while (Idx < NumParamLists - 1) {
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001383 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001384 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001385 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1386 : diag::err_template_spec_extra_headers)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001387 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1388 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001389
1390 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1391 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1392 diag::note_explicit_template_spec_does_not_need_header)
1393 << ExplicitSpecializationsInSpecifier.back();
1394 ExplicitSpecializationsInSpecifier.pop_back();
1395 }
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001396
1397 // We have a template parameter list with no corresponding scope, which
1398 // means that the resulting template declaration can't be instantiated
1399 // properly (we'll end up with dependent nodes when we shouldn't).
1400 if (!isExplicitSpecHeader)
1401 Invalid = true;
1402
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001403 ++Idx;
1404 }
1405 }
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001407 // Return the last template parameter list, which corresponds to the
1408 // entity being declared.
1409 return ParamLists[NumParamLists - 1];
1410}
1411
Douglas Gregor7532dc62009-03-30 22:58:21 +00001412QualType Sema::CheckTemplateIdType(TemplateName Name,
1413 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001414 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001415 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001416 if (!Template) {
1417 // The template name does not resolve to a template, so we just
1418 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001419 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001420 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001421
Douglas Gregor40808ce2009-03-09 23:48:35 +00001422 // Check that the template argument list is well-formed for this
1423 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001424 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCalld5532b62009-11-23 01:53:49 +00001425 TemplateArgs.size());
1426 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001427 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001428 return QualType();
1429
Mike Stump1eb44332009-09-09 15:08:12 +00001430 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001431 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001432 "Converted template argument list is too short!");
1433
1434 QualType CanonType;
1435
Douglas Gregorcaddba02009-11-12 18:38:13 +00001436 if (Name.isDependent() ||
1437 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001438 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001439 // This class template specialization is a dependent
1440 // type. Therefore, its canonical type is another class template
1441 // specialization type that contains all of the converted
1442 // arguments in canonical form. This ensures that, e.g., A<T> and
1443 // A<T, T> have identical types when A is declared as:
1444 //
1445 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001446 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001447 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001448 Converted.getFlatArguments(),
1449 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001450
Douglas Gregor1275ae02009-07-28 23:00:59 +00001451 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001452 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001453 // In the future, we need to teach getTemplateSpecializationType to only
1454 // build the canonical type and return that to us.
1455 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001456
1457 // This might work out to be a current instantiation, in which
1458 // case the canonical type needs to be the InjectedClassNameType.
1459 //
1460 // TODO: in theory this could be a simple hashtable lookup; most
1461 // changes to CurContext don't change the set of current
1462 // instantiations.
1463 if (isa<ClassTemplateDecl>(Template)) {
1464 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1465 // If we get out to a namespace, we're done.
1466 if (Ctx->isFileContext()) break;
1467
1468 // If this isn't a record, keep looking.
1469 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1470 if (!Record) continue;
1471
1472 // Look for one of the two cases with InjectedClassNameTypes
1473 // and check whether it's the same template.
1474 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1475 !Record->getDescribedClassTemplate())
1476 continue;
1477
1478 // Fetch the injected class name type and check whether its
1479 // injected type is equal to the type we just built.
1480 QualType ICNT = Context.getTypeDeclType(Record);
1481 QualType Injected = cast<InjectedClassNameType>(ICNT)
1482 ->getInjectedSpecializationType();
1483
1484 if (CanonType != Injected->getCanonicalTypeInternal())
1485 continue;
1486
1487 // If so, the canonical type of this TST is the injected
1488 // class name type of the record we just found.
1489 assert(ICNT.isCanonical());
1490 CanonType = ICNT;
John McCall31f17ec2010-04-27 00:57:59 +00001491 break;
1492 }
1493 }
Mike Stump1eb44332009-09-09 15:08:12 +00001494 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001495 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001496 // Find the class template specialization declaration that
1497 // corresponds to these arguments.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001498 void *InsertPos = 0;
1499 ClassTemplateSpecializationDecl *Decl
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001500 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
1501 Converted.flatSize(), InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001502 if (!Decl) {
1503 // This is the first time we have referenced this class template
1504 // specialization. Create the canonical declaration and add it to
1505 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001506 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00001507 ClassTemplate->getTemplatedDecl()->getTagKind(),
1508 ClassTemplate->getDeclContext(),
1509 ClassTemplate->getLocation(),
1510 ClassTemplate,
1511 Converted, 0);
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001512 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001513 Decl->setLexicalDeclContext(CurContext);
1514 }
1515
1516 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001517 assert(isa<RecordType>(CanonType) &&
1518 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001519 }
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Douglas Gregor40808ce2009-03-09 23:48:35 +00001521 // Build the fully-sugared type for this class template
1522 // specialization, which refers back to the class template
1523 // specialization we created or found.
John McCall71d74bc2010-06-13 09:25:03 +00001524 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001525}
1526
John McCallf312b1e2010-08-26 23:41:50 +00001527TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001528Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001529 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001530 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001531 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001532 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001533
Douglas Gregor40808ce2009-03-09 23:48:35 +00001534 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001535 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001536 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001537
John McCalld5532b62009-11-23 01:53:49 +00001538 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001539 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001540
1541 if (Result.isNull())
1542 return true;
1543
John McCalla93c9342009-12-07 02:54:59 +00001544 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001545 TemplateSpecializationTypeLoc TL
1546 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1547 TL.setTemplateNameLoc(TemplateLoc);
1548 TL.setLAngleLoc(LAngleLoc);
1549 TL.setRAngleLoc(RAngleLoc);
1550 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1551 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1552
John McCallb3d87482010-08-24 05:47:05 +00001553 return CreateParsedType(Result, DI);
John McCall6b2becf2009-09-08 17:47:29 +00001554}
John McCallf1bbbb42009-09-04 01:14:41 +00001555
John McCallf312b1e2010-08-26 23:41:50 +00001556TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1557 TagUseKind TUK,
1558 TypeSpecifierType TagSpec,
1559 SourceLocation TagLoc) {
John McCall6b2becf2009-09-08 17:47:29 +00001560 if (TypeResult.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001561 return ::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001562
John McCall833ca992009-10-29 08:12:44 +00001563 // FIXME: preserve source info, ideally without copying the DI.
John McCalla93c9342009-12-07 02:54:59 +00001564 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001565 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001566
John McCall6b2becf2009-09-08 17:47:29 +00001567 // Verify the tag specifier.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001568 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001569
John McCall6b2becf2009-09-08 17:47:29 +00001570 if (const RecordType *RT = Type->getAs<RecordType>()) {
1571 RecordDecl *D = RT->getDecl();
1572
1573 IdentifierInfo *Id = D->getIdentifier();
1574 assert(Id && "templated class must have an identifier");
1575
1576 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1577 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001578 << Type
Douglas Gregor849b2432010-03-31 17:46:05 +00001579 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001580 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001581 }
1582 }
1583
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001584 ElaboratedTypeKeyword Keyword
1585 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1586 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCall6b2becf2009-09-08 17:47:29 +00001587
John McCallb3d87482010-08-24 05:47:05 +00001588 return ParsedType::make(ElabType);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001589}
1590
John McCall60d7b3a2010-08-24 06:29:42 +00001591ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001592 LookupResult &R,
1593 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001594 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001595 // FIXME: Can we do any checking at this point? I guess we could check the
1596 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001597 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001598 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001599
1600 // These should be filtered out by our callers.
1601 assert(!R.empty() && "empty lookup results when building templateid");
1602 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1603
1604 NestedNameSpecifier *Qualifier = 0;
1605 SourceRange QualifierRange;
1606 if (SS.isSet()) {
1607 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1608 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001609 }
John McCallc373d482010-01-27 01:50:18 +00001610
1611 // We don't want lookup warnings at this point.
1612 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001613
John McCallf7a1a742009-11-24 19:00:30 +00001614 bool Dependent
1615 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1616 &TemplateArgs);
1617 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001618 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001619 Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00001620 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00001621 RequiresADL, TemplateArgs,
1622 R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001623
1624 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001625}
1626
John McCallf7a1a742009-11-24 19:00:30 +00001627// We actually only call this from template instantiation.
John McCall60d7b3a2010-08-24 06:29:42 +00001628ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001629Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001630 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +00001631 const TemplateArgumentListInfo &TemplateArgs) {
1632 DeclContext *DC;
1633 if (!(DC = computeDeclContext(SS, false)) ||
1634 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00001635 RequireCompleteDeclContext(SS, DC))
Abramo Bagnara25777432010-08-11 22:01:17 +00001636 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001638 bool MemberOfUnknownSpecialization;
Abramo Bagnara25777432010-08-11 22:01:17 +00001639 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001640 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1641 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00001642
John McCallf7a1a742009-11-24 19:00:30 +00001643 if (R.isAmbiguous())
1644 return ExprError();
1645
1646 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001647 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1648 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001649 return ExprError();
1650 }
1651
1652 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001653 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1654 << (NestedNameSpecifier*) SS.getScopeRep()
1655 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001656 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1657 return ExprError();
1658 }
1659
1660 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001661}
1662
Douglas Gregorc45c2322009-03-31 00:43:58 +00001663/// \brief Form a dependent template name.
1664///
1665/// This action forms a dependent template name given the template
1666/// name and its (presumably dependent) scope specifier. For
1667/// example, given "MetaFun::template apply", the scope specifier \p
1668/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1669/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001670TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1671 SourceLocation TemplateKWLoc,
1672 CXXScopeSpec &SS,
1673 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +00001674 ParsedType ObjectType,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001675 bool EnteringContext,
1676 TemplateTy &Result) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00001677 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1678 !getLangOptions().CPlusPlus0x)
1679 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1680 << FixItHint::CreateRemoval(TemplateKWLoc);
1681
Douglas Gregor0707bc52010-01-19 16:01:07 +00001682 DeclContext *LookupCtx = 0;
1683 if (SS.isSet())
1684 LookupCtx = computeDeclContext(SS, EnteringContext);
1685 if (!LookupCtx && ObjectType)
John McCallb3d87482010-08-24 05:47:05 +00001686 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor0707bc52010-01-19 16:01:07 +00001687 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001688 // C++0x [temp.names]p5:
1689 // If a name prefixed by the keyword template is not the name of
1690 // a template, the program is ill-formed. [Note: the keyword
1691 // template may not be applied to non-template members of class
1692 // templates. -end note ] [ Note: as is the case with the
1693 // typename prefix, the template prefix is allowed in cases
1694 // where it is not strictly necessary; i.e., when the
1695 // nested-name-specifier or the expression on the left of the ->
1696 // or . is not dependent on a template-parameter, or the use
1697 // does not appear in the scope of a template. -end note]
1698 //
1699 // Note: C++03 was more strict here, because it banned the use of
1700 // the "template" keyword prior to a template-name that was not a
1701 // dependent name. C++ DR468 relaxed this requirement (the
1702 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregor732281d2010-06-14 22:07:54 +00001703 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001704 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001705 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1706 ObjectType, EnteringContext, Result,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001707 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001708 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1709 isa<CXXRecordDecl>(LookupCtx) &&
1710 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord6ab2322010-06-16 23:00:59 +00001711 // This is a dependent template. Handle it below.
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001712 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001713 Diag(Name.getSourceRange().getBegin(),
1714 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001715 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001716 << Name.getSourceRange()
1717 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001718 return TNK_Non_template;
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001719 } else {
1720 // We found something; return it.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001721 return TNK;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001722 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001723 }
1724
Mike Stump1eb44332009-09-09 15:08:12 +00001725 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001726 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001727
1728 switch (Name.getKind()) {
1729 case UnqualifiedId::IK_Identifier:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001730 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1731 Name.Identifier));
1732 return TNK_Dependent_template_name;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001733
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001734 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001735 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001736 Name.OperatorFunctionId.Operator));
Douglas Gregord6ab2322010-06-16 23:00:59 +00001737 return TNK_Dependent_template_name;
Sean Hunte6252d12009-11-28 08:58:14 +00001738
1739 case UnqualifiedId::IK_LiteralOperatorId:
1740 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1741
Douglas Gregor014e88d2009-11-03 23:16:33 +00001742 default:
1743 break;
1744 }
1745
1746 Diag(Name.getSourceRange().getBegin(),
1747 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001748 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001749 << Name.getSourceRange()
1750 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001751 return TNK_Non_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001752}
1753
Mike Stump1eb44332009-09-09 15:08:12 +00001754bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001755 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001756 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001757 const TemplateArgument &Arg = AL.getArgument();
1758
Anders Carlsson436b1562009-06-13 00:33:33 +00001759 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001760 switch(Arg.getKind()) {
1761 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00001762 // C++ [temp.arg.type]p1:
1763 // A template-argument for a template-parameter which is a
1764 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001765 break;
1766 case TemplateArgument::Template: {
1767 // We have a template type parameter but the template argument
1768 // is a template without any arguments.
1769 SourceRange SR = AL.getSourceRange();
1770 TemplateName Name = Arg.getAsTemplate();
1771 Diag(SR.getBegin(), diag::err_template_missing_args)
1772 << Name << SR;
1773 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1774 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00001775
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001776 return true;
1777 }
1778 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00001779 // We have a template type parameter but the template argument
1780 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001781 SourceRange SR = AL.getSourceRange();
1782 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001783 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Anders Carlsson436b1562009-06-13 00:33:33 +00001785 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001786 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001787 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001788
John McCalla93c9342009-12-07 02:54:59 +00001789 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001790 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Anders Carlsson436b1562009-06-13 00:33:33 +00001792 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001793 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001794 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001795 return false;
1796}
1797
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001798/// \brief Substitute template arguments into the default template argument for
1799/// the given template type parameter.
1800///
1801/// \param SemaRef the semantic analysis object for which we are performing
1802/// the substitution.
1803///
1804/// \param Template the template that we are synthesizing template arguments
1805/// for.
1806///
1807/// \param TemplateLoc the location of the template name that started the
1808/// template-id we are checking.
1809///
1810/// \param RAngleLoc the location of the right angle bracket ('>') that
1811/// terminates the template-id.
1812///
1813/// \param Param the template template parameter whose default we are
1814/// substituting into.
1815///
1816/// \param Converted the list of template arguments provided for template
1817/// parameters that precede \p Param in the template parameter list.
1818///
1819/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001820static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001821SubstDefaultTemplateArgument(Sema &SemaRef,
1822 TemplateDecl *Template,
1823 SourceLocation TemplateLoc,
1824 SourceLocation RAngleLoc,
1825 TemplateTypeParmDecl *Param,
1826 TemplateArgumentListBuilder &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001827 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001828
1829 // If the argument type is dependent, instantiate it now based
1830 // on the previously-computed template arguments.
1831 if (ArgType->getType()->isDependentType()) {
1832 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1833 /*TakeArgs=*/false);
1834
1835 MultiLevelTemplateArgumentList AllTemplateArgs
1836 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1837
1838 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1839 Template, Converted.getFlatArguments(),
1840 Converted.flatSize(),
1841 SourceRange(TemplateLoc, RAngleLoc));
1842
1843 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1844 Param->getDefaultArgumentLoc(),
1845 Param->getDeclName());
1846 }
1847
1848 return ArgType;
1849}
1850
1851/// \brief Substitute template arguments into the default template argument for
1852/// the given non-type template parameter.
1853///
1854/// \param SemaRef the semantic analysis object for which we are performing
1855/// the substitution.
1856///
1857/// \param Template the template that we are synthesizing template arguments
1858/// for.
1859///
1860/// \param TemplateLoc the location of the template name that started the
1861/// template-id we are checking.
1862///
1863/// \param RAngleLoc the location of the right angle bracket ('>') that
1864/// terminates the template-id.
1865///
Douglas Gregor788cd062009-11-11 01:00:40 +00001866/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001867/// substituting into.
1868///
1869/// \param Converted the list of template arguments provided for template
1870/// parameters that precede \p Param in the template parameter list.
1871///
1872/// \returns the substituted template argument, or NULL if an error occurred.
John McCall60d7b3a2010-08-24 06:29:42 +00001873static ExprResult
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001874SubstDefaultTemplateArgument(Sema &SemaRef,
1875 TemplateDecl *Template,
1876 SourceLocation TemplateLoc,
1877 SourceLocation RAngleLoc,
1878 NonTypeTemplateParmDecl *Param,
1879 TemplateArgumentListBuilder &Converted) {
1880 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1881 /*TakeArgs=*/false);
1882
1883 MultiLevelTemplateArgumentList AllTemplateArgs
1884 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1885
1886 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1887 Template, Converted.getFlatArguments(),
1888 Converted.flatSize(),
1889 SourceRange(TemplateLoc, RAngleLoc));
1890
1891 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1892}
1893
Douglas Gregor788cd062009-11-11 01:00:40 +00001894/// \brief Substitute template arguments into the default template argument for
1895/// the given template template parameter.
1896///
1897/// \param SemaRef the semantic analysis object for which we are performing
1898/// the substitution.
1899///
1900/// \param Template the template that we are synthesizing template arguments
1901/// for.
1902///
1903/// \param TemplateLoc the location of the template name that started the
1904/// template-id we are checking.
1905///
1906/// \param RAngleLoc the location of the right angle bracket ('>') that
1907/// terminates the template-id.
1908///
1909/// \param Param the template template parameter whose default we are
1910/// substituting into.
1911///
1912/// \param Converted the list of template arguments provided for template
1913/// parameters that precede \p Param in the template parameter list.
1914///
1915/// \returns the substituted template argument, or NULL if an error occurred.
1916static TemplateName
1917SubstDefaultTemplateArgument(Sema &SemaRef,
1918 TemplateDecl *Template,
1919 SourceLocation TemplateLoc,
1920 SourceLocation RAngleLoc,
1921 TemplateTemplateParmDecl *Param,
1922 TemplateArgumentListBuilder &Converted) {
1923 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1924 /*TakeArgs=*/false);
1925
1926 MultiLevelTemplateArgumentList AllTemplateArgs
1927 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1928
1929 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1930 Template, Converted.getFlatArguments(),
1931 Converted.flatSize(),
1932 SourceRange(TemplateLoc, RAngleLoc));
1933
1934 return SemaRef.SubstTemplateName(
1935 Param->getDefaultArgument().getArgument().getAsTemplate(),
1936 Param->getDefaultArgument().getTemplateNameLoc(),
1937 AllTemplateArgs);
1938}
1939
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001940/// \brief If the given template parameter has a default template
1941/// argument, substitute into that default template argument and
1942/// return the corresponding template argument.
1943TemplateArgumentLoc
1944Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1945 SourceLocation TemplateLoc,
1946 SourceLocation RAngleLoc,
1947 Decl *Param,
1948 TemplateArgumentListBuilder &Converted) {
1949 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1950 if (!TypeParm->hasDefaultArgument())
1951 return TemplateArgumentLoc();
1952
John McCalla93c9342009-12-07 02:54:59 +00001953 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001954 TemplateLoc,
1955 RAngleLoc,
1956 TypeParm,
1957 Converted);
1958 if (DI)
1959 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1960
1961 return TemplateArgumentLoc();
1962 }
1963
1964 if (NonTypeTemplateParmDecl *NonTypeParm
1965 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1966 if (!NonTypeParm->hasDefaultArgument())
1967 return TemplateArgumentLoc();
1968
John McCall60d7b3a2010-08-24 06:29:42 +00001969 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001970 TemplateLoc,
1971 RAngleLoc,
1972 NonTypeParm,
1973 Converted);
1974 if (Arg.isInvalid())
1975 return TemplateArgumentLoc();
1976
1977 Expr *ArgE = Arg.takeAs<Expr>();
1978 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1979 }
1980
1981 TemplateTemplateParmDecl *TempTempParm
1982 = cast<TemplateTemplateParmDecl>(Param);
1983 if (!TempTempParm->hasDefaultArgument())
1984 return TemplateArgumentLoc();
1985
1986 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1987 TemplateLoc,
1988 RAngleLoc,
1989 TempTempParm,
1990 Converted);
1991 if (TName.isNull())
1992 return TemplateArgumentLoc();
1993
1994 return TemplateArgumentLoc(TemplateArgument(TName),
1995 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1996 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1997}
1998
Douglas Gregore7526412009-11-11 19:31:23 +00001999/// \brief Check that the given template argument corresponds to the given
2000/// template parameter.
2001bool Sema::CheckTemplateArgument(NamedDecl *Param,
2002 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00002003 TemplateDecl *Template,
2004 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002005 SourceLocation RAngleLoc,
Douglas Gregor02024a92010-03-28 02:42:43 +00002006 TemplateArgumentListBuilder &Converted,
2007 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002008 // Check template type parameters.
2009 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002010 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00002011
Douglas Gregord9e15302009-11-11 19:41:09 +00002012 // Check non-type template parameters.
2013 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002014 // Do substitution on the type of the non-type template parameter
2015 // with the template arguments we've seen thus far.
2016 QualType NTTPType = NTTP->getType();
2017 if (NTTPType->isDependentType()) {
2018 // Do substitution on the type of the non-type template parameter.
2019 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2020 NTTP, Converted.getFlatArguments(),
2021 Converted.flatSize(),
2022 SourceRange(TemplateLoc, RAngleLoc));
2023
2024 TemplateArgumentList TemplateArgs(Context, Converted,
2025 /*TakeArgs=*/false);
2026 NTTPType = SubstType(NTTPType,
2027 MultiLevelTemplateArgumentList(TemplateArgs),
2028 NTTP->getLocation(),
2029 NTTP->getDeclName());
2030 // If that worked, check the non-type template parameter type
2031 // for validity.
2032 if (!NTTPType.isNull())
2033 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2034 NTTP->getLocation());
2035 if (NTTPType.isNull())
2036 return true;
2037 }
2038
2039 switch (Arg.getArgument().getKind()) {
2040 case TemplateArgument::Null:
2041 assert(false && "Should never see a NULL template argument here");
2042 return true;
2043
2044 case TemplateArgument::Expression: {
2045 Expr *E = Arg.getArgument().getAsExpr();
2046 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002047 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00002048 return true;
2049
2050 Converted.Append(Result);
2051 break;
2052 }
2053
2054 case TemplateArgument::Declaration:
2055 case TemplateArgument::Integral:
2056 // We've already checked this template argument, so just copy
2057 // it to the list of converted arguments.
2058 Converted.Append(Arg.getArgument());
2059 break;
2060
2061 case TemplateArgument::Template:
2062 // We were given a template template argument. It may not be ill-formed;
2063 // see below.
2064 if (DependentTemplateName *DTN
2065 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2066 // We have a template argument such as \c T::template X, which we
2067 // parsed as a template template argument. However, since we now
2068 // know that we need a non-type template argument, convert this
Abramo Bagnara25777432010-08-11 22:01:17 +00002069 // template name into an expression.
2070
2071 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2072 Arg.getTemplateNameLoc());
2073
John McCallf7a1a742009-11-24 19:00:30 +00002074 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2075 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002076 Arg.getTemplateQualifierRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002077 NameInfo);
Douglas Gregore7526412009-11-11 19:31:23 +00002078
2079 TemplateArgument Result;
2080 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2081 return true;
2082
2083 Converted.Append(Result);
2084 break;
2085 }
2086
2087 // We have a template argument that actually does refer to a class
2088 // template, template alias, or template template parameter, and
2089 // therefore cannot be a non-type template argument.
2090 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2091 << Arg.getSourceRange();
2092
2093 Diag(Param->getLocation(), diag::note_template_param_here);
2094 return true;
2095
2096 case TemplateArgument::Type: {
2097 // We have a non-type template parameter but the template
2098 // argument is a type.
2099
2100 // C++ [temp.arg]p2:
2101 // In a template-argument, an ambiguity between a type-id and
2102 // an expression is resolved to a type-id, regardless of the
2103 // form of the corresponding template-parameter.
2104 //
2105 // We warn specifically about this case, since it can be rather
2106 // confusing for users.
2107 QualType T = Arg.getArgument().getAsType();
2108 SourceRange SR = Arg.getSourceRange();
2109 if (T->isFunctionType())
2110 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2111 else
2112 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2113 Diag(Param->getLocation(), diag::note_template_param_here);
2114 return true;
2115 }
2116
2117 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002118 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002119 break;
2120 }
2121
2122 return false;
2123 }
2124
2125
2126 // Check template template parameters.
2127 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2128
2129 // Substitute into the template parameter list of the template
2130 // template parameter, since previously-supplied template arguments
2131 // may appear within the template template parameter.
2132 {
2133 // Set up a template instantiation context.
2134 LocalInstantiationScope Scope(*this);
2135 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2136 TempParm, Converted.getFlatArguments(),
2137 Converted.flatSize(),
2138 SourceRange(TemplateLoc, RAngleLoc));
2139
2140 TemplateArgumentList TemplateArgs(Context, Converted,
2141 /*TakeArgs=*/false);
2142 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2143 SubstDecl(TempParm, CurContext,
2144 MultiLevelTemplateArgumentList(TemplateArgs)));
2145 if (!TempParm)
2146 return true;
2147
2148 // FIXME: TempParam is leaked.
2149 }
2150
2151 switch (Arg.getArgument().getKind()) {
2152 case TemplateArgument::Null:
2153 assert(false && "Should never see a NULL template argument here");
2154 return true;
2155
2156 case TemplateArgument::Template:
2157 if (CheckTemplateArgument(TempParm, Arg))
2158 return true;
2159
2160 Converted.Append(Arg.getArgument());
2161 break;
2162
2163 case TemplateArgument::Expression:
2164 case TemplateArgument::Type:
2165 // We have a template template parameter but the template
2166 // argument does not refer to a template.
2167 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2168 return true;
2169
2170 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002171 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002172 "Declaration argument with template template parameter");
2173 break;
2174 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002175 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002176 "Integral argument with template template parameter");
2177 break;
2178
2179 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002180 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002181 break;
2182 }
2183
2184 return false;
2185}
2186
Douglas Gregorc15cb382009-02-09 23:23:08 +00002187/// \brief Check that the given template argument list is well-formed
2188/// for specializing the given template.
2189bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2190 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002191 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002192 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002193 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002194 TemplateParameterList *Params = Template->getTemplateParameters();
2195 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002196 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002197 bool Invalid = false;
2198
John McCalld5532b62009-11-23 01:53:49 +00002199 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2200
Mike Stump1eb44332009-09-09 15:08:12 +00002201 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002202 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002203
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002204 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002205 (NumArgs < Params->getMinRequiredArguments() &&
2206 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002207 // FIXME: point at either the first arg beyond what we can handle,
2208 // or the '>', depending on whether we have too many or too few
2209 // arguments.
2210 SourceRange Range;
2211 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002212 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002213 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2214 << (NumArgs > NumParams)
2215 << (isa<ClassTemplateDecl>(Template)? 0 :
2216 isa<FunctionTemplateDecl>(Template)? 1 :
2217 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2218 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002219 Diag(Template->getLocation(), diag::note_template_decl_here)
2220 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002221 Invalid = true;
2222 }
Mike Stump1eb44332009-09-09 15:08:12 +00002223
2224 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002225 // [...] The type and form of each template-argument specified in
2226 // a template-id shall match the type and form specified for the
2227 // corresponding parameter declared by the template in its
2228 // template-parameter-list.
2229 unsigned ArgIdx = 0;
2230 for (TemplateParameterList::iterator Param = Params->begin(),
2231 ParamEnd = Params->end();
2232 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002233 if (ArgIdx > NumArgs && PartialTemplateArgs)
2234 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002235
Douglas Gregord9e15302009-11-11 19:41:09 +00002236 // If we have a template parameter pack, check every remaining template
2237 // argument against that template parameter pack.
2238 if ((*Param)->isTemplateParameterPack()) {
2239 Converted.BeginPack();
2240 for (; ArgIdx < NumArgs; ++ArgIdx) {
2241 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2242 TemplateLoc, RAngleLoc, Converted)) {
2243 Invalid = true;
2244 break;
2245 }
2246 }
2247 Converted.EndPack();
2248 continue;
2249 }
2250
Douglas Gregorf35f8282009-11-11 21:54:23 +00002251 if (ArgIdx < NumArgs) {
2252 // Check the template argument we were given.
2253 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2254 TemplateLoc, RAngleLoc, Converted))
2255 return true;
2256
2257 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002258 }
Douglas Gregore7526412009-11-11 19:31:23 +00002259
Douglas Gregorf35f8282009-11-11 21:54:23 +00002260 // We have a default template argument that we will use.
2261 TemplateArgumentLoc Arg;
2262
2263 // Retrieve the default template argument from the template
2264 // parameter. For each kind of template parameter, we substitute the
2265 // template arguments provided thus far and any "outer" template arguments
2266 // (when the template parameter was part of a nested template) into
2267 // the default argument.
2268 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2269 if (!TTP->hasDefaultArgument()) {
2270 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2271 break;
2272 }
2273
John McCalla93c9342009-12-07 02:54:59 +00002274 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002275 Template,
2276 TemplateLoc,
2277 RAngleLoc,
2278 TTP,
2279 Converted);
2280 if (!ArgType)
2281 return true;
2282
2283 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2284 ArgType);
2285 } else if (NonTypeTemplateParmDecl *NTTP
2286 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2287 if (!NTTP->hasDefaultArgument()) {
2288 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2289 break;
2290 }
2291
John McCall60d7b3a2010-08-24 06:29:42 +00002292 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002293 TemplateLoc,
2294 RAngleLoc,
2295 NTTP,
2296 Converted);
2297 if (E.isInvalid())
2298 return true;
2299
2300 Expr *Ex = E.takeAs<Expr>();
2301 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2302 } else {
2303 TemplateTemplateParmDecl *TempParm
2304 = cast<TemplateTemplateParmDecl>(*Param);
2305
2306 if (!TempParm->hasDefaultArgument()) {
2307 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2308 break;
2309 }
2310
2311 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2312 TemplateLoc,
2313 RAngleLoc,
2314 TempParm,
2315 Converted);
2316 if (Name.isNull())
2317 return true;
2318
2319 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2320 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2321 TempParm->getDefaultArgument().getTemplateNameLoc());
2322 }
2323
2324 // Introduce an instantiation record that describes where we are using
2325 // the default template argument.
2326 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2327 Converted.getFlatArguments(),
2328 Converted.flatSize(),
2329 SourceRange(TemplateLoc, RAngleLoc));
2330
2331 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002332 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002333 RAngleLoc, Converted))
2334 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002335 }
2336
2337 return Invalid;
2338}
2339
2340/// \brief Check a template argument against its corresponding
2341/// template type parameter.
2342///
2343/// This routine implements the semantics of C++ [temp.arg.type]. It
2344/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002345bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002346 TypeSourceInfo *ArgInfo) {
2347 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002348 QualType Arg = ArgInfo->getType();
2349
Chandler Carruth17fb8552010-09-03 21:12:34 +00002350 // C++03 [temp.arg.type]p2:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002351 // A local type, a type with no linkage, an unnamed type or a type
2352 // compounded from any of these types shall not be used as a
2353 // template-argument for a template type-parameter.
Chandler Carruth17fb8552010-09-03 21:12:34 +00002354 // C++0x allows these, and even in C++03 we allow them as an extension with
2355 // a warning.
Douglas Gregor0fddb972010-05-22 16:17:30 +00002356 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth17fb8552010-09-03 21:12:34 +00002357 if (!LangOpts.CPlusPlus0x) {
2358 const TagType *Tag = 0;
2359 if (const EnumType *EnumT = Arg->getAs<EnumType>())
2360 Tag = EnumT;
2361 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
2362 Tag = RecordT;
2363 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2364 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
2365 Diag(SR.getBegin(), diag::ext_template_arg_local_type)
2366 << QualType(Tag, 0) << SR;
2367 } else if (Tag && !Tag->getDecl()->getDeclName() &&
2368 !Tag->getDecl()->getTypedefForAnonDecl()) {
2369 Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
2370 Diag(Tag->getDecl()->getLocation(),
2371 diag::note_template_unnamed_type_here);
2372 }
2373 }
2374
2375 if (Arg->isVariablyModifiedType()) {
2376 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002377 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00002378 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002379 }
2380
2381 return false;
2382}
2383
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002384/// \brief Checks whether the given template argument is the address
2385/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002386static bool
2387CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2388 NonTypeTemplateParmDecl *Param,
2389 QualType ParamType,
2390 Expr *ArgIn,
2391 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002392 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002393 Expr *Arg = ArgIn;
2394 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002395
2396 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002397 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002398 Arg = Cast->getSubExpr();
2399
2400 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002401 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002402 // A template-argument for a non-type, non-template
2403 // template-parameter shall be one of: [...]
2404 //
2405 // -- the address of an object or function with external
2406 // linkage, including function templates and function
2407 // template-ids but excluding non-static class members,
2408 // expressed as & id-expression where the & is optional if
2409 // the name refers to a function or array, or if the
2410 // corresponding template-parameter is a reference; or
2411 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002412
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002413 // In C++98/03 mode, give an extension warning on any extra parentheses.
2414 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2415 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002416 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002417 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002418 S.Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002419 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002420 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002421 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002422 }
2423
2424 Arg = Parens->getSubExpr();
2425 }
2426
Douglas Gregorb7a09262010-04-01 18:32:35 +00002427 bool AddressTaken = false;
2428 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002429 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00002430 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002431 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb7a09262010-04-01 18:32:35 +00002432 AddressTaken = true;
2433 AddrOpLoc = UnOp->getOperatorLoc();
2434 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002435 } else
2436 DRE = dyn_cast<DeclRefExpr>(Arg);
2437
Douglas Gregorb7a09262010-04-01 18:32:35 +00002438 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002439 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2440 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002441 S.Diag(Param->getLocation(), diag::note_template_param_here);
2442 return true;
2443 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002444
2445 // Stop checking the precise nature of the argument if it is value dependent,
2446 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002447 if (Arg->isValueDependent()) {
2448 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth038cc392010-01-31 10:01:20 +00002449 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002450 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002451
Douglas Gregorb7a09262010-04-01 18:32:35 +00002452 if (!isa<ValueDecl>(DRE->getDecl())) {
2453 S.Diag(Arg->getSourceRange().getBegin(),
2454 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002455 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002456 S.Diag(Param->getLocation(), diag::note_template_param_here);
2457 return true;
2458 }
2459
2460 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002461
2462 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00002463 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2464 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002465 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002466 S.Diag(Param->getLocation(), diag::note_template_param_here);
2467 return true;
2468 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002469
2470 // Cannot refer to non-static member functions
2471 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00002472 if (!Method->isStatic()) {
2473 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002474 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002475 S.Diag(Param->getLocation(), diag::note_template_param_here);
2476 return true;
2477 }
Mike Stump1eb44332009-09-09 15:08:12 +00002478
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002479 // Functions must have external linkage.
2480 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002481 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002482 S.Diag(Arg->getSourceRange().getBegin(),
2483 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002484 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002485 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002486 << true;
2487 return true;
2488 }
2489
2490 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002491 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002492
Douglas Gregorb7a09262010-04-01 18:32:35 +00002493 // If the template parameter has pointer type, the function decays.
2494 if (ParamType->isPointerType() && !AddressTaken)
2495 ArgType = S.Context.getPointerType(Func->getType());
2496 else if (AddressTaken && ParamType->isReferenceType()) {
2497 // If we originally had an address-of operator, but the
2498 // parameter has reference type, complain and (if things look
2499 // like they will work) drop the address-of operator.
2500 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2501 ParamType.getNonReferenceType())) {
2502 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2503 << ParamType;
2504 S.Diag(Param->getLocation(), diag::note_template_param_here);
2505 return true;
2506 }
2507
2508 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2509 << ParamType
2510 << FixItHint::CreateRemoval(AddrOpLoc);
2511 S.Diag(Param->getLocation(), diag::note_template_param_here);
2512
2513 ArgType = Func->getType();
2514 }
2515 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002516 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002517 S.Diag(Arg->getSourceRange().getBegin(),
2518 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002519 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002520 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002521 << true;
2522 return true;
2523 }
2524
Douglas Gregorb7a09262010-04-01 18:32:35 +00002525 // A value of reference type is not an object.
2526 if (Var->getType()->isReferenceType()) {
2527 S.Diag(Arg->getSourceRange().getBegin(),
2528 diag::err_template_arg_reference_var)
2529 << Var->getType() << Arg->getSourceRange();
2530 S.Diag(Param->getLocation(), diag::note_template_param_here);
2531 return true;
2532 }
2533
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002534 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002535 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002536
2537 // If the template parameter has pointer type, we must have taken
2538 // the address of this object.
2539 if (ParamType->isReferenceType()) {
2540 if (AddressTaken) {
2541 // If we originally had an address-of operator, but the
2542 // parameter has reference type, complain and (if things look
2543 // like they will work) drop the address-of operator.
2544 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2545 ParamType.getNonReferenceType())) {
2546 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2547 << ParamType;
2548 S.Diag(Param->getLocation(), diag::note_template_param_here);
2549 return true;
2550 }
2551
2552 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2553 << ParamType
2554 << FixItHint::CreateRemoval(AddrOpLoc);
2555 S.Diag(Param->getLocation(), diag::note_template_param_here);
2556
2557 ArgType = Var->getType();
2558 }
2559 } else if (!AddressTaken && ParamType->isPointerType()) {
2560 if (Var->getType()->isArrayType()) {
2561 // Array-to-pointer decay.
2562 ArgType = S.Context.getArrayDecayedType(Var->getType());
2563 } else {
2564 // If the template parameter has pointer type but the address of
2565 // this object was not taken, complain and (possibly) recover by
2566 // taking the address of the entity.
2567 ArgType = S.Context.getPointerType(Var->getType());
2568 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2569 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2570 << ParamType;
2571 S.Diag(Param->getLocation(), diag::note_template_param_here);
2572 return true;
2573 }
2574
2575 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2576 << ParamType
2577 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2578
2579 S.Diag(Param->getLocation(), diag::note_template_param_here);
2580 }
2581 }
2582 } else {
2583 // We found something else, but we don't know specifically what it is.
2584 S.Diag(Arg->getSourceRange().getBegin(),
2585 diag::err_template_arg_not_object_or_func)
2586 << Arg->getSourceRange();
2587 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2588 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002589 }
Mike Stump1eb44332009-09-09 15:08:12 +00002590
Douglas Gregorb7a09262010-04-01 18:32:35 +00002591 if (ParamType->isPointerType() &&
2592 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2593 S.IsQualificationConversion(ArgType, ParamType)) {
2594 // For pointer-to-object types, qualification conversions are
2595 // permitted.
2596 } else {
2597 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2598 if (!ParamRef->getPointeeType()->isFunctionType()) {
2599 // C++ [temp.arg.nontype]p5b3:
2600 // For a non-type template-parameter of type reference to
2601 // object, no conversions apply. The type referred to by the
2602 // reference may be more cv-qualified than the (otherwise
2603 // identical) type of the template- argument. The
2604 // template-parameter is bound directly to the
2605 // template-argument, which shall be an lvalue.
2606
2607 // FIXME: Other qualifiers?
2608 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2609 unsigned ArgQuals = ArgType.getCVRQualifiers();
2610
2611 if ((ParamQuals | ArgQuals) != ParamQuals) {
2612 S.Diag(Arg->getSourceRange().getBegin(),
2613 diag::err_template_arg_ref_bind_ignores_quals)
2614 << ParamType << Arg->getType()
2615 << Arg->getSourceRange();
2616 S.Diag(Param->getLocation(), diag::note_template_param_here);
2617 return true;
2618 }
2619 }
2620 }
2621
2622 // At this point, the template argument refers to an object or
2623 // function with external linkage. We now need to check whether the
2624 // argument and parameter types are compatible.
2625 if (!S.Context.hasSameUnqualifiedType(ArgType,
2626 ParamType.getNonReferenceType())) {
2627 // We can't perform this conversion or binding.
2628 if (ParamType->isReferenceType())
2629 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2630 << ParamType << Arg->getType() << Arg->getSourceRange();
2631 else
2632 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2633 << Arg->getType() << ParamType << Arg->getSourceRange();
2634 S.Diag(Param->getLocation(), diag::note_template_param_here);
2635 return true;
2636 }
2637 }
2638
2639 // Create the template argument.
2640 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor77c13e02010-04-24 18:20:53 +00002641 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00002642 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002643}
2644
2645/// \brief Checks whether the given template argument is a pointer to
2646/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002647bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2648 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002649 bool Invalid = false;
2650
2651 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002652 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002653 Arg = Cast->getSubExpr();
2654
2655 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002656 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002657 // A template-argument for a non-type, non-template
2658 // template-parameter shall be one of: [...]
2659 //
2660 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002661 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002662
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002663 // In C++98/03 mode, give an extension warning on any extra parentheses.
2664 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2665 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002666 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002667 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00002668 Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002669 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002670 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002671 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002672 }
2673
2674 Arg = Parens->getSubExpr();
2675 }
2676
Douglas Gregorcaddba02009-11-12 18:38:13 +00002677 // A pointer-to-member constant written &Class::member.
2678 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00002679 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002680 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2681 if (DRE && !DRE->getQualifier())
2682 DRE = 0;
2683 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002684 }
2685 // A constant of pointer-to-member type.
2686 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2687 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2688 if (VD->getType()->isMemberPointerType()) {
2689 if (isa<NonTypeTemplateParmDecl>(VD) ||
2690 (isa<VarDecl>(VD) &&
2691 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2692 if (Arg->isTypeDependent() || Arg->isValueDependent())
2693 Converted = TemplateArgument(Arg->Retain());
2694 else
2695 Converted = TemplateArgument(VD->getCanonicalDecl());
2696 return Invalid;
2697 }
2698 }
2699 }
2700
2701 DRE = 0;
2702 }
2703
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002704 if (!DRE)
2705 return Diag(Arg->getSourceRange().getBegin(),
2706 diag::err_template_arg_not_pointer_to_member_form)
2707 << Arg->getSourceRange();
2708
2709 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2710 assert((isa<FieldDecl>(DRE->getDecl()) ||
2711 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2712 "Only non-static member pointers can make it here");
2713
2714 // Okay: this is the address of a non-static member, and therefore
2715 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002716 if (Arg->isTypeDependent() || Arg->isValueDependent())
2717 Converted = TemplateArgument(Arg->Retain());
2718 else
2719 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002720 return Invalid;
2721 }
2722
2723 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002724 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002725 diag::err_template_arg_not_pointer_to_member_form)
2726 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002727 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002728 diag::note_template_arg_refers_here);
2729 return true;
2730}
2731
Douglas Gregorc15cb382009-02-09 23:23:08 +00002732/// \brief Check a template argument against its corresponding
2733/// non-type template parameter.
2734///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002735/// This routine implements the semantics of C++ [temp.arg.nontype].
2736/// It returns true if an error occurred, and false otherwise. \p
2737/// InstantiatedParamType is the type of the non-type template
2738/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002739///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002740/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002741bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002742 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00002743 TemplateArgument &Converted,
2744 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002745 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2746
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002747 // If either the parameter has a dependent type or the argument is
2748 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00002749 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2750 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002751 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002752 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002753 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002754
2755 // C++ [temp.arg.nontype]p5:
2756 // The following conversions are performed on each expression used
2757 // as a non-type template-argument. If a non-type
2758 // template-argument cannot be converted to the type of the
2759 // corresponding template-parameter then the program is
2760 // ill-formed.
2761 //
2762 // -- for a non-type template-parameter of integral or
2763 // enumeration type, integral promotions (4.5) and integral
2764 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002765 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002766 QualType ArgType = Arg->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002767 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002768 // C++ [temp.arg.nontype]p1:
2769 // A template-argument for a non-type, non-template
2770 // template-parameter shall be one of:
2771 //
2772 // -- an integral constant-expression of integral or enumeration
2773 // type; or
2774 // -- the name of a non-type template-parameter; or
2775 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002776 llvm::APSInt Value;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002777 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002778 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002779 diag::err_template_arg_not_integral_or_enumeral)
2780 << ArgType << Arg->getSourceRange();
2781 Diag(Param->getLocation(), diag::note_template_param_here);
2782 return true;
2783 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002784 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002785 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2786 << ArgType << Arg->getSourceRange();
2787 return true;
2788 }
2789
Douglas Gregor02024a92010-03-28 02:42:43 +00002790 // From here on out, all we care about are the unqualified forms
2791 // of the parameter and argument types.
2792 ParamType = ParamType.getUnqualifiedType();
2793 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002794
2795 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002796 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002797 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00002798 } else if (CTAK == CTAK_Deduced) {
2799 // C++ [temp.deduct.type]p17:
2800 // If, in the declaration of a function template with a non-type
2801 // template-parameter, the non-type template- parameter is used
2802 // in an expression in the function parameter-list and, if the
2803 // corresponding template-argument is deduced, the
2804 // template-argument type shall match the type of the
2805 // template-parameter exactly, except that a template-argument
2806 // deduced from an array bound may be of any integral type.
2807 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2808 << ArgType << ParamType;
2809 Diag(Param->getLocation(), diag::note_template_param_here);
2810 return true;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002811 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2812 !ParamType->isEnumeralType()) {
2813 // This is an integral promotion or conversion.
John McCall2de56d12010-08-25 11:45:40 +00002814 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002815 } else {
2816 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002817 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002818 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002819 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002820 Diag(Param->getLocation(), diag::note_template_param_here);
2821 return true;
2822 }
2823
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002824 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002825 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002826 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002827
2828 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002829 llvm::APSInt OldValue = Value;
2830
2831 // Coerce the template argument's value to the value it will have
2832 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002833 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002834 if (Value.getBitWidth() != AllowedBits)
2835 Value.extOrTrunc(AllowedBits);
2836 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002837
2838 // Complain if an unsigned parameter received a negative value.
2839 if (IntegerType->isUnsignedIntegerType()
2840 && (OldValue.isSigned() && OldValue.isNegative())) {
2841 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2842 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2843 << Arg->getSourceRange();
2844 Diag(Param->getLocation(), diag::note_template_param_here);
2845 }
2846
2847 // Complain if we overflowed the template parameter's type.
2848 unsigned RequiredBits;
2849 if (IntegerType->isUnsignedIntegerType())
2850 RequiredBits = OldValue.getActiveBits();
2851 else if (OldValue.isUnsigned())
2852 RequiredBits = OldValue.getActiveBits() + 1;
2853 else
2854 RequiredBits = OldValue.getMinSignedBits();
2855 if (RequiredBits > AllowedBits) {
2856 Diag(Arg->getSourceRange().getBegin(),
2857 diag::warn_template_arg_too_large)
2858 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2859 << Arg->getSourceRange();
2860 Diag(Param->getLocation(), diag::note_template_param_here);
2861 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002862 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002863
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002864 // Add the value of this argument to the list of converted
2865 // arguments. We use the bitwidth and signedness of the template
2866 // parameter.
2867 if (Arg->isValueDependent()) {
2868 // The argument is value-dependent. Create a new
2869 // TemplateArgument with the converted expression.
2870 Converted = TemplateArgument(Arg);
2871 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002872 }
2873
John McCall833ca992009-10-29 08:12:44 +00002874 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002875 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002876 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002877 return false;
2878 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002879
John McCall6bb80172010-03-30 21:47:33 +00002880 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2881
Douglas Gregorb7a09262010-04-01 18:32:35 +00002882 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2883 // from a template argument of type std::nullptr_t to a non-type
2884 // template parameter of type pointer to object, pointer to
2885 // function, or pointer-to-member, respectively.
2886 if (ArgType->isNullPtrType() &&
2887 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2888 Converted = TemplateArgument((NamedDecl *)0);
2889 return false;
2890 }
2891
Douglas Gregorb86b0572009-02-11 01:18:59 +00002892 // Handle pointer-to-function, reference-to-function, and
2893 // pointer-to-member-function all in (roughly) the same way.
2894 if (// -- For a non-type template-parameter of type pointer to
2895 // function, only the function-to-pointer conversion (4.3) is
2896 // applied. If the template-argument represents a set of
2897 // overloaded functions (or a pointer to such), the matching
2898 // function is selected from the set (13.4).
2899 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002900 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002901 // -- For a non-type template-parameter of type reference to
2902 // function, no conversions apply. If the template-argument
2903 // represents a set of overloaded functions, the matching
2904 // function is selected from the set (13.4).
2905 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002906 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002907 // -- For a non-type template-parameter of type pointer to
2908 // member function, no conversions apply. If the
2909 // template-argument represents a set of overloaded member
2910 // functions, the matching member function is selected from
2911 // the set (13.4).
2912 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002913 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002914 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002915
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002916 if (Arg->getType() == Context.OverloadTy) {
2917 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2918 true,
2919 FoundResult)) {
2920 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2921 return true;
2922
2923 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2924 ArgType = Arg->getType();
2925 } else
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002926 return true;
Douglas Gregora35284b2009-02-11 00:19:33 +00002927 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002928
Douglas Gregorb7a09262010-04-01 18:32:35 +00002929 if (!ParamType->isMemberPointerType())
2930 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2931 ParamType,
2932 Arg, Converted);
2933
2934 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCall2de56d12010-08-25 11:45:40 +00002935 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb7a09262010-04-01 18:32:35 +00002936 } else if (!Context.hasSameUnqualifiedType(ArgType,
2937 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002938 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002939 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002940 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002941 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002942 Diag(Param->getLocation(), diag::note_template_param_here);
2943 return true;
2944 }
Mike Stump1eb44332009-09-09 15:08:12 +00002945
Douglas Gregorb7a09262010-04-01 18:32:35 +00002946 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregora35284b2009-02-11 00:19:33 +00002947 }
2948
Chris Lattnerfe90de72009-02-20 21:37:53 +00002949 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002950 // -- for a non-type template-parameter of type pointer to
2951 // object, qualification conversions (4.4) and the
2952 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002953 // C++0x also allows a value of std::nullptr_t.
Eli Friedman13578692010-08-05 02:49:48 +00002954 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002955 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002956
Douglas Gregorb7a09262010-04-01 18:32:35 +00002957 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2958 ParamType,
2959 Arg, Converted);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002960 }
Mike Stump1eb44332009-09-09 15:08:12 +00002961
Ted Kremenek6217b802009-07-29 21:53:49 +00002962 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002963 // -- For a non-type template-parameter of type reference to
2964 // object, no conversions apply. The type referred to by the
2965 // reference may be more cv-qualified than the (otherwise
2966 // identical) type of the template-argument. The
2967 // template-parameter is bound directly to the
2968 // template-argument, which must be an lvalue.
Eli Friedman13578692010-08-05 02:49:48 +00002969 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002970 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002971
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002972 if (Arg->getType() == Context.OverloadTy) {
2973 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2974 ParamRefType->getPointeeType(),
2975 true,
2976 FoundResult)) {
2977 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2978 return true;
2979
2980 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2981 ArgType = Arg->getType();
2982 } else
Douglas Gregorb7a09262010-04-01 18:32:35 +00002983 return true;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002984 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002985
Douglas Gregorb7a09262010-04-01 18:32:35 +00002986 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2987 ParamType,
2988 Arg, Converted);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002989 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002990
2991 // -- For a non-type template-parameter of type pointer to data
2992 // member, qualification conversions (4.4) are applied.
2993 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2994
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002995 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002996 // Types match exactly: nothing more to do here.
2997 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCall2de56d12010-08-25 11:45:40 +00002998 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor658bbb52009-02-11 16:16:59 +00002999 } else {
3000 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003001 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00003002 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003003 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00003004 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00003005 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00003006 }
3007
Douglas Gregorcaddba02009-11-12 18:38:13 +00003008 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00003009}
3010
3011/// \brief Check a template argument against its corresponding
3012/// template template parameter.
3013///
3014/// This routine implements the semantics of C++ [temp.arg.template].
3015/// It returns true if an error occurred, and false otherwise.
3016bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00003017 const TemplateArgumentLoc &Arg) {
3018 TemplateName Name = Arg.getArgument().getAsTemplate();
3019 TemplateDecl *Template = Name.getAsTemplateDecl();
3020 if (!Template) {
3021 // Any dependent template name is fine.
3022 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3023 return false;
3024 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003025
3026 // C++ [temp.arg.template]p1:
3027 // A template-argument for a template template-parameter shall be
3028 // the name of a class template, expressed as id-expression. Only
3029 // primary class templates are considered when matching the
3030 // template template argument with the corresponding parameter;
3031 // partial specializations are not considered even if their
3032 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003033 //
3034 // Note that we also allow template template parameters here, which
3035 // will happen when we are dealing with, e.g., class template
3036 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00003037 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003038 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003039 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00003040 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00003041 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00003042 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003043 << Template;
3044 }
3045
3046 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3047 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00003048 true,
3049 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00003050 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00003051}
3052
Douglas Gregor02024a92010-03-28 02:42:43 +00003053/// \brief Given a non-type template argument that refers to a
3054/// declaration and the type of its corresponding non-type template
3055/// parameter, produce an expression that properly refers to that
3056/// declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00003057ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003058Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3059 QualType ParamType,
3060 SourceLocation Loc) {
3061 assert(Arg.getKind() == TemplateArgument::Declaration &&
3062 "Only declaration template arguments permitted here");
3063 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3064
3065 if (VD->getDeclContext()->isRecord() &&
3066 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3067 // If the value is a class member, we might have a pointer-to-member.
3068 // Determine whether the non-type template template parameter is of
3069 // pointer-to-member type. If so, we need to build an appropriate
3070 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3071 // would refer to the member itself.
3072 if (ParamType->isMemberPointerType()) {
3073 QualType ClassType
3074 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3075 NestedNameSpecifier *Qualifier
John McCall9ae2f072010-08-23 23:25:46 +00003076 = NestedNameSpecifier::Create(Context, 0, false,
3077 ClassType.getTypePtr());
Douglas Gregor02024a92010-03-28 02:42:43 +00003078 CXXScopeSpec SS;
3079 SS.setScopeRep(Qualifier);
John McCall60d7b3a2010-08-24 06:29:42 +00003080 ExprResult RefExpr = BuildDeclRefExpr(VD,
Douglas Gregor02024a92010-03-28 02:42:43 +00003081 VD->getType().getNonReferenceType(),
3082 Loc,
3083 &SS);
3084 if (RefExpr.isInvalid())
3085 return ExprError();
3086
John McCall2de56d12010-08-25 11:45:40 +00003087 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorc0c83002010-04-30 21:46:38 +00003088
3089 // We might need to perform a trailing qualification conversion, since
3090 // the element type on the parameter could be more qualified than the
3091 // element type in the expression we constructed.
3092 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3093 ParamType.getUnqualifiedType())) {
3094 Expr *RefE = RefExpr.takeAs<Expr>();
John McCall2de56d12010-08-25 11:45:40 +00003095 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorc0c83002010-04-30 21:46:38 +00003096 RefExpr = Owned(RefE);
3097 }
3098
Douglas Gregor02024a92010-03-28 02:42:43 +00003099 assert(!RefExpr.isInvalid() &&
3100 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00003101 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00003102 return move(RefExpr);
3103 }
3104 }
3105
3106 QualType T = VD->getType().getNonReferenceType();
3107 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003108 // When the non-type template parameter is a pointer, take the
3109 // address of the declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00003110 ExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003111 if (RefExpr.isInvalid())
3112 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003113
3114 if (T->isFunctionType() || T->isArrayType()) {
3115 // Decay functions and arrays.
3116 Expr *RefE = (Expr *)RefExpr.get();
3117 DefaultFunctionArrayConversion(RefE);
3118 if (RefE != RefExpr.get()) {
3119 RefExpr.release();
3120 RefExpr = Owned(RefE);
3121 }
3122
3123 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00003124 }
3125
Douglas Gregorb7a09262010-04-01 18:32:35 +00003126 // Take the address of everything else
John McCall2de56d12010-08-25 11:45:40 +00003127 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregor02024a92010-03-28 02:42:43 +00003128 }
3129
3130 // If the non-type template parameter has reference type, qualify the
3131 // resulting declaration reference with the extra qualifiers on the
3132 // type that the reference refers to.
3133 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3134 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3135
3136 return BuildDeclRefExpr(VD, T, Loc);
3137}
3138
3139/// \brief Construct a new expression that refers to the given
3140/// integral template argument with the given source-location
3141/// information.
3142///
3143/// This routine takes care of the mapping from an integral template
3144/// argument (which may have any integral type) to the appropriate
3145/// literal value.
John McCall60d7b3a2010-08-24 06:29:42 +00003146ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003147Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3148 SourceLocation Loc) {
3149 assert(Arg.getKind() == TemplateArgument::Integral &&
3150 "Operation is only value for integral template arguments");
3151 QualType T = Arg.getIntegralType();
3152 if (T->isCharType() || T->isWideCharType())
3153 return Owned(new (Context) CharacterLiteral(
3154 Arg.getAsIntegral()->getZExtValue(),
3155 T->isWideCharType(),
3156 T,
3157 Loc));
3158 if (T->isBooleanType())
3159 return Owned(new (Context) CXXBoolLiteralExpr(
3160 Arg.getAsIntegral()->getBoolValue(),
3161 T,
3162 Loc));
3163
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003164 return Owned(IntegerLiteral::Create(Context, *Arg.getAsIntegral(), T, Loc));
Douglas Gregor02024a92010-03-28 02:42:43 +00003165}
3166
3167
Douglas Gregorddc29e12009-02-06 22:42:48 +00003168/// \brief Determine whether the given template parameter lists are
3169/// equivalent.
3170///
Mike Stump1eb44332009-09-09 15:08:12 +00003171/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00003172/// source code as part of a new template declaration.
3173///
3174/// \param Old The old template parameter list, typically found via
3175/// name lookup of the template declared with this template parameter
3176/// list.
3177///
3178/// \param Complain If true, this routine will produce a diagnostic if
3179/// the template parameter lists are not equivalent.
3180///
Douglas Gregorfb898e12009-11-12 16:20:59 +00003181/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00003182///
3183/// \param TemplateArgLoc If this source location is valid, then we
3184/// are actually checking the template parameter list of a template
3185/// argument (New) against the template parameter list of its
3186/// corresponding template template parameter (Old). We produce
3187/// slightly different diagnostics in this scenario.
3188///
Douglas Gregorddc29e12009-02-06 22:42:48 +00003189/// \returns True if the template parameter lists are equal, false
3190/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003191bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00003192Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3193 TemplateParameterList *Old,
3194 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003195 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003196 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003197 if (Old->size() != New->size()) {
3198 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003199 unsigned NextDiag = diag::err_template_param_list_different_arity;
3200 if (TemplateArgLoc.isValid()) {
3201 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3202 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00003203 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003204 Diag(New->getTemplateLoc(), NextDiag)
3205 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00003206 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003207 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00003208 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003209 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003210 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3211 }
3212
3213 return false;
3214 }
3215
3216 for (TemplateParameterList::iterator OldParm = Old->begin(),
3217 OldParmEnd = Old->end(), NewParm = New->begin();
3218 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3219 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003220 if (Complain) {
3221 unsigned NextDiag = diag::err_template_param_different_kind;
3222 if (TemplateArgLoc.isValid()) {
3223 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3224 NextDiag = diag::note_template_param_different_kind;
3225 }
3226 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003227 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003228 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003229 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00003230 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003231 return false;
3232 }
3233
Douglas Gregora417b872010-06-04 08:34:32 +00003234 if (TemplateTypeParmDecl *OldTTP
3235 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3236 // Template type parameters are equivalent if either both are template
3237 // type parameter packs or neither are (since we know we're at the same
3238 // index).
3239 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3240 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3241 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3242 // allow one to match a template parameter pack in the template
3243 // parameter list of a template template parameter to one or more
3244 // template parameters in the template parameter list of the
3245 // corresponding template template argument.
3246 if (Complain) {
3247 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3248 if (TemplateArgLoc.isValid()) {
3249 Diag(TemplateArgLoc,
3250 diag::err_template_arg_template_params_mismatch);
3251 NextDiag = diag::note_template_parameter_pack_non_pack;
3252 }
3253 Diag(NewTTP->getLocation(), NextDiag)
3254 << 0 << NewTTP->isParameterPack();
3255 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3256 << 0 << OldTTP->isParameterPack();
3257 }
3258 return false;
3259 }
Mike Stump1eb44332009-09-09 15:08:12 +00003260 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003261 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3262 // The types of non-type template parameters must agree.
3263 NonTypeTemplateParmDecl *NewNTTP
3264 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00003265
3266 // If we are matching a template template argument to a template
3267 // template parameter and one of the non-type template parameter types
3268 // is dependent, then we must wait until template instantiation time
3269 // to actually compare the arguments.
3270 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3271 (OldNTTP->getType()->isDependentType() ||
3272 NewNTTP->getType()->isDependentType()))
3273 continue;
3274
Douglas Gregorddc29e12009-02-06 22:42:48 +00003275 if (Context.getCanonicalType(OldNTTP->getType()) !=
3276 Context.getCanonicalType(NewNTTP->getType())) {
3277 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003278 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3279 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003280 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003281 diag::err_template_arg_template_params_mismatch);
3282 NextDiag = diag::note_template_nontype_parm_different_type;
3283 }
3284 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003285 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00003286 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00003287 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00003288 diag::note_template_nontype_parm_prev_declaration)
3289 << OldNTTP->getType();
3290 }
3291 return false;
3292 }
3293 } else {
3294 // The template parameter lists of template template
3295 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00003296 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00003297 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00003298 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003299 = cast<TemplateTemplateParmDecl>(*OldParm);
3300 TemplateTemplateParmDecl *NewTTP
3301 = cast<TemplateTemplateParmDecl>(*NewParm);
3302 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3303 OldTTP->getTemplateParameters(),
3304 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003305 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00003306 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003307 return false;
3308 }
3309 }
3310
3311 return true;
3312}
3313
3314/// \brief Check whether a template can be declared within this scope.
3315///
3316/// If the template declaration is valid in this scope, returns
3317/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003318bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003319Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003320 // Find the nearest enclosing declaration scope.
3321 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3322 (S->getFlags() & Scope::TemplateParamScope) != 0)
3323 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003324
Douglas Gregorddc29e12009-02-06 22:42:48 +00003325 // C++ [temp]p2:
3326 // A template-declaration can appear only as a namespace scope or
3327 // class scope declaration.
3328 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003329 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3330 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003331 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003332 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003333
Eli Friedman1503f772009-07-31 01:43:05 +00003334 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003335 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003336
3337 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3338 return false;
3339
Mike Stump1eb44332009-09-09 15:08:12 +00003340 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003341 diag::err_template_outside_namespace_or_class_scope)
3342 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003343}
Douglas Gregorcc636682009-02-17 23:15:12 +00003344
Douglas Gregord5cb8762009-10-07 00:13:32 +00003345/// \brief Determine what kind of template specialization the given declaration
3346/// is.
3347static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3348 if (!D)
3349 return TSK_Undeclared;
3350
Douglas Gregorf6b11852009-10-08 15:14:33 +00003351 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3352 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003353 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3354 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003355 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3356 return Var->getTemplateSpecializationKind();
3357
Douglas Gregord5cb8762009-10-07 00:13:32 +00003358 return TSK_Undeclared;
3359}
3360
Douglas Gregor9302da62009-10-14 23:50:59 +00003361/// \brief Check whether a specialization is well-formed in the current
3362/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003363///
Douglas Gregor9302da62009-10-14 23:50:59 +00003364/// This routine determines whether a template specialization can be declared
3365/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003366///
3367/// \param S the semantic analysis object for which this check is being
3368/// performed.
3369///
3370/// \param Specialized the entity being specialized or instantiated, which
3371/// may be a kind of template (class template, function template, etc.) or
3372/// a member of a class template (member function, static data member,
3373/// member class).
3374///
3375/// \param PrevDecl the previous declaration of this entity, if any.
3376///
3377/// \param Loc the location of the explicit specialization or instantiation of
3378/// this entity.
3379///
3380/// \param IsPartialSpecialization whether this is a partial specialization of
3381/// a class template.
3382///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003383/// \returns true if there was an error that we cannot recover from, false
3384/// otherwise.
3385static bool CheckTemplateSpecializationScope(Sema &S,
3386 NamedDecl *Specialized,
3387 NamedDecl *PrevDecl,
3388 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003389 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003390 // Keep these "kind" numbers in sync with the %select statements in the
3391 // various diagnostics emitted by this routine.
3392 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003393 bool isTemplateSpecialization = false;
3394 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003395 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003396 isTemplateSpecialization = true;
3397 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003398 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003399 isTemplateSpecialization = true;
3400 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003401 EntityKind = 3;
3402 else if (isa<VarDecl>(Specialized))
3403 EntityKind = 4;
3404 else if (isa<RecordDecl>(Specialized))
3405 EntityKind = 5;
3406 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003407 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3408 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003409 return true;
3410 }
3411
Douglas Gregor88b70942009-02-25 22:02:03 +00003412 // C++ [temp.expl.spec]p2:
3413 // An explicit specialization shall be declared in the namespace
3414 // of which the template is a member, or, for member templates, in
3415 // the namespace of which the enclosing class or enclosing class
3416 // template is a member. An explicit specialization of a member
3417 // function, member class or static data member of a class
3418 // template shall be declared in the namespace of which the class
3419 // template is a member. Such a declaration may also be a
3420 // definition. If the declaration is not a definition, the
3421 // specialization may be defined later in the name- space in which
3422 // the explicit specialization was declared, or in a namespace
3423 // that encloses the one in which the explicit specialization was
3424 // declared.
Sebastian Redl7a126a42010-08-31 00:36:30 +00003425 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003426 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003427 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003428 return true;
3429 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003430
Douglas Gregor0a407472009-10-07 17:30:37 +00003431 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3432 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003433 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003434 return true;
3435 }
3436
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003437 // C++ [temp.class.spec]p6:
3438 // A class template partial specialization may be declared or redeclared
3439 // in any namespace scope in which its definition may be defined (14.5.1
3440 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003441 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003442 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003443 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003444 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003445 if ((!PrevDecl ||
3446 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3447 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregor121dc9a2010-09-12 05:08:28 +00003448 // C++ [temp.exp.spec]p2:
3449 // An explicit specialization shall be declared in the namespace of which
3450 // the template is a member, or, for member templates, in the namespace
3451 // of which the enclosing class or enclosing class template is a member.
3452 // An explicit specialization of a member function, member class or
3453 // static data member of a class template shall be declared in the
3454 // namespace of which the class template is a member.
3455 //
3456 // C++0x [temp.expl.spec]p2:
3457 // An explicit specialization shall be declared in a namespace enclosing
3458 // the specialized template.
3459 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
3460 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
Douglas Gregora4d5de52010-09-12 05:24:55 +00003461 bool IsCPlusPlus0xExtension
3462 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00003463 if (isa<TranslationUnitDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00003464 S.Diag(Loc, IsCPlusPlus0xExtension
3465 ? diag::ext_template_spec_decl_out_of_scope_global
3466 : diag::err_template_spec_decl_out_of_scope_global)
3467 << EntityKind << Specialized;
Douglas Gregor9302da62009-10-14 23:50:59 +00003468 else if (isa<NamespaceDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00003469 S.Diag(Loc, IsCPlusPlus0xExtension
3470 ? diag::ext_template_spec_decl_out_of_scope
3471 : diag::err_template_spec_decl_out_of_scope)
3472 << EntityKind << Specialized
3473 << cast<NamedDecl>(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00003474
3475 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3476 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003477 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003478 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003479
3480 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003481 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003482 // Note that HandleDeclarator() performs this check for explicit
3483 // specializations of function templates, static data members, and member
3484 // functions, so we skip the check here for those kinds of entities.
3485 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003486 // Should we refactor that check, so that it occurs later?
3487 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003488 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3489 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003490 if (isa<TranslationUnitDecl>(SpecializedContext))
3491 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3492 << EntityKind << Specialized;
3493 else if (isa<NamespaceDecl>(SpecializedContext))
3494 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3495 << EntityKind << Specialized
3496 << cast<NamedDecl>(SpecializedContext);
3497
Douglas Gregor9302da62009-10-14 23:50:59 +00003498 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003499 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003500
3501 // FIXME: check for specialization-after-instantiation errors and such.
3502
Douglas Gregor88b70942009-02-25 22:02:03 +00003503 return false;
3504}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003505
Douglas Gregore94866f2009-06-12 21:21:02 +00003506/// \brief Check the non-type template arguments of a class template
3507/// partial specialization according to C++ [temp.class.spec]p9.
3508///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003509/// \param TemplateParams the template parameters of the primary class
3510/// template.
3511///
3512/// \param TemplateArg the template arguments of the class template
3513/// partial specialization.
3514///
3515/// \param MirrorsPrimaryTemplate will be set true if the class
3516/// template partial specialization arguments are identical to the
3517/// implicit template arguments of the primary template. This is not
3518/// necessarily an error (C++0x), and it is left to the caller to diagnose
3519/// this condition when it is an error.
3520///
Douglas Gregore94866f2009-06-12 21:21:02 +00003521/// \returns true if there was an error, false otherwise.
3522bool Sema::CheckClassTemplatePartialSpecializationArgs(
3523 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00003524 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003525 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003526 // FIXME: the interface to this function will have to change to
3527 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003528 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003529
Anders Carlssonfb250522009-06-23 01:26:57 +00003530 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00003531
Douglas Gregore94866f2009-06-12 21:21:02 +00003532 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003533 // Determine whether the template argument list of the partial
3534 // specialization is identical to the implicit argument list of
3535 // the primary template. The caller may need to diagnostic this as
3536 // an error per C++ [temp.class.spec]p9b3.
3537 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003538 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003539 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3540 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003541 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003542 MirrorsPrimaryTemplate = false;
3543 } else if (TemplateTemplateParmDecl *TTP
3544 = dyn_cast<TemplateTemplateParmDecl>(
3545 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003546 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003547 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003548 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003549 if (!ArgDecl ||
3550 ArgDecl->getIndex() != TTP->getIndex() ||
3551 ArgDecl->getDepth() != TTP->getDepth())
3552 MirrorsPrimaryTemplate = false;
3553 }
3554 }
3555
Mike Stump1eb44332009-09-09 15:08:12 +00003556 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003557 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003558 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003559 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003560 }
3561
Anders Carlsson6360be72009-06-13 18:20:51 +00003562 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003563 if (!ArgExpr) {
3564 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003565 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003566 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003567
3568 // C++ [temp.class.spec]p8:
3569 // A non-type argument is non-specialized if it is the name of a
3570 // non-type parameter. All other non-type arguments are
3571 // specialized.
3572 //
3573 // Below, we check the two conditions that only apply to
3574 // specialized non-type arguments, so skip any non-specialized
3575 // arguments.
3576 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003577 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003578 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003579 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003580 (Param->getIndex() != NTTP->getIndex() ||
3581 Param->getDepth() != NTTP->getDepth()))
3582 MirrorsPrimaryTemplate = false;
3583
Douglas Gregore94866f2009-06-12 21:21:02 +00003584 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003585 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003586
3587 // C++ [temp.class.spec]p9:
3588 // Within the argument list of a class template partial
3589 // specialization, the following restrictions apply:
3590 // -- A partially specialized non-type argument expression
3591 // shall not involve a template parameter of the partial
3592 // specialization except when the argument expression is a
3593 // simple identifier.
3594 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003595 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003596 diag::err_dependent_non_type_arg_in_partial_spec)
3597 << ArgExpr->getSourceRange();
3598 return true;
3599 }
3600
3601 // -- The type of a template parameter corresponding to a
3602 // specialized non-type argument shall not be dependent on a
3603 // parameter of the specialization.
3604 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003605 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003606 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3607 << Param->getType()
3608 << ArgExpr->getSourceRange();
3609 Diag(Param->getLocation(), diag::note_template_param_here);
3610 return true;
3611 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003612
3613 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003614 }
3615
3616 return false;
3617}
3618
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003619/// \brief Retrieve the previous declaration of the given declaration.
3620static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3621 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3622 return VD->getPreviousDeclaration();
3623 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3624 return FD->getPreviousDeclaration();
3625 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3626 return TD->getPreviousDeclaration();
3627 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3628 return TD->getPreviousDeclaration();
3629 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3630 return FTD->getPreviousDeclaration();
3631 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3632 return CTD->getPreviousDeclaration();
3633 return 0;
3634}
3635
John McCalld226f652010-08-21 09:40:31 +00003636DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003637Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3638 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00003639 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003640 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003641 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00003642 SourceLocation TemplateNameLoc,
3643 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00003644 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00003645 SourceLocation RAngleLoc,
3646 AttributeList *Attr,
3647 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003648 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00003649
Douglas Gregorcc636682009-02-17 23:15:12 +00003650 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00003651 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003652 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00003653 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3654
3655 if (!ClassTemplate) {
3656 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3657 << (Name.getAsTemplateDecl() &&
3658 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3659 return true;
3660 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003661
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003662 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003663 bool isPartialSpecialization = false;
3664
Douglas Gregor88b70942009-02-25 22:02:03 +00003665 // Check the validity of the template headers that introduce this
3666 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003667 // FIXME: We probably shouldn't complain about these headers for
3668 // friend declarations.
Douglas Gregor0167f3c2010-07-14 23:14:12 +00003669 bool Invalid = false;
Douglas Gregor05396e22009-08-25 17:23:04 +00003670 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00003671 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3672 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003673 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00003674 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00003675 isExplicitSpecialization,
3676 Invalid);
3677 if (Invalid)
3678 return true;
3679
Abramo Bagnara9b934882010-06-12 08:15:14 +00003680 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3681 if (TemplateParams)
3682 --NumMatchedTemplateParamLists;
3683
Douglas Gregor05396e22009-08-25 17:23:04 +00003684 if (TemplateParams && TemplateParams->size() > 0) {
3685 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003686
Douglas Gregor05396e22009-08-25 17:23:04 +00003687 // C++ [temp.class.spec]p10:
3688 // The template parameter list of a specialization shall not
3689 // contain default template argument values.
3690 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3691 Decl *Param = TemplateParams->getParam(I);
3692 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3693 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003694 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003695 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00003696 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003697 }
3698 } else if (NonTypeTemplateParmDecl *NTTP
3699 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3700 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003701 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003702 diag::err_default_arg_in_partial_spec)
3703 << DefArg->getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00003704 NTTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003705 }
3706 } else {
3707 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003708 if (TTP->hasDefaultArgument()) {
3709 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003710 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003711 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00003712 TTP->removeDefaultArgument();
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003713 }
3714 }
3715 }
Douglas Gregora735b202009-10-13 14:39:41 +00003716 } else if (TemplateParams) {
3717 if (TUK == TUK_Friend)
3718 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00003719 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00003720 SourceRange(TemplateParams->getTemplateLoc(),
3721 TemplateParams->getRAngleLoc()))
3722 << SourceRange(LAngleLoc, RAngleLoc);
3723 else
3724 isExplicitSpecialization = true;
3725 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003726 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00003727 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003728 isExplicitSpecialization = true;
3729 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003730
Douglas Gregorcc636682009-02-17 23:15:12 +00003731 // Check that the specialization uses the same tag kind as the
3732 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003733 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3734 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003735 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003736 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003737 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003738 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003739 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00003740 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003741 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003742 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003743 diag::note_previous_use);
3744 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3745 }
3746
Douglas Gregor40808ce2009-03-09 23:48:35 +00003747 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00003748 TemplateArgumentListInfo TemplateArgs;
3749 TemplateArgs.setLAngleLoc(LAngleLoc);
3750 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00003751 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003752
Douglas Gregorcc636682009-02-17 23:15:12 +00003753 // Check that the template argument list is well-formed for this
3754 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003755 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3756 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00003757 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3758 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003759 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003760
Mike Stump1eb44332009-09-09 15:08:12 +00003761 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003762 ClassTemplate->getTemplateParameters()->size()) &&
3763 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003764
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003765 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003766 // corresponds to these arguments.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003767 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003768 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003769 if (CheckClassTemplatePartialSpecializationArgs(
3770 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003771 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003772 return true;
3773
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003774 if (MirrorsPrimaryTemplate) {
3775 // C++ [temp.class.spec]p9b3:
3776 //
Mike Stump1eb44332009-09-09 15:08:12 +00003777 // -- The argument list of the specialization shall not be identical
3778 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003779 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003780 << (TUK == TUK_Definition)
Douglas Gregor849b2432010-03-31 17:46:05 +00003781 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003782 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003783 ClassTemplate->getIdentifier(),
3784 TemplateNameLoc,
3785 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003786 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003787 AS_none);
3788 }
3789
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003790 // FIXME: Diagnose friend partial specializations
3791
Douglas Gregorde090962010-02-09 00:37:32 +00003792 if (!Name.isDependent() &&
3793 !TemplateSpecializationType::anyDependentTemplateArguments(
3794 TemplateArgs.getArgumentArray(),
3795 TemplateArgs.size())) {
3796 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3797 << ClassTemplate->getDeclName();
3798 isPartialSpecialization = false;
Douglas Gregorde090962010-02-09 00:37:32 +00003799 }
3800 }
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00003801
Douglas Gregorcc636682009-02-17 23:15:12 +00003802 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003803 ClassTemplateSpecializationDecl *PrevDecl = 0;
3804
3805 if (isPartialSpecialization)
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00003806 // FIXME: Template parameter list matters, too
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003807 PrevDecl
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00003808 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
3809 Converted.flatSize(),
3810 InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003811 else
3812 PrevDecl
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00003813 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
3814 Converted.flatSize(), InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003815
3816 ClassTemplateSpecializationDecl *Specialization = 0;
3817
Douglas Gregor88b70942009-02-25 22:02:03 +00003818 // Check whether we can declare a class template specialization in
3819 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003820 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003821 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003822 TemplateNameLoc,
3823 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003824 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003825
Douglas Gregorb88e8882009-07-30 17:40:51 +00003826 // The canonical type
3827 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003828 if (PrevDecl &&
3829 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00003830 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003831 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003832 // arguments was referenced but not declared, or we're only
3833 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003834 // declaration node as our own, updating its source location to
3835 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003836 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003837 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003838 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003839 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003840 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003841 // Build the canonical type that describes the converted template
3842 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00003843 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3844 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb88e8882009-07-30 17:40:51 +00003845 Converted.getFlatArguments(),
3846 Converted.flatSize());
3847
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003848 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003849 ClassTemplatePartialSpecializationDecl *PrevPartial
3850 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00003851 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00003852 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump1eb44332009-09-09 15:08:12 +00003853 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00003854 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003855 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003856 TemplateNameLoc,
3857 TemplateParams,
3858 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003859 Converted,
John McCalld5532b62009-11-23 01:53:49 +00003860 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00003861 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00003862 PrevPartial,
3863 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00003864 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00003865 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00003866 Partial->setTemplateParameterListsInfo(Context,
3867 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00003868 (TemplateParameterList**) TemplateParameterLists.release());
3869 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003870
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00003871 if (!PrevPartial)
3872 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003873 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003874
Douglas Gregored9c0f92009-10-29 00:04:11 +00003875 // If we are providing an explicit specialization of a member class
3876 // template specialization, make a note of that.
3877 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3878 PrevPartial->setMemberSpecialization();
3879
Douglas Gregor031a5882009-06-13 00:26:55 +00003880 // Check that all of the template parameters of the class template
3881 // partial specialization are deducible from the template
3882 // arguments. If not, this class template partial specialization
3883 // will never be used.
3884 llvm::SmallVector<bool, 8> DeducibleParams;
3885 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003886 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003887 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003888 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003889 unsigned NumNonDeducible = 0;
3890 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3891 if (!DeducibleParams[I])
3892 ++NumNonDeducible;
3893
3894 if (NumNonDeducible) {
3895 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3896 << (NumNonDeducible > 1)
3897 << SourceRange(TemplateNameLoc, RAngleLoc);
3898 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3899 if (!DeducibleParams[I]) {
3900 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3901 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003902 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003903 diag::note_partial_spec_unused_parameter)
3904 << Param->getDeclName();
3905 else
Mike Stump1eb44332009-09-09 15:08:12 +00003906 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003907 diag::note_partial_spec_unused_parameter)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00003908 << "<anonymous>";
Douglas Gregor031a5882009-06-13 00:26:55 +00003909 }
3910 }
3911 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003912 } else {
3913 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003914 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003915 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00003916 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00003917 ClassTemplate->getDeclContext(),
3918 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003919 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003920 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003921 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00003922 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00003923 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00003924 Specialization->setTemplateParameterListsInfo(Context,
3925 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00003926 (TemplateParameterList**) TemplateParameterLists.release());
3927 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003928
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00003929 if (!PrevDecl)
3930 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregorb88e8882009-07-30 17:40:51 +00003931
3932 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003933 }
3934
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003935 // C++ [temp.expl.spec]p6:
3936 // If a template, a member template or the member of a class template is
3937 // explicitly specialized then that specialization shall be declared
3938 // before the first use of that specialization that would cause an implicit
3939 // instantiation to take place, in every translation unit in which such a
3940 // use occurs; no diagnostic is required.
3941 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003942 bool Okay = false;
3943 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3944 // Is there any previous explicit specialization declaration?
3945 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3946 Okay = true;
3947 break;
3948 }
3949 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003950
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003951 if (!Okay) {
3952 SourceRange Range(TemplateNameLoc, RAngleLoc);
3953 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3954 << Context.getTypeDeclType(Specialization) << Range;
3955
3956 Diag(PrevDecl->getPointOfInstantiation(),
3957 diag::note_instantiation_required_here)
3958 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003959 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003960 return true;
3961 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003962 }
3963
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003964 // If this is not a friend, note that this is an explicit specialization.
3965 if (TUK != TUK_Friend)
3966 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003967
3968 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003969 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00003970 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003971 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003972 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003973 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003974 Diag(Def->getLocation(), diag::note_previous_definition);
3975 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003976 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003977 }
3978 }
3979
Douglas Gregorfc705b82009-02-26 22:19:44 +00003980 // Build the fully-sugared type for this class template
3981 // specialization as the user wrote in the specialization
3982 // itself. This means that we'll pretty-print the type retrieved
3983 // from the specialization's declaration the way that the user
3984 // actually wrote the specialization, rather than formatting the
3985 // name based on the "canonical" representation used to store the
3986 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00003987 TypeSourceInfo *WrittenTy
3988 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3989 TemplateArgs, CanonType);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00003990 if (TUK != TUK_Friend) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003991 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor7e9b57b2010-07-06 18:33:12 +00003992 if (TemplateParams)
3993 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnarac98971d2010-06-12 07:44:57 +00003994 }
Douglas Gregor40808ce2009-03-09 23:48:35 +00003995 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00003996
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003997 // C++ [temp.expl.spec]p9:
3998 // A template explicit specialization is in the scope of the
3999 // namespace in which the template was defined.
4000 //
4001 // We actually implement this paragraph where we set the semantic
4002 // context (in the creation of the ClassTemplateSpecializationDecl),
4003 // but we also maintain the lexical context where the actual
4004 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00004005 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004006
Douglas Gregorcc636682009-02-17 23:15:12 +00004007 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004008 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00004009 Specialization->startDefinition();
4010
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004011 if (TUK == TUK_Friend) {
4012 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4013 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00004014 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004015 /*FIXME:*/KWLoc);
4016 Friend->setAccess(AS_public);
4017 CurContext->addDecl(Friend);
4018 } else {
4019 // Add the specialization into its lexical context, so that it can
4020 // be seen when iterating through the list of declarations in that
4021 // context. However, specializations are not found by name lookup.
4022 CurContext->addDecl(Specialization);
4023 }
John McCalld226f652010-08-21 09:40:31 +00004024 return Specialization;
Douglas Gregorcc636682009-02-17 23:15:12 +00004025}
Douglas Gregord57959a2009-03-27 23:10:48 +00004026
John McCalld226f652010-08-21 09:40:31 +00004027Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00004028 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004029 Declarator &D) {
Douglas Gregore542c862009-06-23 23:11:28 +00004030 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4031}
4032
John McCalld226f652010-08-21 09:40:31 +00004033Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00004034 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004035 Declarator &D) {
Douglas Gregor52591bf2009-06-24 00:54:41 +00004036 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4037 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4038 "Not a function declarator!");
4039 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00004040
Douglas Gregor52591bf2009-06-24 00:54:41 +00004041 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00004042 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00004043 }
Mike Stump1eb44332009-09-09 15:08:12 +00004044
Douglas Gregor52591bf2009-06-24 00:54:41 +00004045 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004046
John McCalld226f652010-08-21 09:40:31 +00004047 Decl *DP = HandleDeclarator(ParentScope, D,
4048 move(TemplateParameterLists),
4049 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004050 if (FunctionTemplateDecl *FunctionTemplate
John McCalld226f652010-08-21 09:40:31 +00004051 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump1eb44332009-09-09 15:08:12 +00004052 return ActOnStartOfFunctionDef(FnBodyScope,
John McCalld226f652010-08-21 09:40:31 +00004053 FunctionTemplate->getTemplatedDecl());
4054 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4055 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4056 return 0;
Douglas Gregor52591bf2009-06-24 00:54:41 +00004057}
4058
John McCall75042392010-02-11 01:33:53 +00004059/// \brief Strips various properties off an implicit instantiation
4060/// that has just been explicitly specialized.
4061static void StripImplicitInstantiation(NamedDecl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00004062 D->dropAttrs();
John McCall75042392010-02-11 01:33:53 +00004063
4064 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4065 FD->setInlineSpecified(false);
4066 }
4067}
4068
Douglas Gregor454885e2009-10-15 15:54:05 +00004069/// \brief Diagnose cases where we have an explicit template specialization
4070/// before/after an explicit template instantiation, producing diagnostics
4071/// for those cases where they are required and determining whether the
4072/// new specialization/instantiation will have any effect.
4073///
Douglas Gregor454885e2009-10-15 15:54:05 +00004074/// \param NewLoc the location of the new explicit specialization or
4075/// instantiation.
4076///
4077/// \param NewTSK the kind of the new explicit specialization or instantiation.
4078///
4079/// \param PrevDecl the previous declaration of the entity.
4080///
4081/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4082///
4083/// \param PrevPointOfInstantiation if valid, indicates where the previus
4084/// declaration was instantiated (either implicitly or explicitly).
4085///
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004086/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregor454885e2009-10-15 15:54:05 +00004087/// specialization or instantiation has no effect and should be ignored.
4088///
4089/// \returns true if there was an error that should prevent the introduction of
4090/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00004091bool
4092Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4093 TemplateSpecializationKind NewTSK,
4094 NamedDecl *PrevDecl,
4095 TemplateSpecializationKind PrevTSK,
4096 SourceLocation PrevPointOfInstantiation,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004097 bool &HasNoEffect) {
4098 HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00004099
4100 switch (NewTSK) {
4101 case TSK_Undeclared:
4102 case TSK_ImplicitInstantiation:
4103 assert(false && "Don't check implicit instantiations here");
4104 return false;
4105
4106 case TSK_ExplicitSpecialization:
4107 switch (PrevTSK) {
4108 case TSK_Undeclared:
4109 case TSK_ExplicitSpecialization:
4110 // Okay, we're just specializing something that is either already
4111 // explicitly specialized or has merely been mentioned without any
4112 // instantiation.
4113 return false;
4114
4115 case TSK_ImplicitInstantiation:
4116 if (PrevPointOfInstantiation.isInvalid()) {
4117 // The declaration itself has not actually been instantiated, so it is
4118 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00004119 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00004120 return false;
4121 }
4122 // Fall through
4123
4124 case TSK_ExplicitInstantiationDeclaration:
4125 case TSK_ExplicitInstantiationDefinition:
4126 assert((PrevTSK == TSK_ImplicitInstantiation ||
4127 PrevPointOfInstantiation.isValid()) &&
4128 "Explicit instantiation without point of instantiation?");
4129
4130 // C++ [temp.expl.spec]p6:
4131 // If a template, a member template or the member of a class template
4132 // is explicitly specialized then that specialization shall be declared
4133 // before the first use of that specialization that would cause an
4134 // implicit instantiation to take place, in every translation unit in
4135 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004136 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4137 // Is there any previous explicit specialization declaration?
4138 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4139 return false;
4140 }
4141
Douglas Gregor0d035142009-10-27 18:42:08 +00004142 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00004143 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004144 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00004145 << (PrevTSK != TSK_ImplicitInstantiation);
4146
4147 return true;
4148 }
4149 break;
4150
4151 case TSK_ExplicitInstantiationDeclaration:
4152 switch (PrevTSK) {
4153 case TSK_ExplicitInstantiationDeclaration:
4154 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004155 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004156 return false;
4157
4158 case TSK_Undeclared:
4159 case TSK_ImplicitInstantiation:
4160 // We're explicitly instantiating something that may have already been
4161 // implicitly instantiated; that's fine.
4162 return false;
4163
4164 case TSK_ExplicitSpecialization:
4165 // C++0x [temp.explicit]p4:
4166 // For a given set of template parameters, if an explicit instantiation
4167 // of a template appears after a declaration of an explicit
4168 // specialization for that template, the explicit instantiation has no
4169 // effect.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004170 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004171 return false;
4172
4173 case TSK_ExplicitInstantiationDefinition:
4174 // C++0x [temp.explicit]p10:
4175 // If an entity is the subject of both an explicit instantiation
4176 // declaration and an explicit instantiation definition in the same
4177 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00004178 Diag(NewLoc,
4179 diag::err_explicit_instantiation_declaration_after_definition);
4180 Diag(PrevPointOfInstantiation,
4181 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00004182 assert(PrevPointOfInstantiation.isValid() &&
4183 "Explicit instantiation without point of instantiation?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004184 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004185 return false;
4186 }
4187 break;
4188
4189 case TSK_ExplicitInstantiationDefinition:
4190 switch (PrevTSK) {
4191 case TSK_Undeclared:
4192 case TSK_ImplicitInstantiation:
4193 // We're explicitly instantiating something that may have already been
4194 // implicitly instantiated; that's fine.
4195 return false;
4196
4197 case TSK_ExplicitSpecialization:
4198 // C++ DR 259, C++0x [temp.explicit]p4:
4199 // For a given set of template parameters, if an explicit
4200 // instantiation of a template appears after a declaration of
4201 // an explicit specialization for that template, the explicit
4202 // instantiation has no effect.
4203 //
4204 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00004205 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00004206 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00004207 if (!getLangOptions().CPlusPlus0x) {
4208 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00004209 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004210 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00004211 diag::note_previous_template_specialization);
4212 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004213 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004214 return false;
4215
4216 case TSK_ExplicitInstantiationDeclaration:
4217 // We're explicity instantiating a definition for something for which we
4218 // were previously asked to suppress instantiations. That's fine.
4219 return false;
4220
4221 case TSK_ExplicitInstantiationDefinition:
4222 // C++0x [temp.spec]p5:
4223 // For a given template and a given set of template-arguments,
4224 // - an explicit instantiation definition shall appear at most once
4225 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00004226 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00004227 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004228 Diag(PrevPointOfInstantiation,
4229 diag::note_previous_explicit_instantiation);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004230 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004231 return false;
4232 }
4233 break;
4234 }
4235
4236 assert(false && "Missing specialization/instantiation case?");
4237
4238 return false;
4239}
4240
John McCallaf2094e2010-04-08 09:05:18 +00004241/// \brief Perform semantic analysis for the given dependent function
4242/// template specialization. The only possible way to get a dependent
4243/// function template specialization is with a friend declaration,
4244/// like so:
4245///
4246/// template <class T> void foo(T);
4247/// template <class T> class A {
4248/// friend void foo<>(T);
4249/// };
4250///
4251/// There really isn't any useful analysis we can do here, so we
4252/// just store the information.
4253bool
4254Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4255 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4256 LookupResult &Previous) {
4257 // Remove anything from Previous that isn't a function template in
4258 // the correct context.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004259 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallaf2094e2010-04-08 09:05:18 +00004260 LookupResult::Filter F = Previous.makeFilter();
4261 while (F.hasNext()) {
4262 NamedDecl *D = F.next()->getUnderlyingDecl();
4263 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl7a126a42010-08-31 00:36:30 +00004264 !FDLookupContext->InEnclosingNamespaceSetOf(
4265 D->getDeclContext()->getRedeclContext()))
John McCallaf2094e2010-04-08 09:05:18 +00004266 F.erase();
4267 }
4268 F.done();
4269
4270 // Should this be diagnosed here?
4271 if (Previous.empty()) return true;
4272
4273 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4274 ExplicitTemplateArgs);
4275 return false;
4276}
4277
Abramo Bagnarae03db982010-05-20 15:32:11 +00004278/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004279/// specialization.
4280///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004281/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004282/// explicit function template specialization. On successful completion,
4283/// the function declaration \p FD will become a function template
4284/// specialization.
4285///
4286/// \param FD the function declaration, which will be updated to become a
4287/// function template specialization.
4288///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004289/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4290/// if any. Note that this may be valid info even when 0 arguments are
4291/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4292/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004293///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004294/// \param PrevDecl the set of declarations that may be specialized by
4295/// this function specialization.
4296bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004297Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004298 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004299 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004300 // The set of function template specializations that could match this
4301 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004302 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004303
Sebastian Redl7a126a42010-08-31 00:36:30 +00004304 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall68263142009-11-18 22:49:29 +00004305 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4306 I != E; ++I) {
4307 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4308 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004309 // Only consider templates found within the same semantic lookup scope as
4310 // FD.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004311 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4312 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004313 continue;
4314
4315 // C++ [temp.expl.spec]p11:
4316 // A trailing template-argument can be left unspecified in the
4317 // template-id naming an explicit function template specialization
4318 // provided it can be deduced from the function argument type.
4319 // Perform template argument deduction to determine whether we may be
4320 // specializing this template.
4321 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004322 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004323 FunctionDecl *Specialization = 0;
4324 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004325 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004326 FD->getType(),
4327 Specialization,
4328 Info)) {
4329 // FIXME: Template argument deduction failed; record why it failed, so
4330 // that we can provide nifty diagnostics.
4331 (void)TDK;
4332 continue;
4333 }
4334
4335 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004336 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004337 }
4338 }
4339
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004340 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004341 UnresolvedSetIterator Result
4342 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4343 TPOC_Other, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004344 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004345 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004346 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004347 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004348 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004349 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004350 return true;
John McCallc373d482010-01-27 01:50:18 +00004351
4352 // Ignore access information; it doesn't figure into redeclaration checking.
4353 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorc42b6522010-04-09 21:02:29 +00004354 Specialization->setLocation(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004355
4356 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004357 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004358
4359 // If this is a friend declaration, then we're not really declaring
4360 // an explicit specialization.
4361 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004362
Douglas Gregord5cb8762009-10-07 00:13:32 +00004363 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004364 if (!isFriend &&
4365 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004366 Specialization->getPrimaryTemplate(),
4367 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004368 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004369 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004370
4371 // C++ [temp.expl.spec]p6:
4372 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004373 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004374 // before the first use of that specialization that would cause an implicit
4375 // instantiation to take place, in every translation unit in which such a
4376 // use occurs; no diagnostic is required.
4377 FunctionTemplateSpecializationInfo *SpecInfo
4378 = Specialization->getTemplateSpecializationInfo();
4379 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004380
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004381 bool HasNoEffect = false;
John McCall7ad650f2010-03-24 07:46:06 +00004382 if (!isFriend &&
4383 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004384 TSK_ExplicitSpecialization,
4385 Specialization,
4386 SpecInfo->getTemplateSpecializationKind(),
4387 SpecInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004388 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004389 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004390
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004391 // Mark the prior declaration as an explicit specialization, so that later
4392 // clients know that this is an explicit specialization.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004393 if (!isFriend) {
John McCall7ad650f2010-03-24 07:46:06 +00004394 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004395 MarkUnusedFileScopedDecl(Specialization);
4396 }
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004397
4398 // Turn the given function declaration into a function template
4399 // specialization, with the template arguments from the previous
4400 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00004401 // Take copies of (semantic and syntactic) template argument lists.
4402 const TemplateArgumentList* TemplArgs = new (Context)
4403 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4404 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4405 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregor838db382010-02-11 01:19:42 +00004406 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00004407 TemplArgs, /*InsertPos=*/0,
4408 SpecInfo->getTemplateSpecializationKind(),
4409 TemplArgsAsWritten);
4410
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004411 // The "previous declaration" for this function template specialization is
4412 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004413 Previous.clear();
4414 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004415 return false;
4416}
4417
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004418/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004419/// specialization.
4420///
4421/// This routine performs all of the semantic analysis required for an
4422/// explicit member function specialization. On successful completion,
4423/// the function declaration \p FD will become a member function
4424/// specialization.
4425///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004426/// \param Member the member declaration, which will be updated to become a
4427/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004428///
John McCall68263142009-11-18 22:49:29 +00004429/// \param Previous the set of declarations, one of which may be specialized
4430/// by this function specialization; the set will be modified to contain the
4431/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004432bool
John McCall68263142009-11-18 22:49:29 +00004433Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004434 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00004435
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004436 // Try to find the member we are instantiating.
4437 NamedDecl *Instantiation = 0;
4438 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004439 MemberSpecializationInfo *MSInfo = 0;
4440
John McCall68263142009-11-18 22:49:29 +00004441 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004442 // Nowhere to look anyway.
4443 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004444 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4445 I != E; ++I) {
4446 NamedDecl *D = (*I)->getUnderlyingDecl();
4447 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004448 if (Context.hasSameType(Function->getType(), Method->getType())) {
4449 Instantiation = Method;
4450 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004451 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004452 break;
4453 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004454 }
4455 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004456 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004457 VarDecl *PrevVar;
4458 if (Previous.isSingleResult() &&
4459 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004460 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004461 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004462 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004463 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004464 }
4465 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004466 CXXRecordDecl *PrevRecord;
4467 if (Previous.isSingleResult() &&
4468 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4469 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004470 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004471 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004472 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004473 }
4474
4475 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004476 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004477 // specializations are always out-of-line, the caller will complain about
4478 // this mismatch later.
4479 return false;
4480 }
John McCall77e8b112010-04-13 20:37:33 +00004481
4482 // If this is a friend, just bail out here before we start turning
4483 // things into explicit specializations.
4484 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4485 // Preserve instantiation information.
4486 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4487 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4488 cast<CXXMethodDecl>(InstantiatedFrom),
4489 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4490 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4491 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4492 cast<CXXRecordDecl>(InstantiatedFrom),
4493 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4494 }
4495
4496 Previous.clear();
4497 Previous.addDecl(Instantiation);
4498 return false;
4499 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004500
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004501 // Make sure that this is a specialization of a member.
4502 if (!InstantiatedFrom) {
4503 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4504 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004505 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4506 return true;
4507 }
4508
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004509 // C++ [temp.expl.spec]p6:
4510 // If a template, a member template or the member of a class template is
4511 // explicitly specialized then that spe- cialization shall be declared
4512 // before the first use of that specialization that would cause an implicit
4513 // instantiation to take place, in every translation unit in which such a
4514 // use occurs; no diagnostic is required.
4515 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004516
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004517 bool HasNoEffect = false;
John McCall75042392010-02-11 01:33:53 +00004518 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4519 TSK_ExplicitSpecialization,
4520 Instantiation,
4521 MSInfo->getTemplateSpecializationKind(),
4522 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004523 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004524 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004525
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004526 // Check the scope of this explicit specialization.
4527 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004528 InstantiatedFrom,
4529 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004530 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004531 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004532
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004533 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004534 // the original declaration to note that it is an explicit specialization
4535 // (if it was previously an implicit instantiation). This latter step
4536 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004537 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004538 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4539 if (InstantiationFunction->getTemplateSpecializationKind() ==
4540 TSK_ImplicitInstantiation) {
4541 InstantiationFunction->setTemplateSpecializationKind(
4542 TSK_ExplicitSpecialization);
4543 InstantiationFunction->setLocation(Member->getLocation());
4544 }
4545
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004546 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4547 cast<CXXMethodDecl>(InstantiatedFrom),
4548 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004549 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004550 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004551 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4552 if (InstantiationVar->getTemplateSpecializationKind() ==
4553 TSK_ImplicitInstantiation) {
4554 InstantiationVar->setTemplateSpecializationKind(
4555 TSK_ExplicitSpecialization);
4556 InstantiationVar->setLocation(Member->getLocation());
4557 }
4558
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004559 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4560 cast<VarDecl>(InstantiatedFrom),
4561 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004562 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004563 } else {
4564 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004565 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4566 if (InstantiationClass->getTemplateSpecializationKind() ==
4567 TSK_ImplicitInstantiation) {
4568 InstantiationClass->setTemplateSpecializationKind(
4569 TSK_ExplicitSpecialization);
4570 InstantiationClass->setLocation(Member->getLocation());
4571 }
4572
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004573 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004574 cast<CXXRecordDecl>(InstantiatedFrom),
4575 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004576 }
4577
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004578 // Save the caller the trouble of having to figure out which declaration
4579 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004580 Previous.clear();
4581 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004582 return false;
4583}
4584
Douglas Gregor558c0322009-10-14 23:41:34 +00004585/// \brief Check the scope of an explicit instantiation.
Douglas Gregor669eed82010-07-13 00:10:04 +00004586///
4587/// \returns true if a serious error occurs, false otherwise.
4588static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregor558c0322009-10-14 23:41:34 +00004589 SourceLocation InstLoc,
4590 bool WasQualifiedName) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00004591 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
4592 DeclContext *CurContext = S.CurContext->getRedeclContext();
Douglas Gregor558c0322009-10-14 23:41:34 +00004593
Douglas Gregor669eed82010-07-13 00:10:04 +00004594 if (CurContext->isRecord()) {
4595 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4596 << D;
4597 return true;
4598 }
4599
Douglas Gregor558c0322009-10-14 23:41:34 +00004600 // 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 &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004606 !CurContext->Encloses(OrigContext)) {
4607 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
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);
Douglas Gregor669eed82010-07-13 00:10:04 +00004620 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00004621 }
Sebastian Redl7a126a42010-08-31 00:36:30 +00004622
Douglas Gregor558c0322009-10-14 23:41:34 +00004623 // 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)
Douglas Gregor669eed82010-07-13 00:10:04 +00004629 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00004630
4631 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
Douglas Gregor669eed82010-07-13 00:10:04 +00004632 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00004633
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)
Sebastian Redl7a126a42010-08-31 00:36:30 +00004638 << D << OrigContext;
Douglas Gregor558c0322009-10-14 23:41:34 +00004639 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00004640 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00004641}
4642
4643/// \brief Determine whether the given scope specifier has a template-id in it.
4644static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4645 if (!SS.isSet())
4646 return false;
4647
4648 // C++0x [temp.explicit]p2:
4649 // If the explicit instantiation is for a member function, a member class
4650 // or a static data member of a class template specialization, the name of
4651 // the class template specialization in the qualified-id for the member
4652 // name shall be a simple-template-id.
4653 //
4654 // C++98 has the same restriction, just worded differently.
4655 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4656 NNS; NNS = NNS->getPrefix())
4657 if (Type *T = NNS->getAsType())
4658 if (isa<TemplateSpecializationType>(T))
4659 return true;
4660
4661 return false;
4662}
4663
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004664// Explicit instantiation of a class template specialization
John McCallf312b1e2010-08-26 23:41:50 +00004665DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004666Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004667 SourceLocation ExternLoc,
4668 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004669 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004670 SourceLocation KWLoc,
4671 const CXXScopeSpec &SS,
4672 TemplateTy TemplateD,
4673 SourceLocation TemplateNameLoc,
4674 SourceLocation LAngleLoc,
4675 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004676 SourceLocation RAngleLoc,
4677 AttributeList *Attr) {
4678 // Find the class template we're specializing
4679 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004680 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004681 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4682
4683 // Check that the specialization uses the same tag kind as the
4684 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004685 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4686 assert(Kind != TTK_Enum &&
4687 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004688 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004689 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004690 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004691 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004692 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004693 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004694 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004695 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004696 diag::note_previous_use);
4697 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4698 }
4699
Douglas Gregor558c0322009-10-14 23:41:34 +00004700 // C++0x [temp.explicit]p2:
4701 // There are two forms of explicit instantiation: an explicit instantiation
4702 // definition and an explicit instantiation declaration. An explicit
4703 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00004704 TemplateSpecializationKind TSK
4705 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4706 : TSK_ExplicitInstantiationDeclaration;
4707
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004708 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004709 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004710 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004711
4712 // Check that the template argument list is well-formed for this
4713 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00004714 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4715 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00004716 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4717 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004718 return true;
4719
Mike Stump1eb44332009-09-09 15:08:12 +00004720 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004721 ClassTemplate->getTemplateParameters()->size()) &&
4722 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004723
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004724 // Find the class template specialization declaration that
4725 // corresponds to these arguments.
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004726 void *InsertPos = 0;
4727 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004728 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4729 Converted.flatSize(), InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004730
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004731 TemplateSpecializationKind PrevDecl_TSK
4732 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4733
Douglas Gregord5cb8762009-10-07 00:13:32 +00004734 // C++0x [temp.explicit]p2:
4735 // [...] An explicit instantiation shall appear in an enclosing
4736 // namespace of its template. [...]
4737 //
4738 // This is C++ DR 275.
Douglas Gregor669eed82010-07-13 00:10:04 +00004739 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4740 SS.isSet()))
4741 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004742
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004743 ClassTemplateSpecializationDecl *Specialization = 0;
4744
Douglas Gregord78f5982009-11-25 06:01:46 +00004745 bool ReusedDecl = false;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004746 bool HasNoEffect = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004747 if (PrevDecl) {
Douglas Gregor0d035142009-10-27 18:42:08 +00004748 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004749 PrevDecl, PrevDecl_TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004750 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004751 HasNoEffect))
John McCalld226f652010-08-21 09:40:31 +00004752 return PrevDecl;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004753
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004754 // Even though HasNoEffect == true means that this explicit instantiation
4755 // has no effect on semantics, we go on to put its syntax in the AST.
4756
4757 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4758 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor52604ab2009-09-11 21:19:12 +00004759 // Since the only prior class template specialization with these
4760 // arguments was referenced but not declared, reuse that
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004761 // declaration node as our own, updating the source location
4762 // for the template name to reflect our new declaration.
4763 // (Other source locations will be updated later.)
Douglas Gregor52604ab2009-09-11 21:19:12 +00004764 Specialization = PrevDecl;
4765 Specialization->setLocation(TemplateNameLoc);
4766 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00004767 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00004768 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004769 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004770
Douglas Gregor52604ab2009-09-11 21:19:12 +00004771 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004772 // Create a new class template specialization declaration node for
4773 // this explicit specialization.
4774 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00004775 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004776 ClassTemplate->getDeclContext(),
4777 TemplateNameLoc,
4778 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00004779 Converted, PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004780 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004781
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004782 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004783 // Insert the new specialization.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004784 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004785 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004786 }
4787
4788 // Build the fully-sugared type for this explicit instantiation as
4789 // the user wrote in the explicit instantiation itself. This means
4790 // that we'll pretty-print the type retrieved from the
4791 // specialization's declaration the way that the user actually wrote
4792 // the explicit instantiation, rather than formatting the name based
4793 // on the "canonical" representation used to store the template
4794 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004795 TypeSourceInfo *WrittenTy
4796 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4797 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004798 Context.getTypeDeclType(Specialization));
4799 Specialization->setTypeAsWritten(WrittenTy);
4800 TemplateArgsIn.release();
4801
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004802 // Set source locations for keywords.
4803 Specialization->setExternLoc(ExternLoc);
4804 Specialization->setTemplateKeywordLoc(TemplateLoc);
4805
4806 // Add the explicit instantiation into its lexical context. However,
4807 // since explicit instantiations are never found by name lookup, we
4808 // just put it into the declaration context directly.
4809 Specialization->setLexicalDeclContext(CurContext);
4810 CurContext->addDecl(Specialization);
4811
4812 // Syntax is now OK, so return if it has no other effect on semantics.
4813 if (HasNoEffect) {
4814 // Set the template specialization kind.
4815 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00004816 return Specialization;
Douglas Gregord78f5982009-11-25 06:01:46 +00004817 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004818
4819 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004820 // A definition of a class template or class member template
4821 // shall be in scope at the point of the explicit instantiation of
4822 // the class template or class member template.
4823 //
4824 // This check comes when we actually try to perform the
4825 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004826 ClassTemplateSpecializationDecl *Def
4827 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004828 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004829 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004830 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004831 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004832 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004833 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
4834 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004835
Douglas Gregor0d035142009-10-27 18:42:08 +00004836 // Instantiate the members of this class template specialization.
4837 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004838 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004839 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00004840 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4841
4842 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4843 // TSK_ExplicitInstantiationDefinition
4844 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4845 TSK == TSK_ExplicitInstantiationDefinition)
4846 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004847
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004848 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004849 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004850
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004851 // Set the template specialization kind.
4852 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00004853 return Specialization;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004854}
4855
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004856// Explicit instantiation of a member class of a class template.
John McCalld226f652010-08-21 09:40:31 +00004857DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004858Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004859 SourceLocation ExternLoc,
4860 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004861 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004862 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004863 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004864 IdentifierInfo *Name,
4865 SourceLocation NameLoc,
4866 AttributeList *Attr) {
4867
Douglas Gregor402abb52009-05-28 23:31:59 +00004868 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004869 bool IsDependent = false;
John McCallf312b1e2010-08-26 23:41:50 +00004870 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCalld226f652010-08-21 09:40:31 +00004871 KWLoc, SS, Name, NameLoc, Attr, AS_none,
4872 MultiTemplateParamsArg(*this, 0, 0),
4873 Owned, IsDependent);
John McCallc4e70192009-09-11 04:59:25 +00004874 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4875
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004876 if (!TagD)
4877 return true;
4878
John McCalld226f652010-08-21 09:40:31 +00004879 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004880 if (Tag->isEnum()) {
4881 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4882 << Context.getTypeDeclType(Tag);
4883 return true;
4884 }
4885
Douglas Gregord0c87372009-05-27 17:30:49 +00004886 if (Tag->isInvalidDecl())
4887 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004888
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004889 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4890 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4891 if (!Pattern) {
4892 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4893 << Context.getTypeDeclType(Record);
4894 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4895 return true;
4896 }
4897
Douglas Gregor558c0322009-10-14 23:41:34 +00004898 // C++0x [temp.explicit]p2:
4899 // If the explicit instantiation is for a class or member class, the
4900 // elaborated-type-specifier in the declaration shall include a
4901 // simple-template-id.
4902 //
4903 // C++98 has the same restriction, just worded differently.
4904 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregora2dd8282010-06-16 16:26:47 +00004905 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00004906 << Record << SS.getRange();
4907
4908 // C++0x [temp.explicit]p2:
4909 // There are two forms of explicit instantiation: an explicit instantiation
4910 // definition and an explicit instantiation declaration. An explicit
4911 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004912 TemplateSpecializationKind TSK
4913 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4914 : TSK_ExplicitInstantiationDeclaration;
4915
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004916 // C++0x [temp.explicit]p2:
4917 // [...] An explicit instantiation shall appear in an enclosing
4918 // namespace of its template. [...]
4919 //
4920 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004921 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004922
4923 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004924 CXXRecordDecl *PrevDecl
4925 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00004926 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00004927 PrevDecl = Record;
4928 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004929 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004930 bool HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00004931 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004932 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004933 PrevDecl,
4934 MSInfo->getTemplateSpecializationKind(),
4935 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004936 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00004937 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004938 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00004939 return TagD;
4940 }
4941
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004942 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00004943 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004944 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004945 // C++ [temp.explicit]p3:
4946 // A definition of a member class of a class template shall be in scope
4947 // at the point of an explicit instantiation of the member class.
4948 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00004949 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004950 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004951 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4952 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004953 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4954 << Pattern;
4955 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004956 } else {
4957 if (InstantiateClass(NameLoc, Record, Def,
4958 getTemplateInstantiationArgs(Record),
4959 TSK))
4960 return true;
4961
Douglas Gregor952b0172010-02-11 01:04:33 +00004962 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00004963 if (!RecordDef)
4964 return true;
4965 }
4966 }
4967
4968 // Instantiate all of the members of the class.
4969 InstantiateClassMembers(NameLoc, RecordDef,
4970 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004971
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004972 if (TSK == TSK_ExplicitInstantiationDefinition)
4973 MarkVTableUsed(NameLoc, RecordDef, true);
4974
Mike Stump390b4cc2009-05-16 07:39:55 +00004975 // FIXME: We don't have any representation for explicit instantiations of
4976 // member classes. Such a representation is not needed for compilation, but it
4977 // should be available for clients that want to see all of the declarations in
4978 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004979 return TagD;
4980}
4981
John McCallf312b1e2010-08-26 23:41:50 +00004982DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4983 SourceLocation ExternLoc,
4984 SourceLocation TemplateLoc,
4985 Declarator &D) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00004986 // Explicit instantiations always require a name.
Abramo Bagnara25777432010-08-11 22:01:17 +00004987 // TODO: check if/when DNInfo should replace Name.
4988 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4989 DeclarationName Name = NameInfo.getName();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004990 if (!Name) {
4991 if (!D.isInvalidType())
4992 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4993 diag::err_explicit_instantiation_requires_name)
4994 << D.getDeclSpec().getSourceRange()
4995 << D.getSourceRange();
4996
4997 return true;
4998 }
4999
5000 // The scope passed in may not be a decl scope. Zip up the scope tree until
5001 // we find one that is.
5002 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5003 (S->getFlags() & Scope::TemplateParamScope) != 0)
5004 S = S->getParent();
5005
5006 // Determine the type of the declaration.
John McCallbf1a0282010-06-04 23:28:52 +00005007 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5008 QualType R = T->getType();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005009 if (R.isNull())
5010 return true;
5011
5012 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5013 // Cannot explicitly instantiate a typedef.
5014 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5015 << Name;
5016 return true;
5017 }
5018
Douglas Gregor663b5a02009-10-14 20:14:33 +00005019 // C++0x [temp.explicit]p1:
5020 // [...] An explicit instantiation of a function template shall not use the
5021 // inline or constexpr specifiers.
5022 // Presumably, this also applies to member functions of class templates as
5023 // well.
5024 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5025 Diag(D.getDeclSpec().getInlineSpecLoc(),
5026 diag::err_explicit_instantiation_inline)
Douglas Gregor849b2432010-03-31 17:46:05 +00005027 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00005028
5029 // FIXME: check for constexpr specifier.
5030
Douglas Gregor558c0322009-10-14 23:41:34 +00005031 // C++0x [temp.explicit]p2:
5032 // There are two forms of explicit instantiation: an explicit instantiation
5033 // definition and an explicit instantiation declaration. An explicit
5034 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00005035 TemplateSpecializationKind TSK
5036 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5037 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00005038
Abramo Bagnara25777432010-08-11 22:01:17 +00005039 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005040 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005041
5042 if (!R->isFunctionType()) {
5043 // C++ [temp.explicit]p1:
5044 // A [...] static data member of a class template can be explicitly
5045 // instantiated from the member definition associated with its class
5046 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00005047 if (Previous.isAmbiguous())
5048 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005049
John McCall1bcee0a2009-12-02 08:25:40 +00005050 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005051 if (!Prev || !Prev->isStaticDataMember()) {
5052 // We expect to see a data data member here.
5053 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5054 << Name;
5055 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5056 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00005057 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005058 return true;
5059 }
5060
5061 if (!Prev->getInstantiatedFromStaticDataMember()) {
5062 // FIXME: Check for explicit specialization?
5063 Diag(D.getIdentifierLoc(),
5064 diag::err_explicit_instantiation_data_member_not_instantiated)
5065 << Prev;
5066 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5067 // FIXME: Can we provide a note showing where this was declared?
5068 return true;
5069 }
5070
Douglas Gregor558c0322009-10-14 23:41:34 +00005071 // C++0x [temp.explicit]p2:
5072 // If the explicit instantiation is for a member function, a member class
5073 // or a static data member of a class template specialization, the name of
5074 // the class template specialization in the qualified-id for the member
5075 // name shall be a simple-template-id.
5076 //
5077 // C++98 has the same restriction, just worded differently.
5078 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5079 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005080 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005081 << Prev << D.getCXXScopeSpec().getRange();
5082
5083 // Check the scope of this explicit instantiation.
5084 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5085
Douglas Gregor454885e2009-10-15 15:54:05 +00005086 // Verify that it is okay to explicitly instantiate here.
5087 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5088 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005089 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005090 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00005091 MSInfo->getTemplateSpecializationKind(),
5092 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005093 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005094 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005095 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005096 return (Decl*) 0;
Douglas Gregor454885e2009-10-15 15:54:05 +00005097
Douglas Gregord5a423b2009-09-25 18:43:00 +00005098 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005099 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005100 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005101 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005102
5103 // FIXME: Create an ExplicitInstantiation node?
John McCalld226f652010-08-21 09:40:31 +00005104 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005105 }
5106
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005107 // If the declarator is a template-id, translate the parser's template
5108 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00005109 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00005110 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005111 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5112 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00005113 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5114 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00005115 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5116 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00005117 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00005118 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00005119 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00005120 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00005121 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005122
Douglas Gregord5a423b2009-09-25 18:43:00 +00005123 // C++ [temp.explicit]p1:
5124 // A [...] function [...] can be explicitly instantiated from its template.
5125 // A member function [...] of a class template can be explicitly
5126 // instantiated from the member definition associated with its class
5127 // template.
John McCallc373d482010-01-27 01:50:18 +00005128 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005129 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5130 P != PEnd; ++P) {
5131 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00005132 if (!HasExplicitTemplateArgs) {
5133 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5134 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5135 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00005136
John McCallc373d482010-01-27 01:50:18 +00005137 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00005138 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5139 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00005140 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00005141 }
5142 }
5143
5144 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5145 if (!FunTmpl)
5146 continue;
5147
John McCall5769d612010-02-08 23:07:23 +00005148 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005149 FunctionDecl *Specialization = 0;
5150 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00005151 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00005152 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00005153 R, Specialization, Info)) {
5154 // FIXME: Keep track of almost-matches?
5155 (void)TDK;
5156 continue;
5157 }
5158
John McCallc373d482010-01-27 01:50:18 +00005159 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005160 }
5161
5162 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005163 UnresolvedSetIterator Result
5164 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregord5a423b2009-09-25 18:43:00 +00005165 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005166 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5167 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5168 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00005169
John McCallc373d482010-01-27 01:50:18 +00005170 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00005171 return true;
John McCallc373d482010-01-27 01:50:18 +00005172
5173 // Ignore access control bits, we don't need them for redeclaration checking.
5174 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005175
Douglas Gregor0a897e32009-10-15 17:21:20 +00005176 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005177 Diag(D.getIdentifierLoc(),
5178 diag::err_explicit_instantiation_member_function_not_instantiated)
5179 << Specialization
5180 << (Specialization->getTemplateSpecializationKind() ==
5181 TSK_ExplicitSpecialization);
5182 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5183 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005184 }
Douglas Gregor558c0322009-10-14 23:41:34 +00005185
Douglas Gregor0a897e32009-10-15 17:21:20 +00005186 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00005187 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5188 PrevDecl = Specialization;
5189
Douglas Gregor0a897e32009-10-15 17:21:20 +00005190 if (PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005191 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005192 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00005193 PrevDecl,
5194 PrevDecl->getTemplateSpecializationKind(),
5195 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005196 HasNoEffect))
Douglas Gregor0a897e32009-10-15 17:21:20 +00005197 return true;
5198
5199 // FIXME: We may still want to build some representation of this
5200 // explicit specialization.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005201 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005202 return (Decl*) 0;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005203 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00005204
5205 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00005206
5207 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005208 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor0a897e32009-10-15 17:21:20 +00005209
Douglas Gregor558c0322009-10-14 23:41:34 +00005210 // C++0x [temp.explicit]p2:
5211 // If the explicit instantiation is for a member function, a member class
5212 // or a static data member of a class template specialization, the name of
5213 // the class template specialization in the qualified-id for the member
5214 // name shall be a simple-template-id.
5215 //
5216 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005217 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005218 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00005219 D.getCXXScopeSpec().isSet() &&
5220 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5221 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005222 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005223 << Specialization << D.getCXXScopeSpec().getRange();
5224
5225 CheckExplicitInstantiationScope(*this,
5226 FunTmpl? (NamedDecl *)FunTmpl
5227 : Specialization->getInstantiatedFromMemberFunction(),
5228 D.getIdentifierLoc(),
5229 D.getCXXScopeSpec().isSet());
5230
Douglas Gregord5a423b2009-09-25 18:43:00 +00005231 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCalld226f652010-08-21 09:40:31 +00005232 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005233}
5234
John McCallf312b1e2010-08-26 23:41:50 +00005235TypeResult
John McCallc4e70192009-09-11 04:59:25 +00005236Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5237 const CXXScopeSpec &SS, IdentifierInfo *Name,
5238 SourceLocation TagLoc, SourceLocation NameLoc) {
5239 // This has to hold, because SS is expected to be defined.
5240 assert(Name && "Expected a name in a dependent tag");
5241
5242 NestedNameSpecifier *NNS
5243 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5244 if (!NNS)
5245 return true;
5246
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005247 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005248
Douglas Gregor48c89f42010-04-24 16:38:41 +00005249 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5250 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005251 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00005252 return true;
5253 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005254
5255 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallb3d87482010-08-24 05:47:05 +00005256 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCallc4e70192009-09-11 04:59:25 +00005257}
5258
John McCallf312b1e2010-08-26 23:41:50 +00005259TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005260Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5261 const CXXScopeSpec &SS, const IdentifierInfo &II,
5262 SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005263 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00005264 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5265 if (!NNS)
5266 return true;
5267
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005268 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5269 !getLangOptions().CPlusPlus0x)
5270 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5271 << FixItHint::CreateRemoval(TypenameLoc);
5272
Douglas Gregor107de902010-04-24 15:35:55 +00005273 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005274 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00005275 if (T.isNull())
5276 return true;
John McCall63b43852010-04-29 23:50:39 +00005277
5278 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5279 if (isa<DependentNameType>(T)) {
5280 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005281 TL.setKeywordLoc(TypenameLoc);
5282 TL.setQualifierRange(SS.getRange());
5283 TL.setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005284 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005285 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005286 TL.setKeywordLoc(TypenameLoc);
5287 TL.setQualifierRange(SS.getRange());
5288 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005289 }
5290
John McCallb3d87482010-08-24 05:47:05 +00005291 return CreateParsedType(T, TSI);
Douglas Gregord57959a2009-03-27 23:10:48 +00005292}
5293
John McCallf312b1e2010-08-26 23:41:50 +00005294TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005295Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5296 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallb3d87482010-08-24 05:47:05 +00005297 ParsedType Ty) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005298 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5299 !getLangOptions().CPlusPlus0x)
5300 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5301 << FixItHint::CreateRemoval(TypenameLoc);
5302
John McCall4e449832010-05-28 23:32:21 +00005303 TypeSourceInfo *InnerTSI = 0;
5304 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCall4e449832010-05-28 23:32:21 +00005305
5306 assert(isa<TemplateSpecializationType>(T) &&
5307 "Expected a template specialization type");
Douglas Gregor17343172009-04-01 00:28:59 +00005308
Douglas Gregor6946baf2009-09-02 13:05:45 +00005309 if (computeDeclContext(SS, false)) {
5310 // If we can compute a declaration context, then the "typename"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005311 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor6946baf2009-09-02 13:05:45 +00005312 // track of the nested-name-specifier.
John McCall4e449832010-05-28 23:32:21 +00005313
5314 // Push the inner type, preserving its source locations if possible.
5315 TypeLocBuilder Builder;
5316 if (InnerTSI)
5317 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5318 else
5319 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5320
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005321 /* Note: NNS already embedded in template specialization type T. */
5322 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCall4e449832010-05-28 23:32:21 +00005323 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5324 TL.setKeywordLoc(TypenameLoc);
5325 TL.setQualifierRange(SS.getRange());
5326
5327 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallb3d87482010-08-24 05:47:05 +00005328 return CreateParsedType(T, TSI);
Douglas Gregor6946baf2009-09-02 13:05:45 +00005329 }
Mike Stump1eb44332009-09-09 15:08:12 +00005330
John McCall33500952010-06-11 00:33:02 +00005331 // TODO: it's really silly that we make a template specialization
5332 // type earlier only to drop it again here.
5333 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5334 DependentTemplateName *DTN =
5335 TST->getTemplateName().getAsDependentTemplateName();
5336 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005337 assert(DTN->getQualifier()
5338 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5339 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5340 DTN->getQualifier(),
John McCall33500952010-06-11 00:33:02 +00005341 DTN->getIdentifier(),
5342 TST->getNumArgs(),
5343 TST->getArgs());
John McCall63b43852010-04-29 23:50:39 +00005344 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCall33500952010-06-11 00:33:02 +00005345 DependentTemplateSpecializationTypeLoc TL =
5346 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5347 if (InnerTSI) {
5348 TemplateSpecializationTypeLoc TSTL =
5349 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5350 TL.setLAngleLoc(TSTL.getLAngleLoc());
5351 TL.setRAngleLoc(TSTL.getRAngleLoc());
5352 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5353 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5354 } else {
5355 TL.initializeLocal(SourceLocation());
5356 }
John McCall4e449832010-05-28 23:32:21 +00005357 TL.setKeywordLoc(TypenameLoc);
5358 TL.setQualifierRange(SS.getRange());
John McCallb3d87482010-08-24 05:47:05 +00005359 return CreateParsedType(T, TSI);
Douglas Gregor17343172009-04-01 00:28:59 +00005360}
5361
Douglas Gregord57959a2009-03-27 23:10:48 +00005362/// \brief Build the type that describes a C++ typename specifier,
5363/// e.g., "typename T::type".
5364QualType
Douglas Gregor107de902010-04-24 15:35:55 +00005365Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5366 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005367 SourceLocation KeywordLoc, SourceRange NNSRange,
5368 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00005369 CXXScopeSpec SS;
5370 SS.setScopeRep(NNS);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005371 SS.setRange(NNSRange);
Douglas Gregord57959a2009-03-27 23:10:48 +00005372
John McCall77bb1aa2010-05-01 00:40:08 +00005373 DeclContext *Ctx = computeDeclContext(SS);
5374 if (!Ctx) {
5375 // If the nested-name-specifier is dependent and couldn't be
5376 // resolved to a type, build a typename type.
5377 assert(NNS->isDependent());
5378 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00005379 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005380
John McCall77bb1aa2010-05-01 00:40:08 +00005381 // If the nested-name-specifier refers to the current instantiation,
5382 // the "typename" keyword itself is superfluous. In C++03, the
5383 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5384 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregor732281d2010-06-14 22:07:54 +00005385 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00005386
John McCall77bb1aa2010-05-01 00:40:08 +00005387 if (RequireCompleteDeclContext(SS, Ctx))
5388 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00005389
5390 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005391 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005392 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005393 unsigned DiagID = 0;
5394 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005395 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005396 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005397 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005398 break;
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005399
5400 case LookupResult::NotFoundInCurrentInstantiation:
5401 // Okay, it's a member of an unknown instantiation.
Douglas Gregor107de902010-04-24 15:35:55 +00005402 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00005403
5404 case LookupResult::Found:
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005405 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005406 // We found a type. Build an ElaboratedType, since the
5407 // typename-specifier was just sugar.
5408 return Context.getElaboratedType(ETK_Typename, NNS,
5409 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00005410 }
5411
5412 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00005413 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00005414 break;
5415
John McCall7ba107a2009-11-18 02:36:19 +00005416 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005417 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00005418 return QualType();
5419
Douglas Gregord57959a2009-03-27 23:10:48 +00005420 case LookupResult::FoundOverloaded:
5421 DiagID = diag::err_typename_nested_not_type;
5422 Referenced = *Result.begin();
5423 break;
5424
John McCall6e247262009-10-10 05:48:19 +00005425 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00005426 return QualType();
5427 }
5428
5429 // If we get here, it's because name lookup did not find a
5430 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005431 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5432 IILoc);
5433 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00005434 if (Referenced)
5435 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5436 << Name;
5437 return QualType();
5438}
Douglas Gregor4a959d82009-08-06 16:20:37 +00005439
5440namespace {
5441 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00005442 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00005443 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00005444 SourceLocation Loc;
5445 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00005446
Douglas Gregor4a959d82009-08-06 16:20:37 +00005447 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00005448 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5449
Mike Stump1eb44332009-09-09 15:08:12 +00005450 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005451 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005452 DeclarationName Entity)
5453 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00005454 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00005455
5456 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00005457 /// transformed.
5458 ///
5459 /// For the purposes of type reconstruction, a type has already been
5460 /// transformed if it is NULL or if it is not dependent.
5461 bool AlreadyTransformed(QualType T) {
5462 return T.isNull() || !T->isDependentType();
5463 }
Mike Stump1eb44332009-09-09 15:08:12 +00005464
5465 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00005466 /// rebuilt.
5467 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00005468
Douglas Gregor4a959d82009-08-06 16:20:37 +00005469 /// \brief Returns the name of the entity whose type is being rebuilt.
5470 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00005471
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005472 /// \brief Sets the "base" location and entity when that
5473 /// information is known based on another transformation.
5474 void setBase(SourceLocation Loc, DeclarationName Entity) {
5475 this->Loc = Loc;
5476 this->Entity = Entity;
5477 }
Douglas Gregor4a959d82009-08-06 16:20:37 +00005478 };
5479}
5480
Douglas Gregor4a959d82009-08-06 16:20:37 +00005481/// \brief Rebuilds a type within the context of the current instantiation.
5482///
Mike Stump1eb44332009-09-09 15:08:12 +00005483/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00005484/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00005485/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00005486/// partial specialization thereof). This routine will rebuild that type now
5487/// that we have entered the declarator's scope, which may produce different
5488/// canonical types, e.g.,
5489///
5490/// \code
5491/// template<typename T>
5492/// struct X {
5493/// typedef T* pointer;
5494/// pointer data();
5495/// };
5496///
5497/// template<typename T>
5498/// typename X<T>::pointer X<T>::data() { ... }
5499/// \endcode
5500///
Douglas Gregor4714c122010-03-31 17:34:00 +00005501/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005502/// since we do not know that we can look into X<T> when we parsed the type.
5503/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005504/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00005505/// as the canonical type of T*, allowing the return types of the out-of-line
5506/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00005507TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5508 SourceLocation Loc,
5509 DeclarationName Name) {
5510 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00005511 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00005512
Douglas Gregor4a959d82009-08-06 16:20:37 +00005513 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5514 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00005515}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005516
John McCall60d7b3a2010-08-24 06:29:42 +00005517ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallb3d87482010-08-24 05:47:05 +00005518 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5519 DeclarationName());
5520 return Rebuilder.TransformExpr(E);
5521}
5522
John McCall63b43852010-04-29 23:50:39 +00005523bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5524 if (SS.isInvalid()) return true;
John McCall31f17ec2010-04-27 00:57:59 +00005525
5526 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5527 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5528 DeclarationName());
5529 NestedNameSpecifier *Rebuilt =
5530 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall63b43852010-04-29 23:50:39 +00005531 if (!Rebuilt) return true;
5532
5533 SS.setScopeRep(Rebuilt);
5534 return false;
John McCall31f17ec2010-04-27 00:57:59 +00005535}
5536
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005537/// \brief Produces a formatted string that describes the binding of
5538/// template parameters to template arguments.
5539std::string
5540Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5541 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005542 // FIXME: For variadic templates, we'll need to get the structured list.
5543 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5544 Args.flat_size());
5545}
5546
5547std::string
5548Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5549 const TemplateArgument *Args,
5550 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005551 std::string Result;
5552
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005553 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005554 return Result;
5555
5556 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005557 if (I >= NumArgs)
5558 break;
5559
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005560 if (I == 0)
5561 Result += "[with ";
5562 else
5563 Result += ", ";
5564
5565 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5566 Result += Id->getName();
5567 } else {
5568 Result += '$';
5569 Result += llvm::utostr(I);
5570 }
5571
5572 Result += " = ";
5573
5574 switch (Args[I].getKind()) {
5575 case TemplateArgument::Null:
5576 Result += "<no value>";
5577 break;
5578
5579 case TemplateArgument::Type: {
5580 std::string TypeStr;
5581 Args[I].getAsType().getAsStringInternal(TypeStr,
5582 Context.PrintingPolicy);
5583 Result += TypeStr;
5584 break;
5585 }
5586
5587 case TemplateArgument::Declaration: {
5588 bool Unnamed = true;
5589 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5590 if (ND->getDeclName()) {
5591 Unnamed = false;
5592 Result += ND->getNameAsString();
5593 }
5594 }
5595
5596 if (Unnamed) {
5597 Result += "<anonymous>";
5598 }
5599 break;
5600 }
5601
Douglas Gregor788cd062009-11-11 01:00:40 +00005602 case TemplateArgument::Template: {
5603 std::string Str;
5604 llvm::raw_string_ostream OS(Str);
5605 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5606 Result += OS.str();
5607 break;
5608 }
5609
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005610 case TemplateArgument::Integral: {
5611 Result += Args[I].getAsIntegral()->toString(10);
5612 break;
5613 }
5614
5615 case TemplateArgument::Expression: {
Douglas Gregor77e2c672010-04-29 04:55:13 +00005616 // FIXME: This is non-optimal, since we're regurgitating the
5617 // expression we were given.
5618 std::string Str;
5619 {
5620 llvm::raw_string_ostream OS(Str);
5621 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5622 Context.PrintingPolicy);
5623 }
5624 Result += Str;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005625 break;
5626 }
5627
5628 case TemplateArgument::Pack:
5629 // FIXME: Format template argument packs
5630 Result += "<template argument pack>";
5631 break;
5632 }
5633 }
5634
5635 Result += ']';
5636 return Result;
5637}