blob: 22a0933c7202e9c1988643330812166d82572a73 [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 McCallb8592062010-08-13 02:23:42 +0000144 if (R.empty() || R.isAmbiguous()) {
145 R.suppressDiagnostics();
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000146 return TNK_Non_template;
John McCallb8592062010-08-13 02:23:42 +0000147 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000148
John McCall0bd6feb2009-12-02 08:04:21 +0000149 TemplateName Template;
150 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000151
John McCall0bd6feb2009-12-02 08:04:21 +0000152 unsigned ResultCount = R.end() - R.begin();
153 if (ResultCount > 1) {
154 // We assume that we'll preserve the qualifier from a function
155 // template name in other ways.
156 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
157 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000158
159 // We'll do this lookup again later.
160 R.suppressDiagnostics();
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000161 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000162 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
163
164 if (SS.isSet() && !SS.isInvalid()) {
165 NestedNameSpecifier *Qualifier
166 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c153532010-08-06 12:11:11 +0000167 Template = Context.getQualifiedTemplateName(Qualifier,
168 hasTemplateKeyword, TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000169 } else {
170 Template = TemplateName(TD);
171 }
172
John McCallb8592062010-08-13 02:23:42 +0000173 if (isa<FunctionTemplateDecl>(TD)) {
John McCall0bd6feb2009-12-02 08:04:21 +0000174 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000175
176 // We'll do this lookup again later.
177 R.suppressDiagnostics();
178 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000179 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
180 TemplateKind = TNK_Type_template;
181 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000182 }
Mike Stump1eb44332009-09-09 15:08:12 +0000183
John McCall0bd6feb2009-12-02 08:04:21 +0000184 TemplateResult = TemplateTy::make(Template);
185 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000186}
187
Douglas Gregor84d0a192010-01-12 21:28:44 +0000188bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
189 SourceLocation IILoc,
190 Scope *S,
191 const CXXScopeSpec *SS,
192 TemplateTy &SuggestedTemplate,
193 TemplateNameKind &SuggestedKind) {
194 // We can't recover unless there's a dependent scope specifier preceding the
195 // template name.
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000196 // FIXME: Typo correction?
Douglas Gregor84d0a192010-01-12 21:28:44 +0000197 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
198 computeDeclContext(*SS))
199 return false;
200
201 // The code is missing a 'template' keyword prior to the dependent template
202 // name.
203 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
204 Diag(IILoc, diag::err_template_kw_missing)
205 << Qualifier << II.getName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000206 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor84d0a192010-01-12 21:28:44 +0000207 SuggestedTemplate
208 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
209 SuggestedKind = TNK_Dependent_template_name;
210 return true;
211}
212
John McCallf7a1a742009-11-24 19:00:30 +0000213void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000214 Scope *S, CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +0000215 QualType ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000216 bool EnteringContext,
217 bool &MemberOfUnknownSpecialization) {
John McCallf7a1a742009-11-24 19:00:30 +0000218 // Determine where to perform name lookup
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000219 MemberOfUnknownSpecialization = false;
John McCallf7a1a742009-11-24 19:00:30 +0000220 DeclContext *LookupCtx = 0;
221 bool isDependent = false;
222 if (!ObjectType.isNull()) {
223 // This nested-name-specifier occurs in a member access expression, e.g.,
224 // x->B::f, and we are looking into the type of the object.
225 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
226 LookupCtx = computeDeclContext(ObjectType);
227 isDependent = ObjectType->isDependentType();
228 assert((isDependent || !ObjectType->isIncompleteType()) &&
229 "Caller should have completed object type");
230 } else if (SS.isSet()) {
231 // This nested-name-specifier occurs after another nested-name-specifier,
232 // so long into the context associated with the prior nested-name-specifier.
233 LookupCtx = computeDeclContext(SS, EnteringContext);
234 isDependent = isDependentScopeSpecifier(SS);
235
236 // The declaration context must be complete.
John McCall77bb1aa2010-05-01 00:40:08 +0000237 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCallf7a1a742009-11-24 19:00:30 +0000238 return;
239 }
240
241 bool ObjectTypeSearchedInScope = false;
242 if (LookupCtx) {
243 // Perform "qualified" name lookup into the declaration context we
244 // computed, which is either the type of the base of a member access
245 // expression or the declaration context associated with a prior
246 // nested-name-specifier.
247 LookupQualifiedName(Found, LookupCtx);
248
249 if (!ObjectType.isNull() && Found.empty()) {
250 // C++ [basic.lookup.classref]p1:
251 // In a class member access expression (5.2.5), if the . or -> token is
252 // immediately followed by an identifier followed by a <, the
253 // identifier must be looked up to determine whether the < is the
254 // beginning of a template argument list (14.2) or a less-than operator.
255 // The identifier is first looked up in the class of the object
256 // expression. If the identifier is not found, it is then looked up in
257 // the context of the entire postfix-expression and shall name a class
258 // or function template.
John McCallf7a1a742009-11-24 19:00:30 +0000259 if (S) LookupName(Found, S);
260 ObjectTypeSearchedInScope = true;
261 }
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000262 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregor2e933882010-01-12 17:06:20 +0000263 // We cannot look into a dependent object type or nested nme
264 // specifier.
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000265 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000266 return;
267 } else {
268 // Perform unqualified name lookup in the current scope.
269 LookupName(Found, S);
270 }
271
Douglas Gregor2e933882010-01-12 17:06:20 +0000272 if (Found.empty() && !isDependent) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000273 // If we did not find any names, attempt to correct any typos.
274 DeclarationName Name = Found.getLookupName();
Douglas Gregoraaf87162010-04-14 20:04:41 +0000275 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000276 false, CTC_CXXCasts)) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000277 FilterAcceptableTemplateNames(Context, Found);
John McCallad00b772010-06-16 08:42:20 +0000278 if (!Found.empty()) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000279 if (LookupCtx)
280 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
281 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000282 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000283 Found.getLookupName().getAsString());
284 else
285 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
286 << Name << Found.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000287 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000288 Found.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000289 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
290 Diag(Template->getLocation(), diag::note_previous_decl)
291 << Template->getDeclName();
John McCallad00b772010-06-16 08:42:20 +0000292 }
Douglas Gregorbfea2392009-12-31 08:11:17 +0000293 } else {
294 Found.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000295 Found.setLookupName(Name);
Douglas Gregorbfea2392009-12-31 08:11:17 +0000296 }
297 }
298
John McCallf7a1a742009-11-24 19:00:30 +0000299 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000300 if (Found.empty()) {
301 if (isDependent)
302 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000303 return;
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000304 }
John McCallf7a1a742009-11-24 19:00:30 +0000305
306 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
307 // C++ [basic.lookup.classref]p1:
308 // [...] If the lookup in the class of the object expression finds a
309 // template, the name is also looked up in the context of the entire
310 // postfix-expression and [...]
311 //
312 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
313 LookupOrdinaryName);
314 LookupName(FoundOuter, S);
315 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000316
John McCallf7a1a742009-11-24 19:00:30 +0000317 if (FoundOuter.empty()) {
318 // - if the name is not found, the name found in the class of the
319 // object expression is used, otherwise
320 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
321 // - if the name is found in the context of the entire
322 // postfix-expression and does not name a class template, the name
323 // found in the class of the object expression is used, otherwise
John McCallad00b772010-06-16 08:42:20 +0000324 } else if (!Found.isSuppressingDiagnostics()) {
John McCallf7a1a742009-11-24 19:00:30 +0000325 // - if the name found is a class template, it must refer to the same
326 // entity as the one found in the class of the object expression,
327 // otherwise the program is ill-formed.
328 if (!Found.isSingleResult() ||
329 Found.getFoundDecl()->getCanonicalDecl()
330 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
331 Diag(Found.getNameLoc(),
Jeffrey Yasskin21d07e42010-06-05 01:39:57 +0000332 diag::ext_nested_name_member_ref_lookup_ambiguous)
333 << Found.getLookupName()
334 << ObjectType;
John McCallf7a1a742009-11-24 19:00:30 +0000335 Diag(Found.getRepresentativeDecl()->getLocation(),
336 diag::note_ambig_member_ref_object_type)
337 << ObjectType;
338 Diag(FoundOuter.getFoundDecl()->getLocation(),
339 diag::note_ambig_member_ref_scope);
340
341 // Recover by taking the template that we found in the object
342 // expression's type.
343 }
344 }
345 }
346}
347
John McCall2f841ba2009-12-02 03:53:29 +0000348/// ActOnDependentIdExpression - Handle a dependent id-expression that
349/// was just parsed. This is only possible with an explicit scope
350/// specifier naming a dependent type.
John McCall60d7b3a2010-08-24 06:29:42 +0000351ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000352Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000353 const DeclarationNameInfo &NameInfo,
John McCall2f841ba2009-12-02 03:53:29 +0000354 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000355 const TemplateArgumentListInfo *TemplateArgs) {
356 NestedNameSpecifier *Qualifier
357 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallea1471e2010-05-20 01:18:31 +0000358
359 DeclContext *DC = getFunctionLevelDeclContext();
John McCallf7a1a742009-11-24 19:00:30 +0000360
John McCall2f841ba2009-12-02 03:53:29 +0000361 if (!isAddressOfOperand &&
John McCallea1471e2010-05-20 01:18:31 +0000362 isa<CXXMethodDecl>(DC) &&
363 cast<CXXMethodDecl>(DC)->isInstance()) {
364 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2f841ba2009-12-02 03:53:29 +0000365
John McCallf7a1a742009-11-24 19:00:30 +0000366 // Since the 'this' expression is synthesized, we don't need to
367 // perform the double-lookup check.
368 NamedDecl *FirstQualifierInScope = 0;
369
John McCallaa81e162009-12-01 22:10:20 +0000370 return Owned(CXXDependentScopeMemberExpr::Create(Context,
371 /*This*/ 0, ThisType,
372 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000373 /*Op*/ SourceLocation(),
374 Qualifier, SS.getRange(),
375 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +0000376 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000377 TemplateArgs));
378 }
379
Abramo Bagnara25777432010-08-11 22:01:17 +0000380 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +0000381}
382
John McCall60d7b3a2010-08-24 06:29:42 +0000383ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000384Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000385 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000386 const TemplateArgumentListInfo *TemplateArgs) {
387 return Owned(DependentScopeDeclRefExpr::Create(Context,
388 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
389 SS.getRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +0000390 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000391 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000392}
393
Douglas Gregor72c3f312008-12-05 18:15:24 +0000394/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
395/// that the template parameter 'PrevDecl' is being shadowed by a new
396/// declaration at location Loc. Returns true to indicate that this is
397/// an error, and false otherwise.
398bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000399 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000400
401 // Microsoft Visual C++ permits template parameters to be shadowed.
402 if (getLangOptions().Microsoft)
403 return false;
404
405 // C++ [temp.local]p4:
406 // A template-parameter shall not be redeclared within its
407 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000408 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000409 << cast<NamedDecl>(PrevDecl)->getDeclName();
410 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
411 return true;
412}
413
Douglas Gregor2943aed2009-03-03 04:44:36 +0000414/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000415/// the parameter D to reference the templated declaration and return a pointer
416/// to the template declaration. Otherwise, do nothing to D and return null.
John McCalld226f652010-08-21 09:40:31 +0000417TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
418 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
419 D = Temp->getTemplatedDecl();
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000420 return Temp;
421 }
422 return 0;
423}
424
Douglas Gregor788cd062009-11-11 01:00:40 +0000425static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
426 const ParsedTemplateArgument &Arg) {
427
428 switch (Arg.getKind()) {
429 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000430 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000431 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
432 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000433 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000434 return TemplateArgumentLoc(TemplateArgument(T), DI);
435 }
436
437 case ParsedTemplateArgument::NonType: {
438 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
439 return TemplateArgumentLoc(TemplateArgument(E), E);
440 }
441
442 case ParsedTemplateArgument::Template: {
John McCall2b5289b2010-08-23 07:28:44 +0000443 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor788cd062009-11-11 01:00:40 +0000444 return TemplateArgumentLoc(TemplateArgument(Template),
445 Arg.getScopeSpec().getRange(),
446 Arg.getLocation());
447 }
448 }
449
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000450 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000451 return TemplateArgumentLoc();
452}
453
454/// \brief Translates template arguments as provided by the parser
455/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000456void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
457 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000458 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000459 TemplateArgs.addArgument(translateTemplateArgument(*this,
460 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000461}
462
Douglas Gregor72c3f312008-12-05 18:15:24 +0000463/// ActOnTypeParameter - Called when a C++ template type parameter
464/// (e.g., "typename T") has been parsed. Typename specifies whether
465/// the keyword "typename" was used to declare the type parameter
466/// (otherwise, "class" was used), and KeyLoc is the location of the
467/// "class" or "typename" keyword. ParamName is the name of the
468/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregorefed5c82010-06-16 15:23:05 +0000469/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000470/// If the type parameter has a default argument, it will be added
471/// later via ActOnTypeParameterDefault.
John McCalld226f652010-08-21 09:40:31 +0000472Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
473 SourceLocation EllipsisLoc,
474 SourceLocation KeyLoc,
475 IdentifierInfo *ParamName,
476 SourceLocation ParamNameLoc,
477 unsigned Depth, unsigned Position,
478 SourceLocation EqualLoc,
John McCallb3d87482010-08-24 05:47:05 +0000479 ParsedType DefaultArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000480 assert(S->isTemplateParamScope() &&
481 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000482 bool Invalid = false;
483
484 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000485 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000486 LookupOrdinaryName,
487 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000488 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000489 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000490 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000491 }
492
Douglas Gregorddc29e12009-02-06 22:42:48 +0000493 SourceLocation Loc = ParamNameLoc;
494 if (!ParamName)
495 Loc = KeyLoc;
496
Douglas Gregor72c3f312008-12-05 18:15:24 +0000497 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000498 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
499 Loc, Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000500 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000501 if (Invalid)
502 Param->setInvalidDecl();
503
504 if (ParamName) {
505 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000506 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000507 IdResolver.AddDecl(Param);
508 }
509
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000510 // Handle the default argument, if provided.
511 if (DefaultArg) {
512 TypeSourceInfo *DefaultTInfo;
513 GetTypeFromParser(DefaultArg, &DefaultTInfo);
514
515 assert(DefaultTInfo && "expected source information for type");
516
517 // C++0x [temp.param]p9:
518 // A default template-argument may be specified for any kind of
519 // template-parameter that is not a template parameter pack.
520 if (Ellipsis) {
521 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
John McCalld226f652010-08-21 09:40:31 +0000522 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000523 }
524
525 // Check the template argument itself.
526 if (CheckTemplateArgument(Param, DefaultTInfo)) {
527 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000528 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000529 }
530
531 Param->setDefaultArgument(DefaultTInfo, false);
532 }
533
John McCalld226f652010-08-21 09:40:31 +0000534 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000535}
536
Douglas Gregor2943aed2009-03-03 04:44:36 +0000537/// \brief Check that the type of a non-type template parameter is
538/// well-formed.
539///
540/// \returns the (possibly-promoted) parameter type if valid;
541/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000542QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000543Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora481ec42010-05-23 19:57:01 +0000544 // We don't allow variably-modified types as the type of non-type template
545 // parameters.
546 if (T->isVariablyModifiedType()) {
547 Diag(Loc, diag::err_variably_modified_nontype_template_param)
548 << T;
549 return QualType();
550 }
551
Douglas Gregor2943aed2009-03-03 04:44:36 +0000552 // C++ [temp.param]p4:
553 //
554 // A non-type template-parameter shall have one of the following
555 // (optionally cv-qualified) types:
556 //
557 // -- integral or enumeration type,
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000558 if (T->isIntegralOrEnumerationType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000559 // -- pointer to object or pointer to function,
Eli Friedman13578692010-08-05 02:49:48 +0000560 T->isPointerType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000561 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000562 T->isReferenceType() ||
563 // -- pointer to member.
564 T->isMemberPointerType() ||
565 // If T is a dependent type, we can't do the check now, so we
566 // assume that it is well-formed.
567 T->isDependentType())
568 return T;
569 // C++ [temp.param]p8:
570 //
571 // A non-type template-parameter of type "array of T" or
572 // "function returning T" is adjusted to be of type "pointer to
573 // T" or "pointer to function returning T", respectively.
574 else if (T->isArrayType())
575 // FIXME: Keep the type prior to promotion?
576 return Context.getArrayDecayedType(T);
577 else if (T->isFunctionType())
578 // FIXME: Keep the type prior to promotion?
579 return Context.getPointerType(T);
Douglas Gregor0fddb972010-05-22 16:17:30 +0000580
Douglas Gregor2943aed2009-03-03 04:44:36 +0000581 Diag(Loc, diag::err_template_nontype_parm_bad_type)
582 << T;
583
584 return QualType();
585}
586
John McCalld226f652010-08-21 09:40:31 +0000587Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
588 unsigned Depth,
589 unsigned Position,
590 SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000591 Expr *Default) {
John McCallbf1a0282010-06-04 23:28:52 +0000592 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
593 QualType T = TInfo->getType();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000594
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000595 assert(S->isTemplateParamScope() &&
596 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000597 bool Invalid = false;
598
599 IdentifierInfo *ParamName = D.getIdentifier();
600 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000601 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000602 LookupOrdinaryName,
603 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000604 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000605 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000606 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000607 }
608
Douglas Gregor2943aed2009-03-03 04:44:36 +0000609 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000610 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000611 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000612 Invalid = true;
613 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000614
Douglas Gregor72c3f312008-12-05 18:15:24 +0000615 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000616 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
617 D.getIdentifierLoc(),
John McCalla93c9342009-12-07 02:54:59 +0000618 Depth, Position, ParamName, T, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000619 if (Invalid)
620 Param->setInvalidDecl();
621
622 if (D.getIdentifier()) {
623 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000624 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000625 IdResolver.AddDecl(Param);
626 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000627
628 // Check the well-formedness of the default template argument, if provided.
John McCall9ae2f072010-08-23 23:25:46 +0000629 if (Default) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000630 TemplateArgument Converted;
631 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
632 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000633 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000634 }
635
John McCall9ae2f072010-08-23 23:25:46 +0000636 Param->setDefaultArgument(Default, false);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000637 }
638
John McCalld226f652010-08-21 09:40:31 +0000639 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000640}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000641
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000642/// ActOnTemplateTemplateParameter - Called when a C++ template template
643/// parameter (e.g. T in template <template <typename> class T> class array)
644/// has been parsed. S is the current scope.
John McCalld226f652010-08-21 09:40:31 +0000645Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
646 SourceLocation TmpLoc,
647 TemplateParamsTy *Params,
648 IdentifierInfo *Name,
649 SourceLocation NameLoc,
650 unsigned Depth,
651 unsigned Position,
652 SourceLocation EqualLoc,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000653 const ParsedTemplateArgument &Default) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000654 assert(S->isTemplateParamScope() &&
655 "Template template parameter not in template parameter scope!");
656
657 // Construct the parameter object.
658 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000659 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
660 TmpLoc, Depth, Position, Name,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000661 (TemplateParameterList*)Params);
662
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000663 // If the template template parameter has a name, then link the identifier
664 // into the scope and lookup mechanisms.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000665 if (Name) {
John McCalld226f652010-08-21 09:40:31 +0000666 S->AddDecl(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000667 IdResolver.AddDecl(Param);
668 }
669
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000670 if (!Default.isInvalid()) {
671 // Check only that we have a template template argument. We don't want to
672 // try to check well-formedness now, because our template template parameter
673 // might have dependent types in its template parameters, which we wouldn't
674 // be able to match now.
675 //
676 // If none of the template template parameter's template arguments mention
677 // other template parameters, we could actually perform more checking here.
678 // However, it isn't worth doing.
679 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
680 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
681 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
682 << DefaultArg.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +0000683 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000684 }
685
686 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000687 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000688
John McCalld226f652010-08-21 09:40:31 +0000689 return Param;
Douglas Gregord684b002009-02-10 19:49:53 +0000690}
691
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000692/// ActOnTemplateParameterList - Builds a TemplateParameterList that
693/// contains the template parameters in Params/NumParams.
694Sema::TemplateParamsTy *
695Sema::ActOnTemplateParameterList(unsigned Depth,
696 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000697 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000698 SourceLocation LAngleLoc,
John McCalld226f652010-08-21 09:40:31 +0000699 Decl **Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000700 SourceLocation RAngleLoc) {
701 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000702 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000703
Douglas Gregorddc29e12009-02-06 22:42:48 +0000704 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000705 (NamedDecl**)Params, NumParams,
706 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000707}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000708
John McCallb6217662010-03-15 10:12:16 +0000709static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
710 if (SS.isSet())
711 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
712 SS.getRange());
713}
714
Douglas Gregor212e81c2009-03-25 00:13:59 +0000715Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000716Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000717 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000718 IdentifierInfo *Name, SourceLocation NameLoc,
719 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000720 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000721 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000722 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000723 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000724 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000725 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000726
727 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000728 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000729 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000730
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000731 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
732 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000733
734 // There is no such thing as an unnamed class template.
735 if (!Name) {
736 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000737 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000738 }
739
740 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000741 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000742 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000743 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000744 if (SS.isNotEmpty() && !SS.isInvalid()) {
745 SemanticContext = computeDeclContext(SS, true);
746 if (!SemanticContext) {
747 // FIXME: Produce a reasonable diagnostic here
748 return true;
749 }
Mike Stump1eb44332009-09-09 15:08:12 +0000750
John McCall77bb1aa2010-05-01 00:40:08 +0000751 if (RequireCompleteDeclContext(SS, SemanticContext))
752 return true;
753
John McCalla24dc2e2009-11-17 02:14:36 +0000754 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000755 } else {
756 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000757 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000758 }
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Douglas Gregor57265e32010-04-12 16:00:01 +0000760 if (Previous.isAmbiguous())
761 return true;
762
Douglas Gregorddc29e12009-02-06 22:42:48 +0000763 NamedDecl *PrevDecl = 0;
764 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000765 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000766
Douglas Gregorddc29e12009-02-06 22:42:48 +0000767 // If there is a previous declaration with the same name, check
768 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000769 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000770 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000771
772 // We may have found the injected-class-name of a class template,
773 // class template partial specialization, or class template specialization.
774 // In these cases, grab the template that is being defined or specialized.
775 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
776 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
777 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
778 PrevClassTemplate
779 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
780 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
781 PrevClassTemplate
782 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
783 ->getSpecializedTemplate();
784 }
785 }
786
John McCall65c49462009-12-18 11:25:59 +0000787 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000788 // C++ [namespace.memdef]p3:
789 // [...] When looking for a prior declaration of a class or a function
790 // declared as a friend, and when the name of the friend class or
791 // function is neither a qualified name nor a template-id, scopes outside
792 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000793 if (!SS.isSet()) {
794 DeclContext *OutermostContext = CurContext;
795 while (!OutermostContext->isFileContext())
796 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000797
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000798 if (PrevDecl &&
799 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
800 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
801 SemanticContext = PrevDecl->getDeclContext();
802 } else {
803 // Declarations in outer scopes don't matter. However, the outermost
804 // context we computed is the semantic context for our new
805 // declaration.
806 PrevDecl = PrevClassTemplate = 0;
807 SemanticContext = OutermostContext;
808 }
John McCalle129d442009-12-17 23:21:11 +0000809 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000810
John McCalle129d442009-12-17 23:21:11 +0000811 if (CurContext->isDependentContext()) {
812 // If this is a dependent context, we don't want to link the friend
813 // class template to the template in scope, because that would perform
814 // checking of the template parameter lists that can't be performed
815 // until the outer context is instantiated.
816 PrevDecl = PrevClassTemplate = 0;
817 }
818 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
819 PrevDecl = PrevClassTemplate = 0;
Douglas Gregor57265e32010-04-12 16:00:01 +0000820
Douglas Gregorddc29e12009-02-06 22:42:48 +0000821 if (PrevClassTemplate) {
822 // Ensure that the template parameter lists are compatible.
823 if (!TemplateParameterListsAreEqual(TemplateParams,
824 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000825 /*Complain=*/true,
826 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000827 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000828
829 // C++ [temp.class]p4:
830 // In a redeclaration, partial specialization, explicit
831 // specialization or explicit instantiation of a class template,
832 // the class-key shall agree in kind with the original class
833 // template declaration (7.1.5.3).
834 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000835 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000836 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000837 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000838 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000839 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000840 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000841 }
842
Douglas Gregorddc29e12009-02-06 22:42:48 +0000843 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000844 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000845 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000846 Diag(NameLoc, diag::err_redefinition) << Name;
847 Diag(Def->getLocation(), diag::note_previous_definition);
848 // FIXME: Would it make sense to try to "forget" the previous
849 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000850 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000851 }
852 }
853 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
854 // Maybe we will complain about the shadowed template parameter.
855 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
856 // Just pretend that we didn't see the previous declaration.
857 PrevDecl = 0;
858 } else if (PrevDecl) {
859 // C++ [temp]p5:
860 // A class template shall not have the same name as any other
861 // template, class, function, object, enumeration, enumerator,
862 // namespace, or type in the same scope (3.3), except as specified
863 // in (14.5.4).
864 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
865 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000866 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000867 }
868
Douglas Gregord684b002009-02-10 19:49:53 +0000869 // Check the template parameter list of this declaration, possibly
870 // merging in the template parameter list from the previous class
871 // template declaration.
872 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000873 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
874 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000875 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Douglas Gregor57265e32010-04-12 16:00:01 +0000877 if (SS.isSet()) {
878 // If the name of the template was qualified, we must be defining the
879 // template out-of-line.
880 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
881 !(TUK == TUK_Friend && CurContext->isDependentContext()))
882 Diag(NameLoc, diag::err_member_def_does_not_match)
883 << Name << SemanticContext << SS.getRange();
884 }
885
Mike Stump1eb44332009-09-09 15:08:12 +0000886 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000887 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000888 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000889 PrevClassTemplate->getTemplatedDecl() : 0,
890 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000891 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000892
893 ClassTemplateDecl *NewTemplate
894 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
895 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000896 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000897 NewClass->setDescribedClassTemplate(NewTemplate);
898
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000899 // Build the type for the class template declaration now.
Douglas Gregor24bae922010-07-08 18:37:38 +0000900 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCall3cb0ebd2010-03-10 03:28:59 +0000901 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000902 assert(T->isDependentType() && "Class template type is not dependent?");
903 (void)T;
904
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000905 // If we are providing an explicit specialization of a member that is a
906 // class template, make a note of that.
907 if (PrevClassTemplate &&
908 PrevClassTemplate->getInstantiatedFromMemberTemplate())
909 PrevClassTemplate->setMemberSpecialization();
910
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000911 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000912 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000913 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000914
Douglas Gregorddc29e12009-02-06 22:42:48 +0000915 // Set the lexical context of these templates
916 NewClass->setLexicalDeclContext(CurContext);
917 NewTemplate->setLexicalDeclContext(CurContext);
918
John McCall0f434ec2009-07-31 02:45:11 +0000919 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000920 NewClass->startDefinition();
921
922 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000923 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000924
John McCall05b23ea2009-09-14 21:59:20 +0000925 if (TUK != TUK_Friend)
926 PushOnScopeChains(NewTemplate, S);
927 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000928 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000929 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000930 NewClass->setAccess(PrevClassTemplate->getAccess());
931 }
John McCall05b23ea2009-09-14 21:59:20 +0000932
Douglas Gregord85bea22009-09-26 06:47:28 +0000933 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
934 PrevClassTemplate != NULL);
935
John McCall05b23ea2009-09-14 21:59:20 +0000936 // Friend templates are visible in fairly strange ways.
937 if (!CurContext->isDependentContext()) {
938 DeclContext *DC = SemanticContext->getLookupContext();
939 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
940 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
941 PushOnScopeChains(NewTemplate, EnclosingScope,
942 /* AddToContext = */ false);
943 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000944
945 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
946 NewClass->getLocation(),
947 NewTemplate,
948 /*FIXME:*/NewClass->getLocation());
949 Friend->setAccess(AS_public);
950 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000951 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000952
Douglas Gregord684b002009-02-10 19:49:53 +0000953 if (Invalid) {
954 NewTemplate->setInvalidDecl();
955 NewClass->setInvalidDecl();
956 }
John McCalld226f652010-08-21 09:40:31 +0000957 return NewTemplate;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000958}
959
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000960/// \brief Diagnose the presence of a default template argument on a
961/// template parameter, which is ill-formed in certain contexts.
962///
963/// \returns true if the default template argument should be dropped.
964static bool DiagnoseDefaultTemplateArgument(Sema &S,
965 Sema::TemplateParamListContext TPC,
966 SourceLocation ParamLoc,
967 SourceRange DefArgRange) {
968 switch (TPC) {
969 case Sema::TPC_ClassTemplate:
970 return false;
971
972 case Sema::TPC_FunctionTemplate:
973 // C++ [temp.param]p9:
974 // A default template-argument shall not be specified in a
975 // function template declaration or a function template
976 // definition [...]
977 // (This sentence is not in C++0x, per DR226).
978 if (!S.getLangOptions().CPlusPlus0x)
979 S.Diag(ParamLoc,
980 diag::err_template_parameter_default_in_function_template)
981 << DefArgRange;
982 return false;
983
984 case Sema::TPC_ClassTemplateMember:
985 // C++0x [temp.param]p9:
986 // A default template-argument shall not be specified in the
987 // template-parameter-lists of the definition of a member of a
988 // class template that appears outside of the member's class.
989 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
990 << DefArgRange;
991 return true;
992
993 case Sema::TPC_FriendFunctionTemplate:
994 // C++ [temp.param]p9:
995 // A default template-argument shall not be specified in a
996 // friend template declaration.
997 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
998 << DefArgRange;
999 return true;
1000
1001 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1002 // for friend function templates if there is only a single
1003 // declaration (and it is a definition). Strange!
1004 }
1005
1006 return false;
1007}
1008
Douglas Gregord684b002009-02-10 19:49:53 +00001009/// \brief Checks the validity of a template parameter list, possibly
1010/// considering the template parameter list from a previous
1011/// declaration.
1012///
1013/// If an "old" template parameter list is provided, it must be
1014/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1015/// template parameter list.
1016///
1017/// \param NewParams Template parameter list for a new template
1018/// declaration. This template parameter list will be updated with any
1019/// default arguments that are carried through from the previous
1020/// template parameter list.
1021///
1022/// \param OldParams If provided, template parameter list from a
1023/// previous declaration of the same template. Default template
1024/// arguments will be merged from the old template parameter list to
1025/// the new template parameter list.
1026///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001027/// \param TPC Describes the context in which we are checking the given
1028/// template parameter list.
1029///
Douglas Gregord684b002009-02-10 19:49:53 +00001030/// \returns true if an error occurred, false otherwise.
1031bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001032 TemplateParameterList *OldParams,
1033 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001034 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Douglas Gregord684b002009-02-10 19:49:53 +00001036 // C++ [temp.param]p10:
1037 // The set of default template-arguments available for use with a
1038 // template declaration or definition is obtained by merging the
1039 // default arguments from the definition (if in scope) and all
1040 // declarations in scope in the same way default function
1041 // arguments are (8.3.6).
1042 bool SawDefaultArgument = false;
1043 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001044
Anders Carlsson49d25572009-06-12 23:20:15 +00001045 bool SawParameterPack = false;
1046 SourceLocation ParameterPackLoc;
1047
Mike Stump1a35fde2009-02-11 23:03:27 +00001048 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001049 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001050 if (OldParams)
1051 OldParam = OldParams->begin();
1052
1053 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1054 NewParamEnd = NewParams->end();
1055 NewParam != NewParamEnd; ++NewParam) {
1056 // Variables used to diagnose redundant default arguments
1057 bool RedundantDefaultArg = false;
1058 SourceLocation OldDefaultLoc;
1059 SourceLocation NewDefaultLoc;
1060
1061 // Variables used to diagnose missing default arguments
1062 bool MissingDefaultArg = false;
1063
Anders Carlsson49d25572009-06-12 23:20:15 +00001064 // C++0x [temp.param]p11:
1065 // If a template parameter of a class template is a template parameter pack,
1066 // it must be the last template parameter.
1067 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001068 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001069 diag::err_template_param_pack_must_be_last_template_parameter);
1070 Invalid = true;
1071 }
1072
Douglas Gregord684b002009-02-10 19:49:53 +00001073 if (TemplateTypeParmDecl *NewTypeParm
1074 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001075 // Check the presence of a default argument here.
1076 if (NewTypeParm->hasDefaultArgument() &&
1077 DiagnoseDefaultTemplateArgument(*this, TPC,
1078 NewTypeParm->getLocation(),
1079 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001080 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001081 NewTypeParm->removeDefaultArgument();
1082
1083 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001084 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001085 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Anders Carlsson49d25572009-06-12 23:20:15 +00001087 if (NewTypeParm->isParameterPack()) {
1088 assert(!NewTypeParm->hasDefaultArgument() &&
1089 "Parameter packs can't have a default argument!");
1090 SawParameterPack = true;
1091 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001092 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001093 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001094 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1095 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1096 SawDefaultArgument = true;
1097 RedundantDefaultArg = true;
1098 PreviousDefaultArgLoc = NewDefaultLoc;
1099 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1100 // Merge the default argument from the old declaration to the
1101 // new declaration.
1102 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001103 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001104 true);
1105 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1106 } else if (NewTypeParm->hasDefaultArgument()) {
1107 SawDefaultArgument = true;
1108 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1109 } else if (SawDefaultArgument)
1110 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001111 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001112 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001113 // Check the presence of a default argument here.
1114 if (NewNonTypeParm->hasDefaultArgument() &&
1115 DiagnoseDefaultTemplateArgument(*this, TPC,
1116 NewNonTypeParm->getLocation(),
1117 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001118 NewNonTypeParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001119 }
1120
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001121 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001122 NonTypeTemplateParmDecl *OldNonTypeParm
1123 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001124 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001125 NewNonTypeParm->hasDefaultArgument()) {
1126 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1127 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1128 SawDefaultArgument = true;
1129 RedundantDefaultArg = true;
1130 PreviousDefaultArgLoc = NewDefaultLoc;
1131 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1132 // Merge the default argument from the old declaration to the
1133 // new declaration.
1134 SawDefaultArgument = true;
1135 // FIXME: We need to create a new kind of "default argument"
1136 // expression that points to a previous template template
1137 // parameter.
1138 NewNonTypeParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001139 OldNonTypeParm->getDefaultArgument(),
1140 /*Inherited=*/ true);
Douglas Gregord684b002009-02-10 19:49:53 +00001141 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1142 } else if (NewNonTypeParm->hasDefaultArgument()) {
1143 SawDefaultArgument = true;
1144 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1145 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001146 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001147 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001148 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001149 TemplateTemplateParmDecl *NewTemplateParm
1150 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001151 if (NewTemplateParm->hasDefaultArgument() &&
1152 DiagnoseDefaultTemplateArgument(*this, TPC,
1153 NewTemplateParm->getLocation(),
1154 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001155 NewTemplateParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001156
1157 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001158 TemplateTemplateParmDecl *OldTemplateParm
1159 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001160 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001161 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001162 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1163 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001164 SawDefaultArgument = true;
1165 RedundantDefaultArg = true;
1166 PreviousDefaultArgLoc = NewDefaultLoc;
1167 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1168 // Merge the default argument from the old declaration to the
1169 // new declaration.
1170 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001171 // FIXME: We need to create a new kind of "default argument" expression
1172 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001173 NewTemplateParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001174 OldTemplateParm->getDefaultArgument(),
1175 /*Inherited=*/ true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001176 PreviousDefaultArgLoc
1177 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001178 } else if (NewTemplateParm->hasDefaultArgument()) {
1179 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001180 PreviousDefaultArgLoc
1181 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001182 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001183 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001184 }
1185
1186 if (RedundantDefaultArg) {
1187 // C++ [temp.param]p12:
1188 // A template-parameter shall not be given default arguments
1189 // by two different declarations in the same scope.
1190 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1191 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1192 Invalid = true;
1193 } else if (MissingDefaultArg) {
1194 // C++ [temp.param]p11:
1195 // If a template-parameter has a default template-argument,
1196 // all subsequent template-parameters shall have a default
1197 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001198 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001199 diag::err_template_param_default_arg_missing);
1200 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1201 Invalid = true;
1202 }
1203
1204 // If we have an old template parameter list that we're merging
1205 // in, move on to the next parameter.
1206 if (OldParams)
1207 ++OldParam;
1208 }
1209
1210 return Invalid;
1211}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001212
Mike Stump1eb44332009-09-09 15:08:12 +00001213/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001214/// specifier, returning the template parameter list that applies to the
1215/// name.
1216///
1217/// \param DeclStartLoc the start of the declaration that has a scope
1218/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001219///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001220/// \param SS the scope specifier that will be matched to the given template
1221/// parameter lists. This scope specifier precedes a qualified name that is
1222/// being declared.
1223///
1224/// \param ParamLists the template parameter lists, from the outermost to the
1225/// innermost template parameter lists.
1226///
1227/// \param NumParamLists the number of template parameter lists in ParamLists.
1228///
John McCall77e8b112010-04-13 20:37:33 +00001229/// \param IsFriend Whether to apply the slightly different rules for
1230/// matching template parameters to scope specifiers in friend
1231/// declarations.
1232///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001233/// \param IsExplicitSpecialization will be set true if the entity being
1234/// declared is an explicit specialization, false otherwise.
1235///
Mike Stump1eb44332009-09-09 15:08:12 +00001236/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001237/// name that is preceded by the scope specifier @p SS. This template
1238/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001239/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001240/// template specialization), or may be NULL (if we were's declaring isn't
1241/// itself a template).
1242TemplateParameterList *
1243Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1244 const CXXScopeSpec &SS,
1245 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001246 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001247 bool IsFriend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001248 bool &IsExplicitSpecialization,
1249 bool &Invalid) {
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001250 IsExplicitSpecialization = false;
1251
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001252 // Find the template-ids that occur within the nested-name-specifier. These
1253 // template-ids will match up with the template parameter lists.
1254 llvm::SmallVector<const TemplateSpecializationType *, 4>
1255 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001256 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1257 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001258 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1259 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001260 const Type *T = NNS->getAsType();
1261 if (!T) break;
1262
1263 // C++0x [temp.expl.spec]p17:
1264 // A member or a member template may be nested within many
1265 // enclosing class templates. In an explicit specialization for
1266 // such a member, the member declaration shall be preceded by a
1267 // template<> for each enclosing class template that is
1268 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001269 //
1270 // Following the existing practice of GNU and EDG, we allow a typedef of a
1271 // template specialization type.
1272 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1273 T = TT->LookThroughTypedefs().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001274
Mike Stump1eb44332009-09-09 15:08:12 +00001275 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001276 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001277 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1278 if (!Template)
1279 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Ted Kremenek6217b802009-07-29 21:53:49 +00001281 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001282 ClassTemplateSpecializationDecl *SpecDecl
1283 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1284 // If the nested name specifier refers to an explicit specialization,
1285 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001286 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1287 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001288 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001289 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001290 }
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001292 TemplateIdsInSpecifier.push_back(SpecType);
1293 }
1294 }
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001296 // Reverse the list of template-ids in the scope specifier, so that we can
1297 // more easily match up the template-ids and the template parameter lists.
1298 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001299
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001300 SourceLocation FirstTemplateLoc = DeclStartLoc;
1301 if (NumParamLists)
1302 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001303
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001304 // Match the template-ids found in the specifier to the template parameter
1305 // lists.
1306 unsigned Idx = 0;
1307 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1308 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001309 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1310 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001311 if (Idx >= NumParamLists) {
1312 // We have a template-id without a corresponding template parameter
1313 // list.
John McCall77e8b112010-04-13 20:37:33 +00001314
1315 // ...which is fine if this is a friend declaration.
1316 if (IsFriend) {
1317 IsExplicitSpecialization = true;
1318 break;
1319 }
1320
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001321 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001322 // FIXME: the location information here isn't great.
1323 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001324 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001325 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001326 << SS.getRange();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001327 Invalid = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001328 } else {
1329 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1330 << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00001331 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001332 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001333 }
1334 return 0;
1335 }
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001337 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001338 if (DependentTemplateId) {
John McCall31f17ec2010-04-27 00:57:59 +00001339 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00001340
John McCall31f17ec2010-04-27 00:57:59 +00001341 // Are there cases in (e.g.) friends where this won't match?
1342 if (const InjectedClassNameType *Injected
1343 = TemplateId->getAs<InjectedClassNameType>()) {
1344 CXXRecordDecl *Record = Injected->getDecl();
1345 if (ClassTemplatePartialSpecializationDecl *Partial =
1346 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1347 ExpectedTemplateParams = Partial->getTemplateParameters();
1348 else
1349 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1350 ->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001351 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001352
John McCall31f17ec2010-04-27 00:57:59 +00001353 if (ExpectedTemplateParams)
1354 TemplateParameterListsAreEqual(ParamLists[Idx],
1355 ExpectedTemplateParams,
1356 true, TPL_TemplateMatch);
1357
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001358 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregorb88e8882009-07-30 17:40:51 +00001359 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001360 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001361 diag::err_template_param_list_matches_nontemplate)
1362 << TemplateId
1363 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001364 else
1365 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001366 }
Mike Stump1eb44332009-09-09 15:08:12 +00001367
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001368 // If there were at least as many template-ids as there were template
1369 // parameter lists, then there are no template parameter lists remaining for
1370 // the declaration itself.
Douglas Gregor72c4c152010-08-20 03:26:10 +00001371 if (Idx >= NumParamLists)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001372 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001373
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001374 // If there were too many template parameter lists, complain about that now.
1375 if (Idx != NumParamLists - 1) {
1376 while (Idx < NumParamLists - 1) {
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001377 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001378 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001379 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1380 : diag::err_template_spec_extra_headers)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001381 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1382 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001383
1384 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1385 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1386 diag::note_explicit_template_spec_does_not_need_header)
1387 << ExplicitSpecializationsInSpecifier.back();
1388 ExplicitSpecializationsInSpecifier.pop_back();
1389 }
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001390
1391 // We have a template parameter list with no corresponding scope, which
1392 // means that the resulting template declaration can't be instantiated
1393 // properly (we'll end up with dependent nodes when we shouldn't).
1394 if (!isExplicitSpecHeader)
1395 Invalid = true;
1396
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001397 ++Idx;
1398 }
1399 }
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001401 // Return the last template parameter list, which corresponds to the
1402 // entity being declared.
1403 return ParamLists[NumParamLists - 1];
1404}
1405
Douglas Gregor7532dc62009-03-30 22:58:21 +00001406QualType Sema::CheckTemplateIdType(TemplateName Name,
1407 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001408 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001409 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001410 if (!Template) {
1411 // The template name does not resolve to a template, so we just
1412 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001413 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001414 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001415
Douglas Gregor40808ce2009-03-09 23:48:35 +00001416 // Check that the template argument list is well-formed for this
1417 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001418 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCalld5532b62009-11-23 01:53:49 +00001419 TemplateArgs.size());
1420 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001421 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001422 return QualType();
1423
Mike Stump1eb44332009-09-09 15:08:12 +00001424 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001425 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001426 "Converted template argument list is too short!");
1427
1428 QualType CanonType;
1429
Douglas Gregorcaddba02009-11-12 18:38:13 +00001430 if (Name.isDependent() ||
1431 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001432 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001433 // This class template specialization is a dependent
1434 // type. Therefore, its canonical type is another class template
1435 // specialization type that contains all of the converted
1436 // arguments in canonical form. This ensures that, e.g., A<T> and
1437 // A<T, T> have identical types when A is declared as:
1438 //
1439 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001440 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001441 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001442 Converted.getFlatArguments(),
1443 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Douglas Gregor1275ae02009-07-28 23:00:59 +00001445 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001446 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001447 // In the future, we need to teach getTemplateSpecializationType to only
1448 // build the canonical type and return that to us.
1449 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001450
1451 // This might work out to be a current instantiation, in which
1452 // case the canonical type needs to be the InjectedClassNameType.
1453 //
1454 // TODO: in theory this could be a simple hashtable lookup; most
1455 // changes to CurContext don't change the set of current
1456 // instantiations.
1457 if (isa<ClassTemplateDecl>(Template)) {
1458 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1459 // If we get out to a namespace, we're done.
1460 if (Ctx->isFileContext()) break;
1461
1462 // If this isn't a record, keep looking.
1463 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1464 if (!Record) continue;
1465
1466 // Look for one of the two cases with InjectedClassNameTypes
1467 // and check whether it's the same template.
1468 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1469 !Record->getDescribedClassTemplate())
1470 continue;
1471
1472 // Fetch the injected class name type and check whether its
1473 // injected type is equal to the type we just built.
1474 QualType ICNT = Context.getTypeDeclType(Record);
1475 QualType Injected = cast<InjectedClassNameType>(ICNT)
1476 ->getInjectedSpecializationType();
1477
1478 if (CanonType != Injected->getCanonicalTypeInternal())
1479 continue;
1480
1481 // If so, the canonical type of this TST is the injected
1482 // class name type of the record we just found.
1483 assert(ICNT.isCanonical());
1484 CanonType = ICNT;
John McCall31f17ec2010-04-27 00:57:59 +00001485 break;
1486 }
1487 }
Mike Stump1eb44332009-09-09 15:08:12 +00001488 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001489 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001490 // Find the class template specialization declaration that
1491 // corresponds to these arguments.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001492 void *InsertPos = 0;
1493 ClassTemplateSpecializationDecl *Decl
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001494 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
1495 Converted.flatSize(), InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001496 if (!Decl) {
1497 // This is the first time we have referenced this class template
1498 // specialization. Create the canonical declaration and add it to
1499 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001500 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00001501 ClassTemplate->getTemplatedDecl()->getTagKind(),
1502 ClassTemplate->getDeclContext(),
1503 ClassTemplate->getLocation(),
1504 ClassTemplate,
1505 Converted, 0);
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001506 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001507 Decl->setLexicalDeclContext(CurContext);
1508 }
1509
1510 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001511 assert(isa<RecordType>(CanonType) &&
1512 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001513 }
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Douglas Gregor40808ce2009-03-09 23:48:35 +00001515 // Build the fully-sugared type for this class template
1516 // specialization, which refers back to the class template
1517 // specialization we created or found.
John McCall71d74bc2010-06-13 09:25:03 +00001518 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001519}
1520
Douglas Gregorcc636682009-02-17 23:15:12 +00001521Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001522Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001523 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001524 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001525 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001526 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001527
Douglas Gregor40808ce2009-03-09 23:48:35 +00001528 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001529 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001530 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001531
John McCalld5532b62009-11-23 01:53:49 +00001532 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001533 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001534
1535 if (Result.isNull())
1536 return true;
1537
John McCalla93c9342009-12-07 02:54:59 +00001538 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001539 TemplateSpecializationTypeLoc TL
1540 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1541 TL.setTemplateNameLoc(TemplateLoc);
1542 TL.setLAngleLoc(LAngleLoc);
1543 TL.setRAngleLoc(RAngleLoc);
1544 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1545 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1546
John McCallb3d87482010-08-24 05:47:05 +00001547 return CreateParsedType(Result, DI);
John McCall6b2becf2009-09-08 17:47:29 +00001548}
John McCallf1bbbb42009-09-04 01:14:41 +00001549
John McCall6b2becf2009-09-08 17:47:29 +00001550Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1551 TagUseKind TUK,
1552 DeclSpec::TST TagSpec,
1553 SourceLocation TagLoc) {
1554 if (TypeResult.isInvalid())
1555 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001556
John McCall833ca992009-10-29 08:12:44 +00001557 // FIXME: preserve source info, ideally without copying the DI.
John McCalla93c9342009-12-07 02:54:59 +00001558 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001559 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001560
John McCall6b2becf2009-09-08 17:47:29 +00001561 // Verify the tag specifier.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001562 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001563
John McCall6b2becf2009-09-08 17:47:29 +00001564 if (const RecordType *RT = Type->getAs<RecordType>()) {
1565 RecordDecl *D = RT->getDecl();
1566
1567 IdentifierInfo *Id = D->getIdentifier();
1568 assert(Id && "templated class must have an identifier");
1569
1570 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1571 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001572 << Type
Douglas Gregor849b2432010-03-31 17:46:05 +00001573 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001574 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001575 }
1576 }
1577
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001578 ElaboratedTypeKeyword Keyword
1579 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1580 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCall6b2becf2009-09-08 17:47:29 +00001581
John McCallb3d87482010-08-24 05:47:05 +00001582 return ParsedType::make(ElabType);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001583}
1584
John McCall60d7b3a2010-08-24 06:29:42 +00001585ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001586 LookupResult &R,
1587 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001588 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001589 // FIXME: Can we do any checking at this point? I guess we could check the
1590 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001591 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001592 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001593
1594 // These should be filtered out by our callers.
1595 assert(!R.empty() && "empty lookup results when building templateid");
1596 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1597
1598 NestedNameSpecifier *Qualifier = 0;
1599 SourceRange QualifierRange;
1600 if (SS.isSet()) {
1601 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1602 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001603 }
John McCallc373d482010-01-27 01:50:18 +00001604
1605 // We don't want lookup warnings at this point.
1606 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001607
John McCallf7a1a742009-11-24 19:00:30 +00001608 bool Dependent
1609 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1610 &TemplateArgs);
1611 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001612 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001613 Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00001614 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00001615 RequiresADL, TemplateArgs,
1616 R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001617
1618 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001619}
1620
John McCallf7a1a742009-11-24 19:00:30 +00001621// We actually only call this from template instantiation.
John McCall60d7b3a2010-08-24 06:29:42 +00001622ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001623Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001624 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +00001625 const TemplateArgumentListInfo &TemplateArgs) {
1626 DeclContext *DC;
1627 if (!(DC = computeDeclContext(SS, false)) ||
1628 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00001629 RequireCompleteDeclContext(SS, DC))
Abramo Bagnara25777432010-08-11 22:01:17 +00001630 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001631
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001632 bool MemberOfUnknownSpecialization;
Abramo Bagnara25777432010-08-11 22:01:17 +00001633 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001634 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1635 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00001636
John McCallf7a1a742009-11-24 19:00:30 +00001637 if (R.isAmbiguous())
1638 return ExprError();
1639
1640 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001641 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1642 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001643 return ExprError();
1644 }
1645
1646 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001647 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1648 << (NestedNameSpecifier*) SS.getScopeRep()
1649 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001650 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1651 return ExprError();
1652 }
1653
1654 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001655}
1656
Douglas Gregorc45c2322009-03-31 00:43:58 +00001657/// \brief Form a dependent template name.
1658///
1659/// This action forms a dependent template name given the template
1660/// name and its (presumably dependent) scope specifier. For
1661/// example, given "MetaFun::template apply", the scope specifier \p
1662/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1663/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001664TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1665 SourceLocation TemplateKWLoc,
1666 CXXScopeSpec &SS,
1667 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +00001668 ParsedType ObjectType,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001669 bool EnteringContext,
1670 TemplateTy &Result) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00001671 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1672 !getLangOptions().CPlusPlus0x)
1673 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1674 << FixItHint::CreateRemoval(TemplateKWLoc);
1675
Douglas Gregor0707bc52010-01-19 16:01:07 +00001676 DeclContext *LookupCtx = 0;
1677 if (SS.isSet())
1678 LookupCtx = computeDeclContext(SS, EnteringContext);
1679 if (!LookupCtx && ObjectType)
John McCallb3d87482010-08-24 05:47:05 +00001680 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor0707bc52010-01-19 16:01:07 +00001681 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001682 // C++0x [temp.names]p5:
1683 // If a name prefixed by the keyword template is not the name of
1684 // a template, the program is ill-formed. [Note: the keyword
1685 // template may not be applied to non-template members of class
1686 // templates. -end note ] [ Note: as is the case with the
1687 // typename prefix, the template prefix is allowed in cases
1688 // where it is not strictly necessary; i.e., when the
1689 // nested-name-specifier or the expression on the left of the ->
1690 // or . is not dependent on a template-parameter, or the use
1691 // does not appear in the scope of a template. -end note]
1692 //
1693 // Note: C++03 was more strict here, because it banned the use of
1694 // the "template" keyword prior to a template-name that was not a
1695 // dependent name. C++ DR468 relaxed this requirement (the
1696 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregor732281d2010-06-14 22:07:54 +00001697 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001698 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001699 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1700 ObjectType, EnteringContext, Result,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001701 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001702 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1703 isa<CXXRecordDecl>(LookupCtx) &&
1704 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord6ab2322010-06-16 23:00:59 +00001705 // This is a dependent template. Handle it below.
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001706 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001707 Diag(Name.getSourceRange().getBegin(),
1708 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001709 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001710 << Name.getSourceRange()
1711 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001712 return TNK_Non_template;
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001713 } else {
1714 // We found something; return it.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001715 return TNK;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001716 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001717 }
1718
Mike Stump1eb44332009-09-09 15:08:12 +00001719 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001720 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001721
1722 switch (Name.getKind()) {
1723 case UnqualifiedId::IK_Identifier:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001724 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1725 Name.Identifier));
1726 return TNK_Dependent_template_name;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001727
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001728 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001729 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001730 Name.OperatorFunctionId.Operator));
Douglas Gregord6ab2322010-06-16 23:00:59 +00001731 return TNK_Dependent_template_name;
Sean Hunte6252d12009-11-28 08:58:14 +00001732
1733 case UnqualifiedId::IK_LiteralOperatorId:
1734 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1735
Douglas Gregor014e88d2009-11-03 23:16:33 +00001736 default:
1737 break;
1738 }
1739
1740 Diag(Name.getSourceRange().getBegin(),
1741 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001742 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001743 << Name.getSourceRange()
1744 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001745 return TNK_Non_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001746}
1747
Mike Stump1eb44332009-09-09 15:08:12 +00001748bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001749 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001750 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001751 const TemplateArgument &Arg = AL.getArgument();
1752
Anders Carlsson436b1562009-06-13 00:33:33 +00001753 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001754 switch(Arg.getKind()) {
1755 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00001756 // C++ [temp.arg.type]p1:
1757 // A template-argument for a template-parameter which is a
1758 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001759 break;
1760 case TemplateArgument::Template: {
1761 // We have a template type parameter but the template argument
1762 // is a template without any arguments.
1763 SourceRange SR = AL.getSourceRange();
1764 TemplateName Name = Arg.getAsTemplate();
1765 Diag(SR.getBegin(), diag::err_template_missing_args)
1766 << Name << SR;
1767 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1768 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00001769
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001770 return true;
1771 }
1772 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00001773 // We have a template type parameter but the template argument
1774 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001775 SourceRange SR = AL.getSourceRange();
1776 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001777 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Anders Carlsson436b1562009-06-13 00:33:33 +00001779 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001780 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001781 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001782
John McCalla93c9342009-12-07 02:54:59 +00001783 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001784 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Anders Carlsson436b1562009-06-13 00:33:33 +00001786 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001787 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001788 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001789 return false;
1790}
1791
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001792/// \brief Substitute template arguments into the default template argument for
1793/// the given template type parameter.
1794///
1795/// \param SemaRef the semantic analysis object for which we are performing
1796/// the substitution.
1797///
1798/// \param Template the template that we are synthesizing template arguments
1799/// for.
1800///
1801/// \param TemplateLoc the location of the template name that started the
1802/// template-id we are checking.
1803///
1804/// \param RAngleLoc the location of the right angle bracket ('>') that
1805/// terminates the template-id.
1806///
1807/// \param Param the template template parameter whose default we are
1808/// substituting into.
1809///
1810/// \param Converted the list of template arguments provided for template
1811/// parameters that precede \p Param in the template parameter list.
1812///
1813/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001814static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001815SubstDefaultTemplateArgument(Sema &SemaRef,
1816 TemplateDecl *Template,
1817 SourceLocation TemplateLoc,
1818 SourceLocation RAngleLoc,
1819 TemplateTypeParmDecl *Param,
1820 TemplateArgumentListBuilder &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001821 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001822
1823 // If the argument type is dependent, instantiate it now based
1824 // on the previously-computed template arguments.
1825 if (ArgType->getType()->isDependentType()) {
1826 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1827 /*TakeArgs=*/false);
1828
1829 MultiLevelTemplateArgumentList AllTemplateArgs
1830 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1831
1832 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1833 Template, Converted.getFlatArguments(),
1834 Converted.flatSize(),
1835 SourceRange(TemplateLoc, RAngleLoc));
1836
1837 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1838 Param->getDefaultArgumentLoc(),
1839 Param->getDeclName());
1840 }
1841
1842 return ArgType;
1843}
1844
1845/// \brief Substitute template arguments into the default template argument for
1846/// the given non-type template parameter.
1847///
1848/// \param SemaRef the semantic analysis object for which we are performing
1849/// the substitution.
1850///
1851/// \param Template the template that we are synthesizing template arguments
1852/// for.
1853///
1854/// \param TemplateLoc the location of the template name that started the
1855/// template-id we are checking.
1856///
1857/// \param RAngleLoc the location of the right angle bracket ('>') that
1858/// terminates the template-id.
1859///
Douglas Gregor788cd062009-11-11 01:00:40 +00001860/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001861/// substituting into.
1862///
1863/// \param Converted the list of template arguments provided for template
1864/// parameters that precede \p Param in the template parameter list.
1865///
1866/// \returns the substituted template argument, or NULL if an error occurred.
John McCall60d7b3a2010-08-24 06:29:42 +00001867static ExprResult
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001868SubstDefaultTemplateArgument(Sema &SemaRef,
1869 TemplateDecl *Template,
1870 SourceLocation TemplateLoc,
1871 SourceLocation RAngleLoc,
1872 NonTypeTemplateParmDecl *Param,
1873 TemplateArgumentListBuilder &Converted) {
1874 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1875 /*TakeArgs=*/false);
1876
1877 MultiLevelTemplateArgumentList AllTemplateArgs
1878 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1879
1880 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1881 Template, Converted.getFlatArguments(),
1882 Converted.flatSize(),
1883 SourceRange(TemplateLoc, RAngleLoc));
1884
1885 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1886}
1887
Douglas Gregor788cd062009-11-11 01:00:40 +00001888/// \brief Substitute template arguments into the default template argument for
1889/// the given template template parameter.
1890///
1891/// \param SemaRef the semantic analysis object for which we are performing
1892/// the substitution.
1893///
1894/// \param Template the template that we are synthesizing template arguments
1895/// for.
1896///
1897/// \param TemplateLoc the location of the template name that started the
1898/// template-id we are checking.
1899///
1900/// \param RAngleLoc the location of the right angle bracket ('>') that
1901/// terminates the template-id.
1902///
1903/// \param Param the template template parameter whose default we are
1904/// substituting into.
1905///
1906/// \param Converted the list of template arguments provided for template
1907/// parameters that precede \p Param in the template parameter list.
1908///
1909/// \returns the substituted template argument, or NULL if an error occurred.
1910static TemplateName
1911SubstDefaultTemplateArgument(Sema &SemaRef,
1912 TemplateDecl *Template,
1913 SourceLocation TemplateLoc,
1914 SourceLocation RAngleLoc,
1915 TemplateTemplateParmDecl *Param,
1916 TemplateArgumentListBuilder &Converted) {
1917 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1918 /*TakeArgs=*/false);
1919
1920 MultiLevelTemplateArgumentList AllTemplateArgs
1921 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1922
1923 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1924 Template, Converted.getFlatArguments(),
1925 Converted.flatSize(),
1926 SourceRange(TemplateLoc, RAngleLoc));
1927
1928 return SemaRef.SubstTemplateName(
1929 Param->getDefaultArgument().getArgument().getAsTemplate(),
1930 Param->getDefaultArgument().getTemplateNameLoc(),
1931 AllTemplateArgs);
1932}
1933
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001934/// \brief If the given template parameter has a default template
1935/// argument, substitute into that default template argument and
1936/// return the corresponding template argument.
1937TemplateArgumentLoc
1938Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1939 SourceLocation TemplateLoc,
1940 SourceLocation RAngleLoc,
1941 Decl *Param,
1942 TemplateArgumentListBuilder &Converted) {
1943 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1944 if (!TypeParm->hasDefaultArgument())
1945 return TemplateArgumentLoc();
1946
John McCalla93c9342009-12-07 02:54:59 +00001947 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001948 TemplateLoc,
1949 RAngleLoc,
1950 TypeParm,
1951 Converted);
1952 if (DI)
1953 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1954
1955 return TemplateArgumentLoc();
1956 }
1957
1958 if (NonTypeTemplateParmDecl *NonTypeParm
1959 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1960 if (!NonTypeParm->hasDefaultArgument())
1961 return TemplateArgumentLoc();
1962
John McCall60d7b3a2010-08-24 06:29:42 +00001963 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001964 TemplateLoc,
1965 RAngleLoc,
1966 NonTypeParm,
1967 Converted);
1968 if (Arg.isInvalid())
1969 return TemplateArgumentLoc();
1970
1971 Expr *ArgE = Arg.takeAs<Expr>();
1972 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1973 }
1974
1975 TemplateTemplateParmDecl *TempTempParm
1976 = cast<TemplateTemplateParmDecl>(Param);
1977 if (!TempTempParm->hasDefaultArgument())
1978 return TemplateArgumentLoc();
1979
1980 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1981 TemplateLoc,
1982 RAngleLoc,
1983 TempTempParm,
1984 Converted);
1985 if (TName.isNull())
1986 return TemplateArgumentLoc();
1987
1988 return TemplateArgumentLoc(TemplateArgument(TName),
1989 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1990 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1991}
1992
Douglas Gregore7526412009-11-11 19:31:23 +00001993/// \brief Check that the given template argument corresponds to the given
1994/// template parameter.
1995bool Sema::CheckTemplateArgument(NamedDecl *Param,
1996 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00001997 TemplateDecl *Template,
1998 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00001999 SourceLocation RAngleLoc,
Douglas Gregor02024a92010-03-28 02:42:43 +00002000 TemplateArgumentListBuilder &Converted,
2001 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002002 // Check template type parameters.
2003 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002004 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00002005
Douglas Gregord9e15302009-11-11 19:41:09 +00002006 // Check non-type template parameters.
2007 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002008 // Do substitution on the type of the non-type template parameter
2009 // with the template arguments we've seen thus far.
2010 QualType NTTPType = NTTP->getType();
2011 if (NTTPType->isDependentType()) {
2012 // Do substitution on the type of the non-type template parameter.
2013 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2014 NTTP, Converted.getFlatArguments(),
2015 Converted.flatSize(),
2016 SourceRange(TemplateLoc, RAngleLoc));
2017
2018 TemplateArgumentList TemplateArgs(Context, Converted,
2019 /*TakeArgs=*/false);
2020 NTTPType = SubstType(NTTPType,
2021 MultiLevelTemplateArgumentList(TemplateArgs),
2022 NTTP->getLocation(),
2023 NTTP->getDeclName());
2024 // If that worked, check the non-type template parameter type
2025 // for validity.
2026 if (!NTTPType.isNull())
2027 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2028 NTTP->getLocation());
2029 if (NTTPType.isNull())
2030 return true;
2031 }
2032
2033 switch (Arg.getArgument().getKind()) {
2034 case TemplateArgument::Null:
2035 assert(false && "Should never see a NULL template argument here");
2036 return true;
2037
2038 case TemplateArgument::Expression: {
2039 Expr *E = Arg.getArgument().getAsExpr();
2040 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002041 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00002042 return true;
2043
2044 Converted.Append(Result);
2045 break;
2046 }
2047
2048 case TemplateArgument::Declaration:
2049 case TemplateArgument::Integral:
2050 // We've already checked this template argument, so just copy
2051 // it to the list of converted arguments.
2052 Converted.Append(Arg.getArgument());
2053 break;
2054
2055 case TemplateArgument::Template:
2056 // We were given a template template argument. It may not be ill-formed;
2057 // see below.
2058 if (DependentTemplateName *DTN
2059 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2060 // We have a template argument such as \c T::template X, which we
2061 // parsed as a template template argument. However, since we now
2062 // know that we need a non-type template argument, convert this
Abramo Bagnara25777432010-08-11 22:01:17 +00002063 // template name into an expression.
2064
2065 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2066 Arg.getTemplateNameLoc());
2067
John McCallf7a1a742009-11-24 19:00:30 +00002068 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2069 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002070 Arg.getTemplateQualifierRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002071 NameInfo);
Douglas Gregore7526412009-11-11 19:31:23 +00002072
2073 TemplateArgument Result;
2074 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2075 return true;
2076
2077 Converted.Append(Result);
2078 break;
2079 }
2080
2081 // We have a template argument that actually does refer to a class
2082 // template, template alias, or template template parameter, and
2083 // therefore cannot be a non-type template argument.
2084 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2085 << Arg.getSourceRange();
2086
2087 Diag(Param->getLocation(), diag::note_template_param_here);
2088 return true;
2089
2090 case TemplateArgument::Type: {
2091 // We have a non-type template parameter but the template
2092 // argument is a type.
2093
2094 // C++ [temp.arg]p2:
2095 // In a template-argument, an ambiguity between a type-id and
2096 // an expression is resolved to a type-id, regardless of the
2097 // form of the corresponding template-parameter.
2098 //
2099 // We warn specifically about this case, since it can be rather
2100 // confusing for users.
2101 QualType T = Arg.getArgument().getAsType();
2102 SourceRange SR = Arg.getSourceRange();
2103 if (T->isFunctionType())
2104 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2105 else
2106 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2107 Diag(Param->getLocation(), diag::note_template_param_here);
2108 return true;
2109 }
2110
2111 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002112 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002113 break;
2114 }
2115
2116 return false;
2117 }
2118
2119
2120 // Check template template parameters.
2121 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2122
2123 // Substitute into the template parameter list of the template
2124 // template parameter, since previously-supplied template arguments
2125 // may appear within the template template parameter.
2126 {
2127 // Set up a template instantiation context.
2128 LocalInstantiationScope Scope(*this);
2129 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2130 TempParm, Converted.getFlatArguments(),
2131 Converted.flatSize(),
2132 SourceRange(TemplateLoc, RAngleLoc));
2133
2134 TemplateArgumentList TemplateArgs(Context, Converted,
2135 /*TakeArgs=*/false);
2136 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2137 SubstDecl(TempParm, CurContext,
2138 MultiLevelTemplateArgumentList(TemplateArgs)));
2139 if (!TempParm)
2140 return true;
2141
2142 // FIXME: TempParam is leaked.
2143 }
2144
2145 switch (Arg.getArgument().getKind()) {
2146 case TemplateArgument::Null:
2147 assert(false && "Should never see a NULL template argument here");
2148 return true;
2149
2150 case TemplateArgument::Template:
2151 if (CheckTemplateArgument(TempParm, Arg))
2152 return true;
2153
2154 Converted.Append(Arg.getArgument());
2155 break;
2156
2157 case TemplateArgument::Expression:
2158 case TemplateArgument::Type:
2159 // We have a template template parameter but the template
2160 // argument does not refer to a template.
2161 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2162 return true;
2163
2164 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002165 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002166 "Declaration argument with template template parameter");
2167 break;
2168 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002169 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002170 "Integral argument with template template parameter");
2171 break;
2172
2173 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002174 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002175 break;
2176 }
2177
2178 return false;
2179}
2180
Douglas Gregorc15cb382009-02-09 23:23:08 +00002181/// \brief Check that the given template argument list is well-formed
2182/// for specializing the given template.
2183bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2184 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002185 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002186 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002187 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002188 TemplateParameterList *Params = Template->getTemplateParameters();
2189 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002190 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002191 bool Invalid = false;
2192
John McCalld5532b62009-11-23 01:53:49 +00002193 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2194
Mike Stump1eb44332009-09-09 15:08:12 +00002195 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002196 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002197
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002198 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002199 (NumArgs < Params->getMinRequiredArguments() &&
2200 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002201 // FIXME: point at either the first arg beyond what we can handle,
2202 // or the '>', depending on whether we have too many or too few
2203 // arguments.
2204 SourceRange Range;
2205 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002206 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002207 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2208 << (NumArgs > NumParams)
2209 << (isa<ClassTemplateDecl>(Template)? 0 :
2210 isa<FunctionTemplateDecl>(Template)? 1 :
2211 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2212 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002213 Diag(Template->getLocation(), diag::note_template_decl_here)
2214 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002215 Invalid = true;
2216 }
Mike Stump1eb44332009-09-09 15:08:12 +00002217
2218 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002219 // [...] The type and form of each template-argument specified in
2220 // a template-id shall match the type and form specified for the
2221 // corresponding parameter declared by the template in its
2222 // template-parameter-list.
2223 unsigned ArgIdx = 0;
2224 for (TemplateParameterList::iterator Param = Params->begin(),
2225 ParamEnd = Params->end();
2226 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002227 if (ArgIdx > NumArgs && PartialTemplateArgs)
2228 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002229
Douglas Gregord9e15302009-11-11 19:41:09 +00002230 // If we have a template parameter pack, check every remaining template
2231 // argument against that template parameter pack.
2232 if ((*Param)->isTemplateParameterPack()) {
2233 Converted.BeginPack();
2234 for (; ArgIdx < NumArgs; ++ArgIdx) {
2235 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2236 TemplateLoc, RAngleLoc, Converted)) {
2237 Invalid = true;
2238 break;
2239 }
2240 }
2241 Converted.EndPack();
2242 continue;
2243 }
2244
Douglas Gregorf35f8282009-11-11 21:54:23 +00002245 if (ArgIdx < NumArgs) {
2246 // Check the template argument we were given.
2247 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2248 TemplateLoc, RAngleLoc, Converted))
2249 return true;
2250
2251 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002252 }
Douglas Gregore7526412009-11-11 19:31:23 +00002253
Douglas Gregorf35f8282009-11-11 21:54:23 +00002254 // We have a default template argument that we will use.
2255 TemplateArgumentLoc Arg;
2256
2257 // Retrieve the default template argument from the template
2258 // parameter. For each kind of template parameter, we substitute the
2259 // template arguments provided thus far and any "outer" template arguments
2260 // (when the template parameter was part of a nested template) into
2261 // the default argument.
2262 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2263 if (!TTP->hasDefaultArgument()) {
2264 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2265 break;
2266 }
2267
John McCalla93c9342009-12-07 02:54:59 +00002268 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002269 Template,
2270 TemplateLoc,
2271 RAngleLoc,
2272 TTP,
2273 Converted);
2274 if (!ArgType)
2275 return true;
2276
2277 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2278 ArgType);
2279 } else if (NonTypeTemplateParmDecl *NTTP
2280 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2281 if (!NTTP->hasDefaultArgument()) {
2282 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2283 break;
2284 }
2285
John McCall60d7b3a2010-08-24 06:29:42 +00002286 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002287 TemplateLoc,
2288 RAngleLoc,
2289 NTTP,
2290 Converted);
2291 if (E.isInvalid())
2292 return true;
2293
2294 Expr *Ex = E.takeAs<Expr>();
2295 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2296 } else {
2297 TemplateTemplateParmDecl *TempParm
2298 = cast<TemplateTemplateParmDecl>(*Param);
2299
2300 if (!TempParm->hasDefaultArgument()) {
2301 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2302 break;
2303 }
2304
2305 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2306 TemplateLoc,
2307 RAngleLoc,
2308 TempParm,
2309 Converted);
2310 if (Name.isNull())
2311 return true;
2312
2313 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2314 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2315 TempParm->getDefaultArgument().getTemplateNameLoc());
2316 }
2317
2318 // Introduce an instantiation record that describes where we are using
2319 // the default template argument.
2320 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2321 Converted.getFlatArguments(),
2322 Converted.flatSize(),
2323 SourceRange(TemplateLoc, RAngleLoc));
2324
2325 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002326 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002327 RAngleLoc, Converted))
2328 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002329 }
2330
2331 return Invalid;
2332}
2333
2334/// \brief Check a template argument against its corresponding
2335/// template type parameter.
2336///
2337/// This routine implements the semantics of C++ [temp.arg.type]. It
2338/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002339bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002340 TypeSourceInfo *ArgInfo) {
2341 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002342 QualType Arg = ArgInfo->getType();
2343
Douglas Gregorc15cb382009-02-09 23:23:08 +00002344 // C++ [temp.arg.type]p2:
2345 // A local type, a type with no linkage, an unnamed type or a type
2346 // compounded from any of these types shall not be used as a
2347 // template-argument for a template type-parameter.
2348 //
Douglas Gregor0fddb972010-05-22 16:17:30 +00002349 // FIXME: Perform the unnamed type check.
2350 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002351 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00002352 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002353 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00002354 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002355 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00002356 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002357 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall833ca992009-10-29 08:12:44 +00002358 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2359 << QualType(Tag, 0) << SR;
2360 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00002361 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall833ca992009-10-29 08:12:44 +00002362 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002363 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2364 return true;
Douglas Gregor0fddb972010-05-22 16:17:30 +00002365 } else if (Arg->isVariablyModifiedType()) {
2366 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2367 << Arg;
2368 return true;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002369 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00002370 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002371 }
2372
2373 return false;
2374}
2375
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002376/// \brief Checks whether the given template argument is the address
2377/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002378static bool
2379CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2380 NonTypeTemplateParmDecl *Param,
2381 QualType ParamType,
2382 Expr *ArgIn,
2383 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002384 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002385 Expr *Arg = ArgIn;
2386 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002387
2388 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002389 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002390 Arg = Cast->getSubExpr();
2391
2392 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002393 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002394 // A template-argument for a non-type, non-template
2395 // template-parameter shall be one of: [...]
2396 //
2397 // -- the address of an object or function with external
2398 // linkage, including function templates and function
2399 // template-ids but excluding non-static class members,
2400 // expressed as & id-expression where the & is optional if
2401 // the name refers to a function or array, or if the
2402 // corresponding template-parameter is a reference; or
2403 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002404
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002405 // Ignore (and complain about) any excess parentheses.
2406 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2407 if (!Invalid) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002408 S.Diag(Arg->getSourceRange().getBegin(),
2409 diag::err_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002410 << Arg->getSourceRange();
2411 Invalid = true;
2412 }
2413
2414 Arg = Parens->getSubExpr();
2415 }
2416
Douglas Gregorb7a09262010-04-01 18:32:35 +00002417 bool AddressTaken = false;
2418 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002419 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00002420 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002421 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb7a09262010-04-01 18:32:35 +00002422 AddressTaken = true;
2423 AddrOpLoc = UnOp->getOperatorLoc();
2424 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002425 } else
2426 DRE = dyn_cast<DeclRefExpr>(Arg);
2427
Douglas Gregorb7a09262010-04-01 18:32:35 +00002428 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002429 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2430 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002431 S.Diag(Param->getLocation(), diag::note_template_param_here);
2432 return true;
2433 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002434
2435 // Stop checking the precise nature of the argument if it is value dependent,
2436 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002437 if (Arg->isValueDependent()) {
2438 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth038cc392010-01-31 10:01:20 +00002439 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002440 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002441
Douglas Gregorb7a09262010-04-01 18:32:35 +00002442 if (!isa<ValueDecl>(DRE->getDecl())) {
2443 S.Diag(Arg->getSourceRange().getBegin(),
2444 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002445 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002446 S.Diag(Param->getLocation(), diag::note_template_param_here);
2447 return true;
2448 }
2449
2450 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002451
2452 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00002453 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2454 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002455 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002456 S.Diag(Param->getLocation(), diag::note_template_param_here);
2457 return true;
2458 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002459
2460 // Cannot refer to non-static member functions
2461 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00002462 if (!Method->isStatic()) {
2463 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002464 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002465 S.Diag(Param->getLocation(), diag::note_template_param_here);
2466 return true;
2467 }
Mike Stump1eb44332009-09-09 15:08:12 +00002468
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002469 // Functions must have external linkage.
2470 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002471 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002472 S.Diag(Arg->getSourceRange().getBegin(),
2473 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002474 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002475 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002476 << true;
2477 return true;
2478 }
2479
2480 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002481 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002482
Douglas Gregorb7a09262010-04-01 18:32:35 +00002483 // If the template parameter has pointer type, the function decays.
2484 if (ParamType->isPointerType() && !AddressTaken)
2485 ArgType = S.Context.getPointerType(Func->getType());
2486 else if (AddressTaken && ParamType->isReferenceType()) {
2487 // If we originally had an address-of operator, but the
2488 // parameter has reference type, complain and (if things look
2489 // like they will work) drop the address-of operator.
2490 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2491 ParamType.getNonReferenceType())) {
2492 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2493 << ParamType;
2494 S.Diag(Param->getLocation(), diag::note_template_param_here);
2495 return true;
2496 }
2497
2498 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2499 << ParamType
2500 << FixItHint::CreateRemoval(AddrOpLoc);
2501 S.Diag(Param->getLocation(), diag::note_template_param_here);
2502
2503 ArgType = Func->getType();
2504 }
2505 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002506 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002507 S.Diag(Arg->getSourceRange().getBegin(),
2508 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002509 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002510 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002511 << true;
2512 return true;
2513 }
2514
Douglas Gregorb7a09262010-04-01 18:32:35 +00002515 // A value of reference type is not an object.
2516 if (Var->getType()->isReferenceType()) {
2517 S.Diag(Arg->getSourceRange().getBegin(),
2518 diag::err_template_arg_reference_var)
2519 << Var->getType() << Arg->getSourceRange();
2520 S.Diag(Param->getLocation(), diag::note_template_param_here);
2521 return true;
2522 }
2523
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002524 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002525 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002526
2527 // If the template parameter has pointer type, we must have taken
2528 // the address of this object.
2529 if (ParamType->isReferenceType()) {
2530 if (AddressTaken) {
2531 // If we originally had an address-of operator, but the
2532 // parameter has reference type, complain and (if things look
2533 // like they will work) drop the address-of operator.
2534 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2535 ParamType.getNonReferenceType())) {
2536 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2537 << ParamType;
2538 S.Diag(Param->getLocation(), diag::note_template_param_here);
2539 return true;
2540 }
2541
2542 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2543 << ParamType
2544 << FixItHint::CreateRemoval(AddrOpLoc);
2545 S.Diag(Param->getLocation(), diag::note_template_param_here);
2546
2547 ArgType = Var->getType();
2548 }
2549 } else if (!AddressTaken && ParamType->isPointerType()) {
2550 if (Var->getType()->isArrayType()) {
2551 // Array-to-pointer decay.
2552 ArgType = S.Context.getArrayDecayedType(Var->getType());
2553 } else {
2554 // If the template parameter has pointer type but the address of
2555 // this object was not taken, complain and (possibly) recover by
2556 // taking the address of the entity.
2557 ArgType = S.Context.getPointerType(Var->getType());
2558 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2559 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2560 << ParamType;
2561 S.Diag(Param->getLocation(), diag::note_template_param_here);
2562 return true;
2563 }
2564
2565 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2566 << ParamType
2567 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2568
2569 S.Diag(Param->getLocation(), diag::note_template_param_here);
2570 }
2571 }
2572 } else {
2573 // We found something else, but we don't know specifically what it is.
2574 S.Diag(Arg->getSourceRange().getBegin(),
2575 diag::err_template_arg_not_object_or_func)
2576 << Arg->getSourceRange();
2577 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2578 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002579 }
Mike Stump1eb44332009-09-09 15:08:12 +00002580
Douglas Gregorb7a09262010-04-01 18:32:35 +00002581 if (ParamType->isPointerType() &&
2582 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2583 S.IsQualificationConversion(ArgType, ParamType)) {
2584 // For pointer-to-object types, qualification conversions are
2585 // permitted.
2586 } else {
2587 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2588 if (!ParamRef->getPointeeType()->isFunctionType()) {
2589 // C++ [temp.arg.nontype]p5b3:
2590 // For a non-type template-parameter of type reference to
2591 // object, no conversions apply. The type referred to by the
2592 // reference may be more cv-qualified than the (otherwise
2593 // identical) type of the template- argument. The
2594 // template-parameter is bound directly to the
2595 // template-argument, which shall be an lvalue.
2596
2597 // FIXME: Other qualifiers?
2598 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2599 unsigned ArgQuals = ArgType.getCVRQualifiers();
2600
2601 if ((ParamQuals | ArgQuals) != ParamQuals) {
2602 S.Diag(Arg->getSourceRange().getBegin(),
2603 diag::err_template_arg_ref_bind_ignores_quals)
2604 << ParamType << Arg->getType()
2605 << Arg->getSourceRange();
2606 S.Diag(Param->getLocation(), diag::note_template_param_here);
2607 return true;
2608 }
2609 }
2610 }
2611
2612 // At this point, the template argument refers to an object or
2613 // function with external linkage. We now need to check whether the
2614 // argument and parameter types are compatible.
2615 if (!S.Context.hasSameUnqualifiedType(ArgType,
2616 ParamType.getNonReferenceType())) {
2617 // We can't perform this conversion or binding.
2618 if (ParamType->isReferenceType())
2619 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2620 << ParamType << Arg->getType() << Arg->getSourceRange();
2621 else
2622 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2623 << Arg->getType() << ParamType << Arg->getSourceRange();
2624 S.Diag(Param->getLocation(), diag::note_template_param_here);
2625 return true;
2626 }
2627 }
2628
2629 // Create the template argument.
2630 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor77c13e02010-04-24 18:20:53 +00002631 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00002632 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002633}
2634
2635/// \brief Checks whether the given template argument is a pointer to
2636/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002637bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2638 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002639 bool Invalid = false;
2640
2641 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002642 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002643 Arg = Cast->getSubExpr();
2644
2645 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002646 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002647 // A template-argument for a non-type, non-template
2648 // template-parameter shall be one of: [...]
2649 //
2650 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002651 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002652
2653 // Ignore (and complain about) any excess parentheses.
2654 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2655 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002656 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002657 diag::err_template_arg_extra_parens)
2658 << Arg->getSourceRange();
2659 Invalid = true;
2660 }
2661
2662 Arg = Parens->getSubExpr();
2663 }
2664
Douglas Gregorcaddba02009-11-12 18:38:13 +00002665 // A pointer-to-member constant written &Class::member.
2666 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00002667 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002668 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2669 if (DRE && !DRE->getQualifier())
2670 DRE = 0;
2671 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002672 }
2673 // A constant of pointer-to-member type.
2674 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2675 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2676 if (VD->getType()->isMemberPointerType()) {
2677 if (isa<NonTypeTemplateParmDecl>(VD) ||
2678 (isa<VarDecl>(VD) &&
2679 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2680 if (Arg->isTypeDependent() || Arg->isValueDependent())
2681 Converted = TemplateArgument(Arg->Retain());
2682 else
2683 Converted = TemplateArgument(VD->getCanonicalDecl());
2684 return Invalid;
2685 }
2686 }
2687 }
2688
2689 DRE = 0;
2690 }
2691
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002692 if (!DRE)
2693 return Diag(Arg->getSourceRange().getBegin(),
2694 diag::err_template_arg_not_pointer_to_member_form)
2695 << Arg->getSourceRange();
2696
2697 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2698 assert((isa<FieldDecl>(DRE->getDecl()) ||
2699 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2700 "Only non-static member pointers can make it here");
2701
2702 // Okay: this is the address of a non-static member, and therefore
2703 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002704 if (Arg->isTypeDependent() || Arg->isValueDependent())
2705 Converted = TemplateArgument(Arg->Retain());
2706 else
2707 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002708 return Invalid;
2709 }
2710
2711 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002712 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002713 diag::err_template_arg_not_pointer_to_member_form)
2714 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002715 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002716 diag::note_template_arg_refers_here);
2717 return true;
2718}
2719
Douglas Gregorc15cb382009-02-09 23:23:08 +00002720/// \brief Check a template argument against its corresponding
2721/// non-type template parameter.
2722///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002723/// This routine implements the semantics of C++ [temp.arg.nontype].
2724/// It returns true if an error occurred, and false otherwise. \p
2725/// InstantiatedParamType is the type of the non-type template
2726/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002727///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002728/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002729bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002730 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00002731 TemplateArgument &Converted,
2732 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002733 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2734
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002735 // If either the parameter has a dependent type or the argument is
2736 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00002737 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2738 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002739 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002740 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002741 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002742
2743 // C++ [temp.arg.nontype]p5:
2744 // The following conversions are performed on each expression used
2745 // as a non-type template-argument. If a non-type
2746 // template-argument cannot be converted to the type of the
2747 // corresponding template-parameter then the program is
2748 // ill-formed.
2749 //
2750 // -- for a non-type template-parameter of integral or
2751 // enumeration type, integral promotions (4.5) and integral
2752 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002753 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002754 QualType ArgType = Arg->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002755 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002756 // C++ [temp.arg.nontype]p1:
2757 // A template-argument for a non-type, non-template
2758 // template-parameter shall be one of:
2759 //
2760 // -- an integral constant-expression of integral or enumeration
2761 // type; or
2762 // -- the name of a non-type template-parameter; or
2763 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002764 llvm::APSInt Value;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002765 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002766 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002767 diag::err_template_arg_not_integral_or_enumeral)
2768 << ArgType << Arg->getSourceRange();
2769 Diag(Param->getLocation(), diag::note_template_param_here);
2770 return true;
2771 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002772 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002773 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2774 << ArgType << Arg->getSourceRange();
2775 return true;
2776 }
2777
Douglas Gregor02024a92010-03-28 02:42:43 +00002778 // From here on out, all we care about are the unqualified forms
2779 // of the parameter and argument types.
2780 ParamType = ParamType.getUnqualifiedType();
2781 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002782
2783 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002784 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002785 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00002786 } else if (CTAK == CTAK_Deduced) {
2787 // C++ [temp.deduct.type]p17:
2788 // If, in the declaration of a function template with a non-type
2789 // template-parameter, the non-type template- parameter is used
2790 // in an expression in the function parameter-list and, if the
2791 // corresponding template-argument is deduced, the
2792 // template-argument type shall match the type of the
2793 // template-parameter exactly, except that a template-argument
2794 // deduced from an array bound may be of any integral type.
2795 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2796 << ArgType << ParamType;
2797 Diag(Param->getLocation(), diag::note_template_param_here);
2798 return true;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002799 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2800 !ParamType->isEnumeralType()) {
2801 // This is an integral promotion or conversion.
John McCall2de56d12010-08-25 11:45:40 +00002802 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002803 } else {
2804 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002805 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002806 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002807 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002808 Diag(Param->getLocation(), diag::note_template_param_here);
2809 return true;
2810 }
2811
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002812 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002813 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002814 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002815
2816 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002817 llvm::APSInt OldValue = Value;
2818
2819 // Coerce the template argument's value to the value it will have
2820 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002821 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002822 if (Value.getBitWidth() != AllowedBits)
2823 Value.extOrTrunc(AllowedBits);
2824 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002825
2826 // Complain if an unsigned parameter received a negative value.
2827 if (IntegerType->isUnsignedIntegerType()
2828 && (OldValue.isSigned() && OldValue.isNegative())) {
2829 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2830 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2831 << Arg->getSourceRange();
2832 Diag(Param->getLocation(), diag::note_template_param_here);
2833 }
2834
2835 // Complain if we overflowed the template parameter's type.
2836 unsigned RequiredBits;
2837 if (IntegerType->isUnsignedIntegerType())
2838 RequiredBits = OldValue.getActiveBits();
2839 else if (OldValue.isUnsigned())
2840 RequiredBits = OldValue.getActiveBits() + 1;
2841 else
2842 RequiredBits = OldValue.getMinSignedBits();
2843 if (RequiredBits > AllowedBits) {
2844 Diag(Arg->getSourceRange().getBegin(),
2845 diag::warn_template_arg_too_large)
2846 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2847 << Arg->getSourceRange();
2848 Diag(Param->getLocation(), diag::note_template_param_here);
2849 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002850 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002851
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002852 // Add the value of this argument to the list of converted
2853 // arguments. We use the bitwidth and signedness of the template
2854 // parameter.
2855 if (Arg->isValueDependent()) {
2856 // The argument is value-dependent. Create a new
2857 // TemplateArgument with the converted expression.
2858 Converted = TemplateArgument(Arg);
2859 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002860 }
2861
John McCall833ca992009-10-29 08:12:44 +00002862 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002863 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002864 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002865 return false;
2866 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002867
John McCall6bb80172010-03-30 21:47:33 +00002868 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2869
Douglas Gregorb7a09262010-04-01 18:32:35 +00002870 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2871 // from a template argument of type std::nullptr_t to a non-type
2872 // template parameter of type pointer to object, pointer to
2873 // function, or pointer-to-member, respectively.
2874 if (ArgType->isNullPtrType() &&
2875 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2876 Converted = TemplateArgument((NamedDecl *)0);
2877 return false;
2878 }
2879
Douglas Gregorb86b0572009-02-11 01:18:59 +00002880 // Handle pointer-to-function, reference-to-function, and
2881 // pointer-to-member-function all in (roughly) the same way.
2882 if (// -- For a non-type template-parameter of type pointer to
2883 // function, only the function-to-pointer conversion (4.3) is
2884 // applied. If the template-argument represents a set of
2885 // overloaded functions (or a pointer to such), the matching
2886 // function is selected from the set (13.4).
2887 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002888 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002889 // -- For a non-type template-parameter of type reference to
2890 // function, no conversions apply. If the template-argument
2891 // represents a set of overloaded functions, the matching
2892 // function is selected from the set (13.4).
2893 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002894 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002895 // -- For a non-type template-parameter of type pointer to
2896 // member function, no conversions apply. If the
2897 // template-argument represents a set of overloaded member
2898 // functions, the matching member function is selected from
2899 // the set (13.4).
2900 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002901 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002902 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002903
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002904 if (Arg->getType() == Context.OverloadTy) {
2905 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2906 true,
2907 FoundResult)) {
2908 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2909 return true;
2910
2911 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2912 ArgType = Arg->getType();
2913 } else
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002914 return true;
Douglas Gregora35284b2009-02-11 00:19:33 +00002915 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002916
Douglas Gregorb7a09262010-04-01 18:32:35 +00002917 if (!ParamType->isMemberPointerType())
2918 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2919 ParamType,
2920 Arg, Converted);
2921
2922 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCall2de56d12010-08-25 11:45:40 +00002923 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb7a09262010-04-01 18:32:35 +00002924 } else if (!Context.hasSameUnqualifiedType(ArgType,
2925 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002926 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002927 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002928 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002929 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002930 Diag(Param->getLocation(), diag::note_template_param_here);
2931 return true;
2932 }
Mike Stump1eb44332009-09-09 15:08:12 +00002933
Douglas Gregorb7a09262010-04-01 18:32:35 +00002934 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregora35284b2009-02-11 00:19:33 +00002935 }
2936
Chris Lattnerfe90de72009-02-20 21:37:53 +00002937 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002938 // -- for a non-type template-parameter of type pointer to
2939 // object, qualification conversions (4.4) and the
2940 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002941 // C++0x also allows a value of std::nullptr_t.
Eli Friedman13578692010-08-05 02:49:48 +00002942 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002943 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002944
Douglas Gregorb7a09262010-04-01 18:32:35 +00002945 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2946 ParamType,
2947 Arg, Converted);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002948 }
Mike Stump1eb44332009-09-09 15:08:12 +00002949
Ted Kremenek6217b802009-07-29 21:53:49 +00002950 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002951 // -- For a non-type template-parameter of type reference to
2952 // object, no conversions apply. The type referred to by the
2953 // reference may be more cv-qualified than the (otherwise
2954 // identical) type of the template-argument. The
2955 // template-parameter is bound directly to the
2956 // template-argument, which must be an lvalue.
Eli Friedman13578692010-08-05 02:49:48 +00002957 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002958 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002959
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002960 if (Arg->getType() == Context.OverloadTy) {
2961 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2962 ParamRefType->getPointeeType(),
2963 true,
2964 FoundResult)) {
2965 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2966 return true;
2967
2968 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2969 ArgType = Arg->getType();
2970 } else
Douglas Gregorb7a09262010-04-01 18:32:35 +00002971 return true;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002972 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002973
Douglas Gregorb7a09262010-04-01 18:32:35 +00002974 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2975 ParamType,
2976 Arg, Converted);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002977 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002978
2979 // -- For a non-type template-parameter of type pointer to data
2980 // member, qualification conversions (4.4) are applied.
2981 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2982
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002983 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002984 // Types match exactly: nothing more to do here.
2985 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCall2de56d12010-08-25 11:45:40 +00002986 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor658bbb52009-02-11 16:16:59 +00002987 } else {
2988 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002989 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00002990 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002991 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00002992 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002993 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00002994 }
2995
Douglas Gregorcaddba02009-11-12 18:38:13 +00002996 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002997}
2998
2999/// \brief Check a template argument against its corresponding
3000/// template template parameter.
3001///
3002/// This routine implements the semantics of C++ [temp.arg.template].
3003/// It returns true if an error occurred, and false otherwise.
3004bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00003005 const TemplateArgumentLoc &Arg) {
3006 TemplateName Name = Arg.getArgument().getAsTemplate();
3007 TemplateDecl *Template = Name.getAsTemplateDecl();
3008 if (!Template) {
3009 // Any dependent template name is fine.
3010 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3011 return false;
3012 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003013
3014 // C++ [temp.arg.template]p1:
3015 // A template-argument for a template template-parameter shall be
3016 // the name of a class template, expressed as id-expression. Only
3017 // primary class templates are considered when matching the
3018 // template template argument with the corresponding parameter;
3019 // partial specializations are not considered even if their
3020 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003021 //
3022 // Note that we also allow template template parameters here, which
3023 // will happen when we are dealing with, e.g., class template
3024 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00003025 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003026 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003027 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00003028 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00003029 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00003030 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003031 << Template;
3032 }
3033
3034 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3035 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00003036 true,
3037 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00003038 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00003039}
3040
Douglas Gregor02024a92010-03-28 02:42:43 +00003041/// \brief Given a non-type template argument that refers to a
3042/// declaration and the type of its corresponding non-type template
3043/// parameter, produce an expression that properly refers to that
3044/// declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00003045ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003046Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3047 QualType ParamType,
3048 SourceLocation Loc) {
3049 assert(Arg.getKind() == TemplateArgument::Declaration &&
3050 "Only declaration template arguments permitted here");
3051 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3052
3053 if (VD->getDeclContext()->isRecord() &&
3054 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3055 // If the value is a class member, we might have a pointer-to-member.
3056 // Determine whether the non-type template template parameter is of
3057 // pointer-to-member type. If so, we need to build an appropriate
3058 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3059 // would refer to the member itself.
3060 if (ParamType->isMemberPointerType()) {
3061 QualType ClassType
3062 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3063 NestedNameSpecifier *Qualifier
John McCall9ae2f072010-08-23 23:25:46 +00003064 = NestedNameSpecifier::Create(Context, 0, false,
3065 ClassType.getTypePtr());
Douglas Gregor02024a92010-03-28 02:42:43 +00003066 CXXScopeSpec SS;
3067 SS.setScopeRep(Qualifier);
John McCall60d7b3a2010-08-24 06:29:42 +00003068 ExprResult RefExpr = BuildDeclRefExpr(VD,
Douglas Gregor02024a92010-03-28 02:42:43 +00003069 VD->getType().getNonReferenceType(),
3070 Loc,
3071 &SS);
3072 if (RefExpr.isInvalid())
3073 return ExprError();
3074
John McCall2de56d12010-08-25 11:45:40 +00003075 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorc0c83002010-04-30 21:46:38 +00003076
3077 // We might need to perform a trailing qualification conversion, since
3078 // the element type on the parameter could be more qualified than the
3079 // element type in the expression we constructed.
3080 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3081 ParamType.getUnqualifiedType())) {
3082 Expr *RefE = RefExpr.takeAs<Expr>();
John McCall2de56d12010-08-25 11:45:40 +00003083 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorc0c83002010-04-30 21:46:38 +00003084 RefExpr = Owned(RefE);
3085 }
3086
Douglas Gregor02024a92010-03-28 02:42:43 +00003087 assert(!RefExpr.isInvalid() &&
3088 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00003089 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00003090 return move(RefExpr);
3091 }
3092 }
3093
3094 QualType T = VD->getType().getNonReferenceType();
3095 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003096 // When the non-type template parameter is a pointer, take the
3097 // address of the declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00003098 ExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003099 if (RefExpr.isInvalid())
3100 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003101
3102 if (T->isFunctionType() || T->isArrayType()) {
3103 // Decay functions and arrays.
3104 Expr *RefE = (Expr *)RefExpr.get();
3105 DefaultFunctionArrayConversion(RefE);
3106 if (RefE != RefExpr.get()) {
3107 RefExpr.release();
3108 RefExpr = Owned(RefE);
3109 }
3110
3111 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00003112 }
3113
Douglas Gregorb7a09262010-04-01 18:32:35 +00003114 // Take the address of everything else
John McCall2de56d12010-08-25 11:45:40 +00003115 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregor02024a92010-03-28 02:42:43 +00003116 }
3117
3118 // If the non-type template parameter has reference type, qualify the
3119 // resulting declaration reference with the extra qualifiers on the
3120 // type that the reference refers to.
3121 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3122 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3123
3124 return BuildDeclRefExpr(VD, T, Loc);
3125}
3126
3127/// \brief Construct a new expression that refers to the given
3128/// integral template argument with the given source-location
3129/// information.
3130///
3131/// This routine takes care of the mapping from an integral template
3132/// argument (which may have any integral type) to the appropriate
3133/// literal value.
John McCall60d7b3a2010-08-24 06:29:42 +00003134ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003135Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3136 SourceLocation Loc) {
3137 assert(Arg.getKind() == TemplateArgument::Integral &&
3138 "Operation is only value for integral template arguments");
3139 QualType T = Arg.getIntegralType();
3140 if (T->isCharType() || T->isWideCharType())
3141 return Owned(new (Context) CharacterLiteral(
3142 Arg.getAsIntegral()->getZExtValue(),
3143 T->isWideCharType(),
3144 T,
3145 Loc));
3146 if (T->isBooleanType())
3147 return Owned(new (Context) CXXBoolLiteralExpr(
3148 Arg.getAsIntegral()->getBoolValue(),
3149 T,
3150 Loc));
3151
3152 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3153}
3154
3155
Douglas Gregorddc29e12009-02-06 22:42:48 +00003156/// \brief Determine whether the given template parameter lists are
3157/// equivalent.
3158///
Mike Stump1eb44332009-09-09 15:08:12 +00003159/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00003160/// source code as part of a new template declaration.
3161///
3162/// \param Old The old template parameter list, typically found via
3163/// name lookup of the template declared with this template parameter
3164/// list.
3165///
3166/// \param Complain If true, this routine will produce a diagnostic if
3167/// the template parameter lists are not equivalent.
3168///
Douglas Gregorfb898e12009-11-12 16:20:59 +00003169/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00003170///
3171/// \param TemplateArgLoc If this source location is valid, then we
3172/// are actually checking the template parameter list of a template
3173/// argument (New) against the template parameter list of its
3174/// corresponding template template parameter (Old). We produce
3175/// slightly different diagnostics in this scenario.
3176///
Douglas Gregorddc29e12009-02-06 22:42:48 +00003177/// \returns True if the template parameter lists are equal, false
3178/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003179bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00003180Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3181 TemplateParameterList *Old,
3182 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003183 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003184 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003185 if (Old->size() != New->size()) {
3186 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003187 unsigned NextDiag = diag::err_template_param_list_different_arity;
3188 if (TemplateArgLoc.isValid()) {
3189 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3190 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00003191 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003192 Diag(New->getTemplateLoc(), NextDiag)
3193 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00003194 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003195 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00003196 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003197 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003198 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3199 }
3200
3201 return false;
3202 }
3203
3204 for (TemplateParameterList::iterator OldParm = Old->begin(),
3205 OldParmEnd = Old->end(), NewParm = New->begin();
3206 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3207 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003208 if (Complain) {
3209 unsigned NextDiag = diag::err_template_param_different_kind;
3210 if (TemplateArgLoc.isValid()) {
3211 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3212 NextDiag = diag::note_template_param_different_kind;
3213 }
3214 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003215 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003216 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003217 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00003218 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003219 return false;
3220 }
3221
Douglas Gregora417b872010-06-04 08:34:32 +00003222 if (TemplateTypeParmDecl *OldTTP
3223 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3224 // Template type parameters are equivalent if either both are template
3225 // type parameter packs or neither are (since we know we're at the same
3226 // index).
3227 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3228 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3229 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3230 // allow one to match a template parameter pack in the template
3231 // parameter list of a template template parameter to one or more
3232 // template parameters in the template parameter list of the
3233 // corresponding template template argument.
3234 if (Complain) {
3235 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3236 if (TemplateArgLoc.isValid()) {
3237 Diag(TemplateArgLoc,
3238 diag::err_template_arg_template_params_mismatch);
3239 NextDiag = diag::note_template_parameter_pack_non_pack;
3240 }
3241 Diag(NewTTP->getLocation(), NextDiag)
3242 << 0 << NewTTP->isParameterPack();
3243 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3244 << 0 << OldTTP->isParameterPack();
3245 }
3246 return false;
3247 }
Mike Stump1eb44332009-09-09 15:08:12 +00003248 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003249 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3250 // The types of non-type template parameters must agree.
3251 NonTypeTemplateParmDecl *NewNTTP
3252 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00003253
3254 // If we are matching a template template argument to a template
3255 // template parameter and one of the non-type template parameter types
3256 // is dependent, then we must wait until template instantiation time
3257 // to actually compare the arguments.
3258 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3259 (OldNTTP->getType()->isDependentType() ||
3260 NewNTTP->getType()->isDependentType()))
3261 continue;
3262
Douglas Gregorddc29e12009-02-06 22:42:48 +00003263 if (Context.getCanonicalType(OldNTTP->getType()) !=
3264 Context.getCanonicalType(NewNTTP->getType())) {
3265 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003266 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3267 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003268 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003269 diag::err_template_arg_template_params_mismatch);
3270 NextDiag = diag::note_template_nontype_parm_different_type;
3271 }
3272 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003273 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00003274 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00003275 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00003276 diag::note_template_nontype_parm_prev_declaration)
3277 << OldNTTP->getType();
3278 }
3279 return false;
3280 }
3281 } else {
3282 // The template parameter lists of template template
3283 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00003284 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00003285 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00003286 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003287 = cast<TemplateTemplateParmDecl>(*OldParm);
3288 TemplateTemplateParmDecl *NewTTP
3289 = cast<TemplateTemplateParmDecl>(*NewParm);
3290 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3291 OldTTP->getTemplateParameters(),
3292 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003293 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00003294 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003295 return false;
3296 }
3297 }
3298
3299 return true;
3300}
3301
3302/// \brief Check whether a template can be declared within this scope.
3303///
3304/// If the template declaration is valid in this scope, returns
3305/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003306bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003307Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003308 // Find the nearest enclosing declaration scope.
3309 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3310 (S->getFlags() & Scope::TemplateParamScope) != 0)
3311 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003312
Douglas Gregorddc29e12009-02-06 22:42:48 +00003313 // C++ [temp]p2:
3314 // A template-declaration can appear only as a namespace scope or
3315 // class scope declaration.
3316 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003317 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3318 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003319 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003320 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003321
Eli Friedman1503f772009-07-31 01:43:05 +00003322 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003323 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003324
3325 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3326 return false;
3327
Mike Stump1eb44332009-09-09 15:08:12 +00003328 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003329 diag::err_template_outside_namespace_or_class_scope)
3330 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003331}
Douglas Gregorcc636682009-02-17 23:15:12 +00003332
Douglas Gregord5cb8762009-10-07 00:13:32 +00003333/// \brief Determine what kind of template specialization the given declaration
3334/// is.
3335static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3336 if (!D)
3337 return TSK_Undeclared;
3338
Douglas Gregorf6b11852009-10-08 15:14:33 +00003339 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3340 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003341 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3342 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003343 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3344 return Var->getTemplateSpecializationKind();
3345
Douglas Gregord5cb8762009-10-07 00:13:32 +00003346 return TSK_Undeclared;
3347}
3348
Douglas Gregor9302da62009-10-14 23:50:59 +00003349/// \brief Check whether a specialization is well-formed in the current
3350/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003351///
Douglas Gregor9302da62009-10-14 23:50:59 +00003352/// This routine determines whether a template specialization can be declared
3353/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003354///
3355/// \param S the semantic analysis object for which this check is being
3356/// performed.
3357///
3358/// \param Specialized the entity being specialized or instantiated, which
3359/// may be a kind of template (class template, function template, etc.) or
3360/// a member of a class template (member function, static data member,
3361/// member class).
3362///
3363/// \param PrevDecl the previous declaration of this entity, if any.
3364///
3365/// \param Loc the location of the explicit specialization or instantiation of
3366/// this entity.
3367///
3368/// \param IsPartialSpecialization whether this is a partial specialization of
3369/// a class template.
3370///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003371/// \returns true if there was an error that we cannot recover from, false
3372/// otherwise.
3373static bool CheckTemplateSpecializationScope(Sema &S,
3374 NamedDecl *Specialized,
3375 NamedDecl *PrevDecl,
3376 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003377 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003378 // Keep these "kind" numbers in sync with the %select statements in the
3379 // various diagnostics emitted by this routine.
3380 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003381 bool isTemplateSpecialization = false;
3382 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003383 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003384 isTemplateSpecialization = true;
3385 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003386 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003387 isTemplateSpecialization = true;
3388 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003389 EntityKind = 3;
3390 else if (isa<VarDecl>(Specialized))
3391 EntityKind = 4;
3392 else if (isa<RecordDecl>(Specialized))
3393 EntityKind = 5;
3394 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003395 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3396 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003397 return true;
3398 }
3399
Douglas Gregor88b70942009-02-25 22:02:03 +00003400 // C++ [temp.expl.spec]p2:
3401 // An explicit specialization shall be declared in the namespace
3402 // of which the template is a member, or, for member templates, in
3403 // the namespace of which the enclosing class or enclosing class
3404 // template is a member. An explicit specialization of a member
3405 // function, member class or static data member of a class
3406 // template shall be declared in the namespace of which the class
3407 // template is a member. Such a declaration may also be a
3408 // definition. If the declaration is not a definition, the
3409 // specialization may be defined later in the name- space in which
3410 // the explicit specialization was declared, or in a namespace
3411 // that encloses the one in which the explicit specialization was
3412 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003413 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3414 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003415 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003416 return true;
3417 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003418
Douglas Gregor0a407472009-10-07 17:30:37 +00003419 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3420 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003421 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003422 return true;
3423 }
3424
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003425 // C++ [temp.class.spec]p6:
3426 // A class template partial specialization may be declared or redeclared
3427 // in any namespace scope in which its definition may be defined (14.5.1
3428 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003429 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003430 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003431 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003432 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003433 if ((!PrevDecl ||
3434 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3435 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3436 // There is no prior declaration of this entity, so this
3437 // specialization must be in the same context as the template
3438 // itself.
3439 if (!DC->Equals(SpecializedContext)) {
3440 if (isa<TranslationUnitDecl>(SpecializedContext))
3441 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3442 << EntityKind << Specialized;
3443 else if (isa<NamespaceDecl>(SpecializedContext))
3444 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3445 << EntityKind << Specialized
3446 << cast<NamedDecl>(SpecializedContext);
3447
3448 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3449 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003450 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003451 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003452
3453 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003454 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003455 // Note that HandleDeclarator() performs this check for explicit
3456 // specializations of function templates, static data members, and member
3457 // functions, so we skip the check here for those kinds of entities.
3458 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003459 // Should we refactor that check, so that it occurs later?
3460 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003461 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3462 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003463 if (isa<TranslationUnitDecl>(SpecializedContext))
3464 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3465 << EntityKind << Specialized;
3466 else if (isa<NamespaceDecl>(SpecializedContext))
3467 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3468 << EntityKind << Specialized
3469 << cast<NamedDecl>(SpecializedContext);
3470
Douglas Gregor9302da62009-10-14 23:50:59 +00003471 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003472 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003473
3474 // FIXME: check for specialization-after-instantiation errors and such.
3475
Douglas Gregor88b70942009-02-25 22:02:03 +00003476 return false;
3477}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003478
Douglas Gregore94866f2009-06-12 21:21:02 +00003479/// \brief Check the non-type template arguments of a class template
3480/// partial specialization according to C++ [temp.class.spec]p9.
3481///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003482/// \param TemplateParams the template parameters of the primary class
3483/// template.
3484///
3485/// \param TemplateArg the template arguments of the class template
3486/// partial specialization.
3487///
3488/// \param MirrorsPrimaryTemplate will be set true if the class
3489/// template partial specialization arguments are identical to the
3490/// implicit template arguments of the primary template. This is not
3491/// necessarily an error (C++0x), and it is left to the caller to diagnose
3492/// this condition when it is an error.
3493///
Douglas Gregore94866f2009-06-12 21:21:02 +00003494/// \returns true if there was an error, false otherwise.
3495bool Sema::CheckClassTemplatePartialSpecializationArgs(
3496 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00003497 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003498 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003499 // FIXME: the interface to this function will have to change to
3500 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003501 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003502
Anders Carlssonfb250522009-06-23 01:26:57 +00003503 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00003504
Douglas Gregore94866f2009-06-12 21:21:02 +00003505 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003506 // Determine whether the template argument list of the partial
3507 // specialization is identical to the implicit argument list of
3508 // the primary template. The caller may need to diagnostic this as
3509 // an error per C++ [temp.class.spec]p9b3.
3510 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003511 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003512 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3513 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003514 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003515 MirrorsPrimaryTemplate = false;
3516 } else if (TemplateTemplateParmDecl *TTP
3517 = dyn_cast<TemplateTemplateParmDecl>(
3518 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003519 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003520 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003521 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003522 if (!ArgDecl ||
3523 ArgDecl->getIndex() != TTP->getIndex() ||
3524 ArgDecl->getDepth() != TTP->getDepth())
3525 MirrorsPrimaryTemplate = false;
3526 }
3527 }
3528
Mike Stump1eb44332009-09-09 15:08:12 +00003529 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003530 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003531 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003532 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003533 }
3534
Anders Carlsson6360be72009-06-13 18:20:51 +00003535 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003536 if (!ArgExpr) {
3537 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003538 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003539 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003540
3541 // C++ [temp.class.spec]p8:
3542 // A non-type argument is non-specialized if it is the name of a
3543 // non-type parameter. All other non-type arguments are
3544 // specialized.
3545 //
3546 // Below, we check the two conditions that only apply to
3547 // specialized non-type arguments, so skip any non-specialized
3548 // arguments.
3549 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003550 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003551 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003552 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003553 (Param->getIndex() != NTTP->getIndex() ||
3554 Param->getDepth() != NTTP->getDepth()))
3555 MirrorsPrimaryTemplate = false;
3556
Douglas Gregore94866f2009-06-12 21:21:02 +00003557 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003558 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003559
3560 // C++ [temp.class.spec]p9:
3561 // Within the argument list of a class template partial
3562 // specialization, the following restrictions apply:
3563 // -- A partially specialized non-type argument expression
3564 // shall not involve a template parameter of the partial
3565 // specialization except when the argument expression is a
3566 // simple identifier.
3567 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003568 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003569 diag::err_dependent_non_type_arg_in_partial_spec)
3570 << ArgExpr->getSourceRange();
3571 return true;
3572 }
3573
3574 // -- The type of a template parameter corresponding to a
3575 // specialized non-type argument shall not be dependent on a
3576 // parameter of the specialization.
3577 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003578 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003579 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3580 << Param->getType()
3581 << ArgExpr->getSourceRange();
3582 Diag(Param->getLocation(), diag::note_template_param_here);
3583 return true;
3584 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003585
3586 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003587 }
3588
3589 return false;
3590}
3591
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003592/// \brief Retrieve the previous declaration of the given declaration.
3593static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3594 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3595 return VD->getPreviousDeclaration();
3596 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3597 return FD->getPreviousDeclaration();
3598 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3599 return TD->getPreviousDeclaration();
3600 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3601 return TD->getPreviousDeclaration();
3602 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3603 return FTD->getPreviousDeclaration();
3604 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3605 return CTD->getPreviousDeclaration();
3606 return 0;
3607}
3608
John McCalld226f652010-08-21 09:40:31 +00003609DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003610Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3611 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00003612 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003613 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003614 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00003615 SourceLocation TemplateNameLoc,
3616 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00003617 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00003618 SourceLocation RAngleLoc,
3619 AttributeList *Attr,
3620 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003621 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00003622
Douglas Gregorcc636682009-02-17 23:15:12 +00003623 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00003624 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003625 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00003626 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3627
3628 if (!ClassTemplate) {
3629 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3630 << (Name.getAsTemplateDecl() &&
3631 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3632 return true;
3633 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003634
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003635 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003636 bool isPartialSpecialization = false;
3637
Douglas Gregor88b70942009-02-25 22:02:03 +00003638 // Check the validity of the template headers that introduce this
3639 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003640 // FIXME: We probably shouldn't complain about these headers for
3641 // friend declarations.
Douglas Gregor0167f3c2010-07-14 23:14:12 +00003642 bool Invalid = false;
Douglas Gregor05396e22009-08-25 17:23:04 +00003643 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00003644 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3645 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003646 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00003647 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00003648 isExplicitSpecialization,
3649 Invalid);
3650 if (Invalid)
3651 return true;
3652
Abramo Bagnara9b934882010-06-12 08:15:14 +00003653 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3654 if (TemplateParams)
3655 --NumMatchedTemplateParamLists;
3656
Douglas Gregor05396e22009-08-25 17:23:04 +00003657 if (TemplateParams && TemplateParams->size() > 0) {
3658 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003659
Douglas Gregor05396e22009-08-25 17:23:04 +00003660 // C++ [temp.class.spec]p10:
3661 // The template parameter list of a specialization shall not
3662 // contain default template argument values.
3663 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3664 Decl *Param = TemplateParams->getParam(I);
3665 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3666 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003667 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003668 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00003669 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003670 }
3671 } else if (NonTypeTemplateParmDecl *NTTP
3672 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3673 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003674 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003675 diag::err_default_arg_in_partial_spec)
3676 << DefArg->getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00003677 NTTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003678 }
3679 } else {
3680 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003681 if (TTP->hasDefaultArgument()) {
3682 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003683 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003684 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00003685 TTP->removeDefaultArgument();
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003686 }
3687 }
3688 }
Douglas Gregora735b202009-10-13 14:39:41 +00003689 } else if (TemplateParams) {
3690 if (TUK == TUK_Friend)
3691 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00003692 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00003693 SourceRange(TemplateParams->getTemplateLoc(),
3694 TemplateParams->getRAngleLoc()))
3695 << SourceRange(LAngleLoc, RAngleLoc);
3696 else
3697 isExplicitSpecialization = true;
3698 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003699 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00003700 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003701 isExplicitSpecialization = true;
3702 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003703
Douglas Gregorcc636682009-02-17 23:15:12 +00003704 // Check that the specialization uses the same tag kind as the
3705 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003706 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3707 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003708 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003709 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003710 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003711 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003712 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00003713 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003714 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003715 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003716 diag::note_previous_use);
3717 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3718 }
3719
Douglas Gregor40808ce2009-03-09 23:48:35 +00003720 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00003721 TemplateArgumentListInfo TemplateArgs;
3722 TemplateArgs.setLAngleLoc(LAngleLoc);
3723 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00003724 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003725
Douglas Gregorcc636682009-02-17 23:15:12 +00003726 // Check that the template argument list is well-formed for this
3727 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003728 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3729 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00003730 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3731 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003732 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003733
Mike Stump1eb44332009-09-09 15:08:12 +00003734 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003735 ClassTemplate->getTemplateParameters()->size()) &&
3736 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003737
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003738 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003739 // corresponds to these arguments.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003740 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003741 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003742 if (CheckClassTemplatePartialSpecializationArgs(
3743 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003744 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003745 return true;
3746
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003747 if (MirrorsPrimaryTemplate) {
3748 // C++ [temp.class.spec]p9b3:
3749 //
Mike Stump1eb44332009-09-09 15:08:12 +00003750 // -- The argument list of the specialization shall not be identical
3751 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003752 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003753 << (TUK == TUK_Definition)
Douglas Gregor849b2432010-03-31 17:46:05 +00003754 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003755 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003756 ClassTemplate->getIdentifier(),
3757 TemplateNameLoc,
3758 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003759 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003760 AS_none);
3761 }
3762
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003763 // FIXME: Diagnose friend partial specializations
3764
Douglas Gregorde090962010-02-09 00:37:32 +00003765 if (!Name.isDependent() &&
3766 !TemplateSpecializationType::anyDependentTemplateArguments(
3767 TemplateArgs.getArgumentArray(),
3768 TemplateArgs.size())) {
3769 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3770 << ClassTemplate->getDeclName();
3771 isPartialSpecialization = false;
Douglas Gregorde090962010-02-09 00:37:32 +00003772 }
3773 }
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00003774
Douglas Gregorcc636682009-02-17 23:15:12 +00003775 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003776 ClassTemplateSpecializationDecl *PrevDecl = 0;
3777
3778 if (isPartialSpecialization)
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00003779 // FIXME: Template parameter list matters, too
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003780 PrevDecl
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00003781 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
3782 Converted.flatSize(),
3783 InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003784 else
3785 PrevDecl
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00003786 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
3787 Converted.flatSize(), InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003788
3789 ClassTemplateSpecializationDecl *Specialization = 0;
3790
Douglas Gregor88b70942009-02-25 22:02:03 +00003791 // Check whether we can declare a class template specialization in
3792 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003793 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003794 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003795 TemplateNameLoc,
3796 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003797 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003798
Douglas Gregorb88e8882009-07-30 17:40:51 +00003799 // The canonical type
3800 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003801 if (PrevDecl &&
3802 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00003803 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003804 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003805 // arguments was referenced but not declared, or we're only
3806 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003807 // declaration node as our own, updating its source location to
3808 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003809 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003810 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003811 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003812 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003813 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003814 // Build the canonical type that describes the converted template
3815 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00003816 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3817 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb88e8882009-07-30 17:40:51 +00003818 Converted.getFlatArguments(),
3819 Converted.flatSize());
3820
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003821 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003822 ClassTemplatePartialSpecializationDecl *PrevPartial
3823 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00003824 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00003825 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump1eb44332009-09-09 15:08:12 +00003826 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00003827 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003828 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003829 TemplateNameLoc,
3830 TemplateParams,
3831 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003832 Converted,
John McCalld5532b62009-11-23 01:53:49 +00003833 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00003834 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00003835 PrevPartial,
3836 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00003837 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00003838 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00003839 Partial->setTemplateParameterListsInfo(Context,
3840 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00003841 (TemplateParameterList**) TemplateParameterLists.release());
3842 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003843
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00003844 if (!PrevPartial)
3845 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003846 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003847
Douglas Gregored9c0f92009-10-29 00:04:11 +00003848 // If we are providing an explicit specialization of a member class
3849 // template specialization, make a note of that.
3850 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3851 PrevPartial->setMemberSpecialization();
3852
Douglas Gregor031a5882009-06-13 00:26:55 +00003853 // Check that all of the template parameters of the class template
3854 // partial specialization are deducible from the template
3855 // arguments. If not, this class template partial specialization
3856 // will never be used.
3857 llvm::SmallVector<bool, 8> DeducibleParams;
3858 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003859 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003860 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003861 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003862 unsigned NumNonDeducible = 0;
3863 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3864 if (!DeducibleParams[I])
3865 ++NumNonDeducible;
3866
3867 if (NumNonDeducible) {
3868 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3869 << (NumNonDeducible > 1)
3870 << SourceRange(TemplateNameLoc, RAngleLoc);
3871 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3872 if (!DeducibleParams[I]) {
3873 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3874 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003875 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003876 diag::note_partial_spec_unused_parameter)
3877 << Param->getDeclName();
3878 else
Mike Stump1eb44332009-09-09 15:08:12 +00003879 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003880 diag::note_partial_spec_unused_parameter)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00003881 << "<anonymous>";
Douglas Gregor031a5882009-06-13 00:26:55 +00003882 }
3883 }
3884 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003885 } else {
3886 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003887 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003888 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00003889 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00003890 ClassTemplate->getDeclContext(),
3891 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003892 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003893 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003894 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00003895 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00003896 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00003897 Specialization->setTemplateParameterListsInfo(Context,
3898 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00003899 (TemplateParameterList**) TemplateParameterLists.release());
3900 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003901
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00003902 if (!PrevDecl)
3903 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregorb88e8882009-07-30 17:40:51 +00003904
3905 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003906 }
3907
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003908 // C++ [temp.expl.spec]p6:
3909 // If a template, a member template or the member of a class template is
3910 // explicitly specialized then that specialization shall be declared
3911 // before the first use of that specialization that would cause an implicit
3912 // instantiation to take place, in every translation unit in which such a
3913 // use occurs; no diagnostic is required.
3914 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003915 bool Okay = false;
3916 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3917 // Is there any previous explicit specialization declaration?
3918 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3919 Okay = true;
3920 break;
3921 }
3922 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003923
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003924 if (!Okay) {
3925 SourceRange Range(TemplateNameLoc, RAngleLoc);
3926 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3927 << Context.getTypeDeclType(Specialization) << Range;
3928
3929 Diag(PrevDecl->getPointOfInstantiation(),
3930 diag::note_instantiation_required_here)
3931 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003932 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003933 return true;
3934 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003935 }
3936
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003937 // If this is not a friend, note that this is an explicit specialization.
3938 if (TUK != TUK_Friend)
3939 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003940
3941 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003942 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00003943 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003944 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003945 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003946 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003947 Diag(Def->getLocation(), diag::note_previous_definition);
3948 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003949 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003950 }
3951 }
3952
Douglas Gregorfc705b82009-02-26 22:19:44 +00003953 // Build the fully-sugared type for this class template
3954 // specialization as the user wrote in the specialization
3955 // itself. This means that we'll pretty-print the type retrieved
3956 // from the specialization's declaration the way that the user
3957 // actually wrote the specialization, rather than formatting the
3958 // name based on the "canonical" representation used to store the
3959 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00003960 TypeSourceInfo *WrittenTy
3961 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3962 TemplateArgs, CanonType);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00003963 if (TUK != TUK_Friend) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003964 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor7e9b57b2010-07-06 18:33:12 +00003965 if (TemplateParams)
3966 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnarac98971d2010-06-12 07:44:57 +00003967 }
Douglas Gregor40808ce2009-03-09 23:48:35 +00003968 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00003969
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003970 // C++ [temp.expl.spec]p9:
3971 // A template explicit specialization is in the scope of the
3972 // namespace in which the template was defined.
3973 //
3974 // We actually implement this paragraph where we set the semantic
3975 // context (in the creation of the ClassTemplateSpecializationDecl),
3976 // but we also maintain the lexical context where the actual
3977 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00003978 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003979
Douglas Gregorcc636682009-02-17 23:15:12 +00003980 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003981 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00003982 Specialization->startDefinition();
3983
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003984 if (TUK == TUK_Friend) {
3985 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3986 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00003987 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003988 /*FIXME:*/KWLoc);
3989 Friend->setAccess(AS_public);
3990 CurContext->addDecl(Friend);
3991 } else {
3992 // Add the specialization into its lexical context, so that it can
3993 // be seen when iterating through the list of declarations in that
3994 // context. However, specializations are not found by name lookup.
3995 CurContext->addDecl(Specialization);
3996 }
John McCalld226f652010-08-21 09:40:31 +00003997 return Specialization;
Douglas Gregorcc636682009-02-17 23:15:12 +00003998}
Douglas Gregord57959a2009-03-27 23:10:48 +00003999
John McCalld226f652010-08-21 09:40:31 +00004000Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00004001 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004002 Declarator &D) {
Douglas Gregore542c862009-06-23 23:11:28 +00004003 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4004}
4005
John McCalld226f652010-08-21 09:40:31 +00004006Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00004007 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004008 Declarator &D) {
Douglas Gregor52591bf2009-06-24 00:54:41 +00004009 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4010 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4011 "Not a function declarator!");
4012 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00004013
Douglas Gregor52591bf2009-06-24 00:54:41 +00004014 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00004015 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00004016 }
Mike Stump1eb44332009-09-09 15:08:12 +00004017
Douglas Gregor52591bf2009-06-24 00:54:41 +00004018 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004019
John McCalld226f652010-08-21 09:40:31 +00004020 Decl *DP = HandleDeclarator(ParentScope, D,
4021 move(TemplateParameterLists),
4022 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004023 if (FunctionTemplateDecl *FunctionTemplate
John McCalld226f652010-08-21 09:40:31 +00004024 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump1eb44332009-09-09 15:08:12 +00004025 return ActOnStartOfFunctionDef(FnBodyScope,
John McCalld226f652010-08-21 09:40:31 +00004026 FunctionTemplate->getTemplatedDecl());
4027 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4028 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4029 return 0;
Douglas Gregor52591bf2009-06-24 00:54:41 +00004030}
4031
John McCall75042392010-02-11 01:33:53 +00004032/// \brief Strips various properties off an implicit instantiation
4033/// that has just been explicitly specialized.
4034static void StripImplicitInstantiation(NamedDecl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00004035 D->dropAttrs();
John McCall75042392010-02-11 01:33:53 +00004036
4037 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4038 FD->setInlineSpecified(false);
4039 }
4040}
4041
Douglas Gregor454885e2009-10-15 15:54:05 +00004042/// \brief Diagnose cases where we have an explicit template specialization
4043/// before/after an explicit template instantiation, producing diagnostics
4044/// for those cases where they are required and determining whether the
4045/// new specialization/instantiation will have any effect.
4046///
Douglas Gregor454885e2009-10-15 15:54:05 +00004047/// \param NewLoc the location of the new explicit specialization or
4048/// instantiation.
4049///
4050/// \param NewTSK the kind of the new explicit specialization or instantiation.
4051///
4052/// \param PrevDecl the previous declaration of the entity.
4053///
4054/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4055///
4056/// \param PrevPointOfInstantiation if valid, indicates where the previus
4057/// declaration was instantiated (either implicitly or explicitly).
4058///
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004059/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregor454885e2009-10-15 15:54:05 +00004060/// specialization or instantiation has no effect and should be ignored.
4061///
4062/// \returns true if there was an error that should prevent the introduction of
4063/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00004064bool
4065Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4066 TemplateSpecializationKind NewTSK,
4067 NamedDecl *PrevDecl,
4068 TemplateSpecializationKind PrevTSK,
4069 SourceLocation PrevPointOfInstantiation,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004070 bool &HasNoEffect) {
4071 HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00004072
4073 switch (NewTSK) {
4074 case TSK_Undeclared:
4075 case TSK_ImplicitInstantiation:
4076 assert(false && "Don't check implicit instantiations here");
4077 return false;
4078
4079 case TSK_ExplicitSpecialization:
4080 switch (PrevTSK) {
4081 case TSK_Undeclared:
4082 case TSK_ExplicitSpecialization:
4083 // Okay, we're just specializing something that is either already
4084 // explicitly specialized or has merely been mentioned without any
4085 // instantiation.
4086 return false;
4087
4088 case TSK_ImplicitInstantiation:
4089 if (PrevPointOfInstantiation.isInvalid()) {
4090 // The declaration itself has not actually been instantiated, so it is
4091 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00004092 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00004093 return false;
4094 }
4095 // Fall through
4096
4097 case TSK_ExplicitInstantiationDeclaration:
4098 case TSK_ExplicitInstantiationDefinition:
4099 assert((PrevTSK == TSK_ImplicitInstantiation ||
4100 PrevPointOfInstantiation.isValid()) &&
4101 "Explicit instantiation without point of instantiation?");
4102
4103 // C++ [temp.expl.spec]p6:
4104 // If a template, a member template or the member of a class template
4105 // is explicitly specialized then that specialization shall be declared
4106 // before the first use of that specialization that would cause an
4107 // implicit instantiation to take place, in every translation unit in
4108 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004109 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4110 // Is there any previous explicit specialization declaration?
4111 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4112 return false;
4113 }
4114
Douglas Gregor0d035142009-10-27 18:42:08 +00004115 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00004116 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004117 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00004118 << (PrevTSK != TSK_ImplicitInstantiation);
4119
4120 return true;
4121 }
4122 break;
4123
4124 case TSK_ExplicitInstantiationDeclaration:
4125 switch (PrevTSK) {
4126 case TSK_ExplicitInstantiationDeclaration:
4127 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004128 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004129 return false;
4130
4131 case TSK_Undeclared:
4132 case TSK_ImplicitInstantiation:
4133 // We're explicitly instantiating something that may have already been
4134 // implicitly instantiated; that's fine.
4135 return false;
4136
4137 case TSK_ExplicitSpecialization:
4138 // C++0x [temp.explicit]p4:
4139 // For a given set of template parameters, if an explicit instantiation
4140 // of a template appears after a declaration of an explicit
4141 // specialization for that template, the explicit instantiation has no
4142 // effect.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004143 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004144 return false;
4145
4146 case TSK_ExplicitInstantiationDefinition:
4147 // C++0x [temp.explicit]p10:
4148 // If an entity is the subject of both an explicit instantiation
4149 // declaration and an explicit instantiation definition in the same
4150 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00004151 Diag(NewLoc,
4152 diag::err_explicit_instantiation_declaration_after_definition);
4153 Diag(PrevPointOfInstantiation,
4154 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00004155 assert(PrevPointOfInstantiation.isValid() &&
4156 "Explicit instantiation without point of instantiation?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004157 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004158 return false;
4159 }
4160 break;
4161
4162 case TSK_ExplicitInstantiationDefinition:
4163 switch (PrevTSK) {
4164 case TSK_Undeclared:
4165 case TSK_ImplicitInstantiation:
4166 // We're explicitly instantiating something that may have already been
4167 // implicitly instantiated; that's fine.
4168 return false;
4169
4170 case TSK_ExplicitSpecialization:
4171 // C++ DR 259, C++0x [temp.explicit]p4:
4172 // For a given set of template parameters, if an explicit
4173 // instantiation of a template appears after a declaration of
4174 // an explicit specialization for that template, the explicit
4175 // instantiation has no effect.
4176 //
4177 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00004178 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00004179 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00004180 if (!getLangOptions().CPlusPlus0x) {
4181 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00004182 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004183 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00004184 diag::note_previous_template_specialization);
4185 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004186 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004187 return false;
4188
4189 case TSK_ExplicitInstantiationDeclaration:
4190 // We're explicity instantiating a definition for something for which we
4191 // were previously asked to suppress instantiations. That's fine.
4192 return false;
4193
4194 case TSK_ExplicitInstantiationDefinition:
4195 // C++0x [temp.spec]p5:
4196 // For a given template and a given set of template-arguments,
4197 // - an explicit instantiation definition shall appear at most once
4198 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00004199 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00004200 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004201 Diag(PrevPointOfInstantiation,
4202 diag::note_previous_explicit_instantiation);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004203 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004204 return false;
4205 }
4206 break;
4207 }
4208
4209 assert(false && "Missing specialization/instantiation case?");
4210
4211 return false;
4212}
4213
John McCallaf2094e2010-04-08 09:05:18 +00004214/// \brief Perform semantic analysis for the given dependent function
4215/// template specialization. The only possible way to get a dependent
4216/// function template specialization is with a friend declaration,
4217/// like so:
4218///
4219/// template <class T> void foo(T);
4220/// template <class T> class A {
4221/// friend void foo<>(T);
4222/// };
4223///
4224/// There really isn't any useful analysis we can do here, so we
4225/// just store the information.
4226bool
4227Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4228 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4229 LookupResult &Previous) {
4230 // Remove anything from Previous that isn't a function template in
4231 // the correct context.
4232 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4233 LookupResult::Filter F = Previous.makeFilter();
4234 while (F.hasNext()) {
4235 NamedDecl *D = F.next()->getUnderlyingDecl();
4236 if (!isa<FunctionTemplateDecl>(D) ||
4237 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4238 F.erase();
4239 }
4240 F.done();
4241
4242 // Should this be diagnosed here?
4243 if (Previous.empty()) return true;
4244
4245 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4246 ExplicitTemplateArgs);
4247 return false;
4248}
4249
Abramo Bagnarae03db982010-05-20 15:32:11 +00004250/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004251/// specialization.
4252///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004253/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004254/// explicit function template specialization. On successful completion,
4255/// the function declaration \p FD will become a function template
4256/// specialization.
4257///
4258/// \param FD the function declaration, which will be updated to become a
4259/// function template specialization.
4260///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004261/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4262/// if any. Note that this may be valid info even when 0 arguments are
4263/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4264/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004265///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004266/// \param PrevDecl the set of declarations that may be specialized by
4267/// this function specialization.
4268bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004269Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004270 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004271 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004272 // The set of function template specializations that could match this
4273 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004274 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004275
4276 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall68263142009-11-18 22:49:29 +00004277 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4278 I != E; ++I) {
4279 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4280 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004281 // Only consider templates found within the same semantic lookup scope as
4282 // FD.
4283 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4284 continue;
4285
4286 // C++ [temp.expl.spec]p11:
4287 // A trailing template-argument can be left unspecified in the
4288 // template-id naming an explicit function template specialization
4289 // provided it can be deduced from the function argument type.
4290 // Perform template argument deduction to determine whether we may be
4291 // specializing this template.
4292 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004293 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004294 FunctionDecl *Specialization = 0;
4295 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004296 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004297 FD->getType(),
4298 Specialization,
4299 Info)) {
4300 // FIXME: Template argument deduction failed; record why it failed, so
4301 // that we can provide nifty diagnostics.
4302 (void)TDK;
4303 continue;
4304 }
4305
4306 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004307 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004308 }
4309 }
4310
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004311 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004312 UnresolvedSetIterator Result
4313 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4314 TPOC_Other, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004315 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004316 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004317 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004318 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004319 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004320 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004321 return true;
John McCallc373d482010-01-27 01:50:18 +00004322
4323 // Ignore access information; it doesn't figure into redeclaration checking.
4324 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorc42b6522010-04-09 21:02:29 +00004325 Specialization->setLocation(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004326
4327 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004328 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004329
4330 // If this is a friend declaration, then we're not really declaring
4331 // an explicit specialization.
4332 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004333
Douglas Gregord5cb8762009-10-07 00:13:32 +00004334 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004335 if (!isFriend &&
4336 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004337 Specialization->getPrimaryTemplate(),
4338 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004339 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004340 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004341
4342 // C++ [temp.expl.spec]p6:
4343 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004344 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004345 // before the first use of that specialization that would cause an implicit
4346 // instantiation to take place, in every translation unit in which such a
4347 // use occurs; no diagnostic is required.
4348 FunctionTemplateSpecializationInfo *SpecInfo
4349 = Specialization->getTemplateSpecializationInfo();
4350 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004351
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004352 bool HasNoEffect = false;
John McCall7ad650f2010-03-24 07:46:06 +00004353 if (!isFriend &&
4354 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004355 TSK_ExplicitSpecialization,
4356 Specialization,
4357 SpecInfo->getTemplateSpecializationKind(),
4358 SpecInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004359 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004360 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004361
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004362 // Mark the prior declaration as an explicit specialization, so that later
4363 // clients know that this is an explicit specialization.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004364 if (!isFriend) {
John McCall7ad650f2010-03-24 07:46:06 +00004365 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004366 MarkUnusedFileScopedDecl(Specialization);
4367 }
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004368
4369 // Turn the given function declaration into a function template
4370 // specialization, with the template arguments from the previous
4371 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00004372 // Take copies of (semantic and syntactic) template argument lists.
4373 const TemplateArgumentList* TemplArgs = new (Context)
4374 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4375 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4376 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregor838db382010-02-11 01:19:42 +00004377 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00004378 TemplArgs, /*InsertPos=*/0,
4379 SpecInfo->getTemplateSpecializationKind(),
4380 TemplArgsAsWritten);
4381
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004382 // The "previous declaration" for this function template specialization is
4383 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004384 Previous.clear();
4385 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004386 return false;
4387}
4388
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004389/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004390/// specialization.
4391///
4392/// This routine performs all of the semantic analysis required for an
4393/// explicit member function specialization. On successful completion,
4394/// the function declaration \p FD will become a member function
4395/// specialization.
4396///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004397/// \param Member the member declaration, which will be updated to become a
4398/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004399///
John McCall68263142009-11-18 22:49:29 +00004400/// \param Previous the set of declarations, one of which may be specialized
4401/// by this function specialization; the set will be modified to contain the
4402/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004403bool
John McCall68263142009-11-18 22:49:29 +00004404Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004405 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00004406
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004407 // Try to find the member we are instantiating.
4408 NamedDecl *Instantiation = 0;
4409 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004410 MemberSpecializationInfo *MSInfo = 0;
4411
John McCall68263142009-11-18 22:49:29 +00004412 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004413 // Nowhere to look anyway.
4414 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004415 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4416 I != E; ++I) {
4417 NamedDecl *D = (*I)->getUnderlyingDecl();
4418 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004419 if (Context.hasSameType(Function->getType(), Method->getType())) {
4420 Instantiation = Method;
4421 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004422 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004423 break;
4424 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004425 }
4426 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004427 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004428 VarDecl *PrevVar;
4429 if (Previous.isSingleResult() &&
4430 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004431 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004432 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004433 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004434 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004435 }
4436 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004437 CXXRecordDecl *PrevRecord;
4438 if (Previous.isSingleResult() &&
4439 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4440 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004441 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004442 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004443 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004444 }
4445
4446 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004447 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004448 // specializations are always out-of-line, the caller will complain about
4449 // this mismatch later.
4450 return false;
4451 }
John McCall77e8b112010-04-13 20:37:33 +00004452
4453 // If this is a friend, just bail out here before we start turning
4454 // things into explicit specializations.
4455 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4456 // Preserve instantiation information.
4457 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4458 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4459 cast<CXXMethodDecl>(InstantiatedFrom),
4460 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4461 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4462 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4463 cast<CXXRecordDecl>(InstantiatedFrom),
4464 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4465 }
4466
4467 Previous.clear();
4468 Previous.addDecl(Instantiation);
4469 return false;
4470 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004471
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004472 // Make sure that this is a specialization of a member.
4473 if (!InstantiatedFrom) {
4474 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4475 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004476 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4477 return true;
4478 }
4479
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004480 // C++ [temp.expl.spec]p6:
4481 // If a template, a member template or the member of a class template is
4482 // explicitly specialized then that spe- cialization shall be declared
4483 // before the first use of that specialization that would cause an implicit
4484 // instantiation to take place, in every translation unit in which such a
4485 // use occurs; no diagnostic is required.
4486 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004487
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004488 bool HasNoEffect = false;
John McCall75042392010-02-11 01:33:53 +00004489 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4490 TSK_ExplicitSpecialization,
4491 Instantiation,
4492 MSInfo->getTemplateSpecializationKind(),
4493 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004494 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004495 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004496
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004497 // Check the scope of this explicit specialization.
4498 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004499 InstantiatedFrom,
4500 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004501 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004502 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004503
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004504 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004505 // the original declaration to note that it is an explicit specialization
4506 // (if it was previously an implicit instantiation). This latter step
4507 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004508 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004509 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4510 if (InstantiationFunction->getTemplateSpecializationKind() ==
4511 TSK_ImplicitInstantiation) {
4512 InstantiationFunction->setTemplateSpecializationKind(
4513 TSK_ExplicitSpecialization);
4514 InstantiationFunction->setLocation(Member->getLocation());
4515 }
4516
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004517 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4518 cast<CXXMethodDecl>(InstantiatedFrom),
4519 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004520 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004521 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004522 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4523 if (InstantiationVar->getTemplateSpecializationKind() ==
4524 TSK_ImplicitInstantiation) {
4525 InstantiationVar->setTemplateSpecializationKind(
4526 TSK_ExplicitSpecialization);
4527 InstantiationVar->setLocation(Member->getLocation());
4528 }
4529
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004530 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4531 cast<VarDecl>(InstantiatedFrom),
4532 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004533 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004534 } else {
4535 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004536 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4537 if (InstantiationClass->getTemplateSpecializationKind() ==
4538 TSK_ImplicitInstantiation) {
4539 InstantiationClass->setTemplateSpecializationKind(
4540 TSK_ExplicitSpecialization);
4541 InstantiationClass->setLocation(Member->getLocation());
4542 }
4543
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004544 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004545 cast<CXXRecordDecl>(InstantiatedFrom),
4546 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004547 }
4548
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004549 // Save the caller the trouble of having to figure out which declaration
4550 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004551 Previous.clear();
4552 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004553 return false;
4554}
4555
Douglas Gregor558c0322009-10-14 23:41:34 +00004556/// \brief Check the scope of an explicit instantiation.
Douglas Gregor669eed82010-07-13 00:10:04 +00004557///
4558/// \returns true if a serious error occurs, false otherwise.
4559static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregor558c0322009-10-14 23:41:34 +00004560 SourceLocation InstLoc,
4561 bool WasQualifiedName) {
4562 DeclContext *ExpectedContext
4563 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4564 DeclContext *CurContext = S.CurContext->getLookupContext();
4565
Douglas Gregor669eed82010-07-13 00:10:04 +00004566 if (CurContext->isRecord()) {
4567 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4568 << D;
4569 return true;
4570 }
4571
Douglas Gregor558c0322009-10-14 23:41:34 +00004572 // C++0x [temp.explicit]p2:
4573 // An explicit instantiation shall appear in an enclosing namespace of its
4574 // template.
4575 //
4576 // This is DR275, which we do not retroactively apply to C++98/03.
4577 if (S.getLangOptions().CPlusPlus0x &&
4578 !CurContext->Encloses(ExpectedContext)) {
4579 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregor2166beb2010-05-11 17:39:34 +00004580 S.Diag(InstLoc,
4581 S.getLangOptions().CPlusPlus0x?
4582 diag::err_explicit_instantiation_out_of_scope
4583 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004584 << D << NS;
4585 else
Douglas Gregor2166beb2010-05-11 17:39:34 +00004586 S.Diag(InstLoc,
4587 S.getLangOptions().CPlusPlus0x?
4588 diag::err_explicit_instantiation_must_be_global
4589 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004590 << D;
4591 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00004592 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00004593 }
4594
4595 // C++0x [temp.explicit]p2:
4596 // If the name declared in the explicit instantiation is an unqualified
4597 // name, the explicit instantiation shall appear in the namespace where
4598 // its template is declared or, if that namespace is inline (7.3.1), any
4599 // namespace from its enclosing namespace set.
4600 if (WasQualifiedName)
Douglas Gregor669eed82010-07-13 00:10:04 +00004601 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00004602
4603 if (CurContext->Equals(ExpectedContext))
Douglas Gregor669eed82010-07-13 00:10:04 +00004604 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00004605
Douglas Gregor2166beb2010-05-11 17:39:34 +00004606 S.Diag(InstLoc,
4607 S.getLangOptions().CPlusPlus0x?
4608 diag::err_explicit_instantiation_unqualified_wrong_namespace
4609 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004610 << D << ExpectedContext;
4611 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00004612 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00004613}
4614
4615/// \brief Determine whether the given scope specifier has a template-id in it.
4616static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4617 if (!SS.isSet())
4618 return false;
4619
4620 // C++0x [temp.explicit]p2:
4621 // If the explicit instantiation is for a member function, a member class
4622 // or a static data member of a class template specialization, the name of
4623 // the class template specialization in the qualified-id for the member
4624 // name shall be a simple-template-id.
4625 //
4626 // C++98 has the same restriction, just worded differently.
4627 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4628 NNS; NNS = NNS->getPrefix())
4629 if (Type *T = NNS->getAsType())
4630 if (isa<TemplateSpecializationType>(T))
4631 return true;
4632
4633 return false;
4634}
4635
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004636// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004637Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004638Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004639 SourceLocation ExternLoc,
4640 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004641 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004642 SourceLocation KWLoc,
4643 const CXXScopeSpec &SS,
4644 TemplateTy TemplateD,
4645 SourceLocation TemplateNameLoc,
4646 SourceLocation LAngleLoc,
4647 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004648 SourceLocation RAngleLoc,
4649 AttributeList *Attr) {
4650 // Find the class template we're specializing
4651 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004652 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004653 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4654
4655 // Check that the specialization uses the same tag kind as the
4656 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004657 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4658 assert(Kind != TTK_Enum &&
4659 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004660 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004661 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004662 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004663 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004664 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004665 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004666 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004667 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004668 diag::note_previous_use);
4669 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4670 }
4671
Douglas Gregor558c0322009-10-14 23:41:34 +00004672 // C++0x [temp.explicit]p2:
4673 // There are two forms of explicit instantiation: an explicit instantiation
4674 // definition and an explicit instantiation declaration. An explicit
4675 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00004676 TemplateSpecializationKind TSK
4677 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4678 : TSK_ExplicitInstantiationDeclaration;
4679
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004680 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004681 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004682 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004683
4684 // Check that the template argument list is well-formed for this
4685 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00004686 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4687 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00004688 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4689 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004690 return true;
4691
Mike Stump1eb44332009-09-09 15:08:12 +00004692 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004693 ClassTemplate->getTemplateParameters()->size()) &&
4694 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004695
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004696 // Find the class template specialization declaration that
4697 // corresponds to these arguments.
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004698 void *InsertPos = 0;
4699 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004700 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4701 Converted.flatSize(), InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004702
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004703 TemplateSpecializationKind PrevDecl_TSK
4704 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4705
Douglas Gregord5cb8762009-10-07 00:13:32 +00004706 // C++0x [temp.explicit]p2:
4707 // [...] An explicit instantiation shall appear in an enclosing
4708 // namespace of its template. [...]
4709 //
4710 // This is C++ DR 275.
Douglas Gregor669eed82010-07-13 00:10:04 +00004711 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4712 SS.isSet()))
4713 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004714
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004715 ClassTemplateSpecializationDecl *Specialization = 0;
4716
Douglas Gregord78f5982009-11-25 06:01:46 +00004717 bool ReusedDecl = false;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004718 bool HasNoEffect = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004719 if (PrevDecl) {
Douglas Gregor0d035142009-10-27 18:42:08 +00004720 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004721 PrevDecl, PrevDecl_TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004722 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004723 HasNoEffect))
John McCalld226f652010-08-21 09:40:31 +00004724 return PrevDecl;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004725
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004726 // Even though HasNoEffect == true means that this explicit instantiation
4727 // has no effect on semantics, we go on to put its syntax in the AST.
4728
4729 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4730 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor52604ab2009-09-11 21:19:12 +00004731 // Since the only prior class template specialization with these
4732 // arguments was referenced but not declared, reuse that
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004733 // declaration node as our own, updating the source location
4734 // for the template name to reflect our new declaration.
4735 // (Other source locations will be updated later.)
Douglas Gregor52604ab2009-09-11 21:19:12 +00004736 Specialization = PrevDecl;
4737 Specialization->setLocation(TemplateNameLoc);
4738 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00004739 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00004740 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004741 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004742
Douglas Gregor52604ab2009-09-11 21:19:12 +00004743 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004744 // Create a new class template specialization declaration node for
4745 // this explicit specialization.
4746 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00004747 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004748 ClassTemplate->getDeclContext(),
4749 TemplateNameLoc,
4750 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00004751 Converted, PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004752 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004753
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004754 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004755 // Insert the new specialization.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004756 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004757 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004758 }
4759
4760 // Build the fully-sugared type for this explicit instantiation as
4761 // the user wrote in the explicit instantiation itself. This means
4762 // that we'll pretty-print the type retrieved from the
4763 // specialization's declaration the way that the user actually wrote
4764 // the explicit instantiation, rather than formatting the name based
4765 // on the "canonical" representation used to store the template
4766 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004767 TypeSourceInfo *WrittenTy
4768 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4769 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004770 Context.getTypeDeclType(Specialization));
4771 Specialization->setTypeAsWritten(WrittenTy);
4772 TemplateArgsIn.release();
4773
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004774 // Set source locations for keywords.
4775 Specialization->setExternLoc(ExternLoc);
4776 Specialization->setTemplateKeywordLoc(TemplateLoc);
4777
4778 // Add the explicit instantiation into its lexical context. However,
4779 // since explicit instantiations are never found by name lookup, we
4780 // just put it into the declaration context directly.
4781 Specialization->setLexicalDeclContext(CurContext);
4782 CurContext->addDecl(Specialization);
4783
4784 // Syntax is now OK, so return if it has no other effect on semantics.
4785 if (HasNoEffect) {
4786 // Set the template specialization kind.
4787 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00004788 return Specialization;
Douglas Gregord78f5982009-11-25 06:01:46 +00004789 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004790
4791 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004792 // A definition of a class template or class member template
4793 // shall be in scope at the point of the explicit instantiation of
4794 // the class template or class member template.
4795 //
4796 // This check comes when we actually try to perform the
4797 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004798 ClassTemplateSpecializationDecl *Def
4799 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004800 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004801 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004802 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004803 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004804 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004805 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
4806 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004807
Douglas Gregor0d035142009-10-27 18:42:08 +00004808 // Instantiate the members of this class template specialization.
4809 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004810 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004811 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00004812 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4813
4814 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4815 // TSK_ExplicitInstantiationDefinition
4816 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4817 TSK == TSK_ExplicitInstantiationDefinition)
4818 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004819
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004820 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004821 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004822
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004823 // Set the template specialization kind.
4824 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00004825 return Specialization;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004826}
4827
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004828// Explicit instantiation of a member class of a class template.
John McCalld226f652010-08-21 09:40:31 +00004829DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004830Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004831 SourceLocation ExternLoc,
4832 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004833 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004834 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004835 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004836 IdentifierInfo *Name,
4837 SourceLocation NameLoc,
4838 AttributeList *Attr) {
4839
Douglas Gregor402abb52009-05-28 23:31:59 +00004840 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004841 bool IsDependent = false;
John McCalld226f652010-08-21 09:40:31 +00004842 Decl *TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
4843 KWLoc, SS, Name, NameLoc, Attr, AS_none,
4844 MultiTemplateParamsArg(*this, 0, 0),
4845 Owned, IsDependent);
John McCallc4e70192009-09-11 04:59:25 +00004846 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4847
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004848 if (!TagD)
4849 return true;
4850
John McCalld226f652010-08-21 09:40:31 +00004851 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004852 if (Tag->isEnum()) {
4853 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4854 << Context.getTypeDeclType(Tag);
4855 return true;
4856 }
4857
Douglas Gregord0c87372009-05-27 17:30:49 +00004858 if (Tag->isInvalidDecl())
4859 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004860
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004861 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4862 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4863 if (!Pattern) {
4864 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4865 << Context.getTypeDeclType(Record);
4866 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4867 return true;
4868 }
4869
Douglas Gregor558c0322009-10-14 23:41:34 +00004870 // C++0x [temp.explicit]p2:
4871 // If the explicit instantiation is for a class or member class, the
4872 // elaborated-type-specifier in the declaration shall include a
4873 // simple-template-id.
4874 //
4875 // C++98 has the same restriction, just worded differently.
4876 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregora2dd8282010-06-16 16:26:47 +00004877 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00004878 << Record << SS.getRange();
4879
4880 // C++0x [temp.explicit]p2:
4881 // There are two forms of explicit instantiation: an explicit instantiation
4882 // definition and an explicit instantiation declaration. An explicit
4883 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004884 TemplateSpecializationKind TSK
4885 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4886 : TSK_ExplicitInstantiationDeclaration;
4887
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004888 // C++0x [temp.explicit]p2:
4889 // [...] An explicit instantiation shall appear in an enclosing
4890 // namespace of its template. [...]
4891 //
4892 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004893 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004894
4895 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004896 CXXRecordDecl *PrevDecl
4897 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00004898 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00004899 PrevDecl = Record;
4900 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004901 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004902 bool HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00004903 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004904 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004905 PrevDecl,
4906 MSInfo->getTemplateSpecializationKind(),
4907 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004908 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00004909 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004910 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00004911 return TagD;
4912 }
4913
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004914 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00004915 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004916 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004917 // C++ [temp.explicit]p3:
4918 // A definition of a member class of a class template shall be in scope
4919 // at the point of an explicit instantiation of the member class.
4920 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00004921 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004922 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004923 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4924 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004925 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4926 << Pattern;
4927 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004928 } else {
4929 if (InstantiateClass(NameLoc, Record, Def,
4930 getTemplateInstantiationArgs(Record),
4931 TSK))
4932 return true;
4933
Douglas Gregor952b0172010-02-11 01:04:33 +00004934 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00004935 if (!RecordDef)
4936 return true;
4937 }
4938 }
4939
4940 // Instantiate all of the members of the class.
4941 InstantiateClassMembers(NameLoc, RecordDef,
4942 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004943
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004944 if (TSK == TSK_ExplicitInstantiationDefinition)
4945 MarkVTableUsed(NameLoc, RecordDef, true);
4946
Mike Stump390b4cc2009-05-16 07:39:55 +00004947 // FIXME: We don't have any representation for explicit instantiations of
4948 // member classes. Such a representation is not needed for compilation, but it
4949 // should be available for clients that want to see all of the declarations in
4950 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004951 return TagD;
4952}
4953
Douglas Gregord5a423b2009-09-25 18:43:00 +00004954Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4955 SourceLocation ExternLoc,
4956 SourceLocation TemplateLoc,
4957 Declarator &D) {
4958 // Explicit instantiations always require a name.
Abramo Bagnara25777432010-08-11 22:01:17 +00004959 // TODO: check if/when DNInfo should replace Name.
4960 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4961 DeclarationName Name = NameInfo.getName();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004962 if (!Name) {
4963 if (!D.isInvalidType())
4964 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4965 diag::err_explicit_instantiation_requires_name)
4966 << D.getDeclSpec().getSourceRange()
4967 << D.getSourceRange();
4968
4969 return true;
4970 }
4971
4972 // The scope passed in may not be a decl scope. Zip up the scope tree until
4973 // we find one that is.
4974 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4975 (S->getFlags() & Scope::TemplateParamScope) != 0)
4976 S = S->getParent();
4977
4978 // Determine the type of the declaration.
John McCallbf1a0282010-06-04 23:28:52 +00004979 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
4980 QualType R = T->getType();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004981 if (R.isNull())
4982 return true;
4983
4984 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4985 // Cannot explicitly instantiate a typedef.
4986 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4987 << Name;
4988 return true;
4989 }
4990
Douglas Gregor663b5a02009-10-14 20:14:33 +00004991 // C++0x [temp.explicit]p1:
4992 // [...] An explicit instantiation of a function template shall not use the
4993 // inline or constexpr specifiers.
4994 // Presumably, this also applies to member functions of class templates as
4995 // well.
4996 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4997 Diag(D.getDeclSpec().getInlineSpecLoc(),
4998 diag::err_explicit_instantiation_inline)
Douglas Gregor849b2432010-03-31 17:46:05 +00004999 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00005000
5001 // FIXME: check for constexpr specifier.
5002
Douglas Gregor558c0322009-10-14 23:41:34 +00005003 // C++0x [temp.explicit]p2:
5004 // There are two forms of explicit instantiation: an explicit instantiation
5005 // definition and an explicit instantiation declaration. An explicit
5006 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00005007 TemplateSpecializationKind TSK
5008 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5009 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00005010
Abramo Bagnara25777432010-08-11 22:01:17 +00005011 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005012 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005013
5014 if (!R->isFunctionType()) {
5015 // C++ [temp.explicit]p1:
5016 // A [...] static data member of a class template can be explicitly
5017 // instantiated from the member definition associated with its class
5018 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00005019 if (Previous.isAmbiguous())
5020 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005021
John McCall1bcee0a2009-12-02 08:25:40 +00005022 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005023 if (!Prev || !Prev->isStaticDataMember()) {
5024 // We expect to see a data data member here.
5025 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5026 << Name;
5027 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5028 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00005029 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005030 return true;
5031 }
5032
5033 if (!Prev->getInstantiatedFromStaticDataMember()) {
5034 // FIXME: Check for explicit specialization?
5035 Diag(D.getIdentifierLoc(),
5036 diag::err_explicit_instantiation_data_member_not_instantiated)
5037 << Prev;
5038 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5039 // FIXME: Can we provide a note showing where this was declared?
5040 return true;
5041 }
5042
Douglas Gregor558c0322009-10-14 23:41:34 +00005043 // C++0x [temp.explicit]p2:
5044 // If the explicit instantiation is for a member function, a member class
5045 // or a static data member of a class template specialization, the name of
5046 // the class template specialization in the qualified-id for the member
5047 // name shall be a simple-template-id.
5048 //
5049 // C++98 has the same restriction, just worded differently.
5050 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5051 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005052 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005053 << Prev << D.getCXXScopeSpec().getRange();
5054
5055 // Check the scope of this explicit instantiation.
5056 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5057
Douglas Gregor454885e2009-10-15 15:54:05 +00005058 // Verify that it is okay to explicitly instantiate here.
5059 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5060 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005061 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005062 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00005063 MSInfo->getTemplateSpecializationKind(),
5064 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005065 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005066 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005067 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005068 return (Decl*) 0;
Douglas Gregor454885e2009-10-15 15:54:05 +00005069
Douglas Gregord5a423b2009-09-25 18:43:00 +00005070 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005071 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005072 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005073 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005074
5075 // FIXME: Create an ExplicitInstantiation node?
John McCalld226f652010-08-21 09:40:31 +00005076 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005077 }
5078
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005079 // If the declarator is a template-id, translate the parser's template
5080 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00005081 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00005082 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005083 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5084 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00005085 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5086 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00005087 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5088 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00005089 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00005090 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00005091 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00005092 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00005093 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005094
Douglas Gregord5a423b2009-09-25 18:43:00 +00005095 // C++ [temp.explicit]p1:
5096 // A [...] function [...] can be explicitly instantiated from its template.
5097 // A member function [...] of a class template can be explicitly
5098 // instantiated from the member definition associated with its class
5099 // template.
John McCallc373d482010-01-27 01:50:18 +00005100 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005101 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5102 P != PEnd; ++P) {
5103 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00005104 if (!HasExplicitTemplateArgs) {
5105 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5106 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5107 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00005108
John McCallc373d482010-01-27 01:50:18 +00005109 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00005110 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5111 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00005112 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00005113 }
5114 }
5115
5116 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5117 if (!FunTmpl)
5118 continue;
5119
John McCall5769d612010-02-08 23:07:23 +00005120 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005121 FunctionDecl *Specialization = 0;
5122 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00005123 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00005124 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00005125 R, Specialization, Info)) {
5126 // FIXME: Keep track of almost-matches?
5127 (void)TDK;
5128 continue;
5129 }
5130
John McCallc373d482010-01-27 01:50:18 +00005131 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005132 }
5133
5134 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005135 UnresolvedSetIterator Result
5136 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregord5a423b2009-09-25 18:43:00 +00005137 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005138 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5139 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5140 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00005141
John McCallc373d482010-01-27 01:50:18 +00005142 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00005143 return true;
John McCallc373d482010-01-27 01:50:18 +00005144
5145 // Ignore access control bits, we don't need them for redeclaration checking.
5146 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005147
Douglas Gregor0a897e32009-10-15 17:21:20 +00005148 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005149 Diag(D.getIdentifierLoc(),
5150 diag::err_explicit_instantiation_member_function_not_instantiated)
5151 << Specialization
5152 << (Specialization->getTemplateSpecializationKind() ==
5153 TSK_ExplicitSpecialization);
5154 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5155 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005156 }
Douglas Gregor558c0322009-10-14 23:41:34 +00005157
Douglas Gregor0a897e32009-10-15 17:21:20 +00005158 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00005159 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5160 PrevDecl = Specialization;
5161
Douglas Gregor0a897e32009-10-15 17:21:20 +00005162 if (PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005163 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005164 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00005165 PrevDecl,
5166 PrevDecl->getTemplateSpecializationKind(),
5167 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005168 HasNoEffect))
Douglas Gregor0a897e32009-10-15 17:21:20 +00005169 return true;
5170
5171 // FIXME: We may still want to build some representation of this
5172 // explicit specialization.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005173 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005174 return (Decl*) 0;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005175 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00005176
5177 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00005178
5179 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005180 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor0a897e32009-10-15 17:21:20 +00005181
Douglas Gregor558c0322009-10-14 23:41:34 +00005182 // C++0x [temp.explicit]p2:
5183 // If the explicit instantiation is for a member function, a member class
5184 // or a static data member of a class template specialization, the name of
5185 // the class template specialization in the qualified-id for the member
5186 // name shall be a simple-template-id.
5187 //
5188 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005189 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005190 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00005191 D.getCXXScopeSpec().isSet() &&
5192 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5193 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005194 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005195 << Specialization << D.getCXXScopeSpec().getRange();
5196
5197 CheckExplicitInstantiationScope(*this,
5198 FunTmpl? (NamedDecl *)FunTmpl
5199 : Specialization->getInstantiatedFromMemberFunction(),
5200 D.getIdentifierLoc(),
5201 D.getCXXScopeSpec().isSet());
5202
Douglas Gregord5a423b2009-09-25 18:43:00 +00005203 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCalld226f652010-08-21 09:40:31 +00005204 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005205}
5206
Douglas Gregord57959a2009-03-27 23:10:48 +00005207Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00005208Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5209 const CXXScopeSpec &SS, IdentifierInfo *Name,
5210 SourceLocation TagLoc, SourceLocation NameLoc) {
5211 // This has to hold, because SS is expected to be defined.
5212 assert(Name && "Expected a name in a dependent tag");
5213
5214 NestedNameSpecifier *NNS
5215 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5216 if (!NNS)
5217 return true;
5218
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005219 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005220
Douglas Gregor48c89f42010-04-24 16:38:41 +00005221 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5222 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005223 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00005224 return true;
5225 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005226
5227 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallb3d87482010-08-24 05:47:05 +00005228 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCallc4e70192009-09-11 04:59:25 +00005229}
5230
5231Sema::TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005232Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5233 const CXXScopeSpec &SS, const IdentifierInfo &II,
5234 SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005235 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00005236 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5237 if (!NNS)
5238 return true;
5239
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005240 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5241 !getLangOptions().CPlusPlus0x)
5242 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5243 << FixItHint::CreateRemoval(TypenameLoc);
5244
Douglas Gregor107de902010-04-24 15:35:55 +00005245 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005246 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00005247 if (T.isNull())
5248 return true;
John McCall63b43852010-04-29 23:50:39 +00005249
5250 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5251 if (isa<DependentNameType>(T)) {
5252 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005253 TL.setKeywordLoc(TypenameLoc);
5254 TL.setQualifierRange(SS.getRange());
5255 TL.setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005256 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005257 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005258 TL.setKeywordLoc(TypenameLoc);
5259 TL.setQualifierRange(SS.getRange());
5260 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005261 }
5262
John McCallb3d87482010-08-24 05:47:05 +00005263 return CreateParsedType(T, TSI);
Douglas Gregord57959a2009-03-27 23:10:48 +00005264}
5265
Douglas Gregor17343172009-04-01 00:28:59 +00005266Sema::TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005267Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5268 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallb3d87482010-08-24 05:47:05 +00005269 ParsedType Ty) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005270 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5271 !getLangOptions().CPlusPlus0x)
5272 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5273 << FixItHint::CreateRemoval(TypenameLoc);
5274
John McCall4e449832010-05-28 23:32:21 +00005275 TypeSourceInfo *InnerTSI = 0;
5276 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCall4e449832010-05-28 23:32:21 +00005277
5278 assert(isa<TemplateSpecializationType>(T) &&
5279 "Expected a template specialization type");
Douglas Gregor17343172009-04-01 00:28:59 +00005280
Douglas Gregor6946baf2009-09-02 13:05:45 +00005281 if (computeDeclContext(SS, false)) {
5282 // If we can compute a declaration context, then the "typename"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005283 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor6946baf2009-09-02 13:05:45 +00005284 // track of the nested-name-specifier.
John McCall4e449832010-05-28 23:32:21 +00005285
5286 // Push the inner type, preserving its source locations if possible.
5287 TypeLocBuilder Builder;
5288 if (InnerTSI)
5289 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5290 else
5291 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5292
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005293 /* Note: NNS already embedded in template specialization type T. */
5294 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCall4e449832010-05-28 23:32:21 +00005295 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5296 TL.setKeywordLoc(TypenameLoc);
5297 TL.setQualifierRange(SS.getRange());
5298
5299 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallb3d87482010-08-24 05:47:05 +00005300 return CreateParsedType(T, TSI);
Douglas Gregor6946baf2009-09-02 13:05:45 +00005301 }
Mike Stump1eb44332009-09-09 15:08:12 +00005302
John McCall33500952010-06-11 00:33:02 +00005303 // TODO: it's really silly that we make a template specialization
5304 // type earlier only to drop it again here.
5305 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5306 DependentTemplateName *DTN =
5307 TST->getTemplateName().getAsDependentTemplateName();
5308 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005309 assert(DTN->getQualifier()
5310 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5311 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5312 DTN->getQualifier(),
John McCall33500952010-06-11 00:33:02 +00005313 DTN->getIdentifier(),
5314 TST->getNumArgs(),
5315 TST->getArgs());
John McCall63b43852010-04-29 23:50:39 +00005316 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCall33500952010-06-11 00:33:02 +00005317 DependentTemplateSpecializationTypeLoc TL =
5318 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5319 if (InnerTSI) {
5320 TemplateSpecializationTypeLoc TSTL =
5321 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5322 TL.setLAngleLoc(TSTL.getLAngleLoc());
5323 TL.setRAngleLoc(TSTL.getRAngleLoc());
5324 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5325 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5326 } else {
5327 TL.initializeLocal(SourceLocation());
5328 }
John McCall4e449832010-05-28 23:32:21 +00005329 TL.setKeywordLoc(TypenameLoc);
5330 TL.setQualifierRange(SS.getRange());
John McCallb3d87482010-08-24 05:47:05 +00005331 return CreateParsedType(T, TSI);
Douglas Gregor17343172009-04-01 00:28:59 +00005332}
5333
Douglas Gregord57959a2009-03-27 23:10:48 +00005334/// \brief Build the type that describes a C++ typename specifier,
5335/// e.g., "typename T::type".
5336QualType
Douglas Gregor107de902010-04-24 15:35:55 +00005337Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5338 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005339 SourceLocation KeywordLoc, SourceRange NNSRange,
5340 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00005341 CXXScopeSpec SS;
5342 SS.setScopeRep(NNS);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005343 SS.setRange(NNSRange);
Douglas Gregord57959a2009-03-27 23:10:48 +00005344
John McCall77bb1aa2010-05-01 00:40:08 +00005345 DeclContext *Ctx = computeDeclContext(SS);
5346 if (!Ctx) {
5347 // If the nested-name-specifier is dependent and couldn't be
5348 // resolved to a type, build a typename type.
5349 assert(NNS->isDependent());
5350 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00005351 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005352
John McCall77bb1aa2010-05-01 00:40:08 +00005353 // If the nested-name-specifier refers to the current instantiation,
5354 // the "typename" keyword itself is superfluous. In C++03, the
5355 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5356 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregor732281d2010-06-14 22:07:54 +00005357 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00005358
John McCall77bb1aa2010-05-01 00:40:08 +00005359 if (RequireCompleteDeclContext(SS, Ctx))
5360 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00005361
5362 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005363 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005364 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005365 unsigned DiagID = 0;
5366 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005367 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005368 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005369 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005370 break;
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005371
5372 case LookupResult::NotFoundInCurrentInstantiation:
5373 // Okay, it's a member of an unknown instantiation.
Douglas Gregor107de902010-04-24 15:35:55 +00005374 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00005375
5376 case LookupResult::Found:
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005377 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005378 // We found a type. Build an ElaboratedType, since the
5379 // typename-specifier was just sugar.
5380 return Context.getElaboratedType(ETK_Typename, NNS,
5381 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00005382 }
5383
5384 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00005385 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00005386 break;
5387
John McCall7ba107a2009-11-18 02:36:19 +00005388 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005389 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00005390 return QualType();
5391
Douglas Gregord57959a2009-03-27 23:10:48 +00005392 case LookupResult::FoundOverloaded:
5393 DiagID = diag::err_typename_nested_not_type;
5394 Referenced = *Result.begin();
5395 break;
5396
John McCall6e247262009-10-10 05:48:19 +00005397 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00005398 return QualType();
5399 }
5400
5401 // If we get here, it's because name lookup did not find a
5402 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005403 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5404 IILoc);
5405 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00005406 if (Referenced)
5407 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5408 << Name;
5409 return QualType();
5410}
Douglas Gregor4a959d82009-08-06 16:20:37 +00005411
5412namespace {
5413 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00005414 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00005415 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00005416 SourceLocation Loc;
5417 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00005418
Douglas Gregor4a959d82009-08-06 16:20:37 +00005419 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00005420 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5421
Mike Stump1eb44332009-09-09 15:08:12 +00005422 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005423 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005424 DeclarationName Entity)
5425 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00005426 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00005427
5428 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00005429 /// transformed.
5430 ///
5431 /// For the purposes of type reconstruction, a type has already been
5432 /// transformed if it is NULL or if it is not dependent.
5433 bool AlreadyTransformed(QualType T) {
5434 return T.isNull() || !T->isDependentType();
5435 }
Mike Stump1eb44332009-09-09 15:08:12 +00005436
5437 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00005438 /// rebuilt.
5439 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00005440
Douglas Gregor4a959d82009-08-06 16:20:37 +00005441 /// \brief Returns the name of the entity whose type is being rebuilt.
5442 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00005443
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005444 /// \brief Sets the "base" location and entity when that
5445 /// information is known based on another transformation.
5446 void setBase(SourceLocation Loc, DeclarationName Entity) {
5447 this->Loc = Loc;
5448 this->Entity = Entity;
5449 }
Douglas Gregor4a959d82009-08-06 16:20:37 +00005450 };
5451}
5452
Douglas Gregor4a959d82009-08-06 16:20:37 +00005453/// \brief Rebuilds a type within the context of the current instantiation.
5454///
Mike Stump1eb44332009-09-09 15:08:12 +00005455/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00005456/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00005457/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00005458/// partial specialization thereof). This routine will rebuild that type now
5459/// that we have entered the declarator's scope, which may produce different
5460/// canonical types, e.g.,
5461///
5462/// \code
5463/// template<typename T>
5464/// struct X {
5465/// typedef T* pointer;
5466/// pointer data();
5467/// };
5468///
5469/// template<typename T>
5470/// typename X<T>::pointer X<T>::data() { ... }
5471/// \endcode
5472///
Douglas Gregor4714c122010-03-31 17:34:00 +00005473/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005474/// since we do not know that we can look into X<T> when we parsed the type.
5475/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005476/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00005477/// as the canonical type of T*, allowing the return types of the out-of-line
5478/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00005479TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5480 SourceLocation Loc,
5481 DeclarationName Name) {
5482 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00005483 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00005484
Douglas Gregor4a959d82009-08-06 16:20:37 +00005485 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5486 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00005487}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005488
John McCall60d7b3a2010-08-24 06:29:42 +00005489ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallb3d87482010-08-24 05:47:05 +00005490 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5491 DeclarationName());
5492 return Rebuilder.TransformExpr(E);
5493}
5494
John McCall63b43852010-04-29 23:50:39 +00005495bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5496 if (SS.isInvalid()) return true;
John McCall31f17ec2010-04-27 00:57:59 +00005497
5498 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5499 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5500 DeclarationName());
5501 NestedNameSpecifier *Rebuilt =
5502 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall63b43852010-04-29 23:50:39 +00005503 if (!Rebuilt) return true;
5504
5505 SS.setScopeRep(Rebuilt);
5506 return false;
John McCall31f17ec2010-04-27 00:57:59 +00005507}
5508
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005509/// \brief Produces a formatted string that describes the binding of
5510/// template parameters to template arguments.
5511std::string
5512Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5513 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005514 // FIXME: For variadic templates, we'll need to get the structured list.
5515 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5516 Args.flat_size());
5517}
5518
5519std::string
5520Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5521 const TemplateArgument *Args,
5522 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005523 std::string Result;
5524
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005525 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005526 return Result;
5527
5528 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005529 if (I >= NumArgs)
5530 break;
5531
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005532 if (I == 0)
5533 Result += "[with ";
5534 else
5535 Result += ", ";
5536
5537 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5538 Result += Id->getName();
5539 } else {
5540 Result += '$';
5541 Result += llvm::utostr(I);
5542 }
5543
5544 Result += " = ";
5545
5546 switch (Args[I].getKind()) {
5547 case TemplateArgument::Null:
5548 Result += "<no value>";
5549 break;
5550
5551 case TemplateArgument::Type: {
5552 std::string TypeStr;
5553 Args[I].getAsType().getAsStringInternal(TypeStr,
5554 Context.PrintingPolicy);
5555 Result += TypeStr;
5556 break;
5557 }
5558
5559 case TemplateArgument::Declaration: {
5560 bool Unnamed = true;
5561 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5562 if (ND->getDeclName()) {
5563 Unnamed = false;
5564 Result += ND->getNameAsString();
5565 }
5566 }
5567
5568 if (Unnamed) {
5569 Result += "<anonymous>";
5570 }
5571 break;
5572 }
5573
Douglas Gregor788cd062009-11-11 01:00:40 +00005574 case TemplateArgument::Template: {
5575 std::string Str;
5576 llvm::raw_string_ostream OS(Str);
5577 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5578 Result += OS.str();
5579 break;
5580 }
5581
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005582 case TemplateArgument::Integral: {
5583 Result += Args[I].getAsIntegral()->toString(10);
5584 break;
5585 }
5586
5587 case TemplateArgument::Expression: {
Douglas Gregor77e2c672010-04-29 04:55:13 +00005588 // FIXME: This is non-optimal, since we're regurgitating the
5589 // expression we were given.
5590 std::string Str;
5591 {
5592 llvm::raw_string_ostream OS(Str);
5593 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5594 Context.PrintingPolicy);
5595 }
5596 Result += Str;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005597 break;
5598 }
5599
5600 case TemplateArgument::Pack:
5601 // FIXME: Format template argument packs
5602 Result += "<template argument pack>";
5603 break;
5604 }
5605 }
5606
5607 Result += ']';
5608 return Result;
5609}