blob: 4a5f038284e2352b3b33a21b92f2419a5fb7ca4c [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000018#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000020#include "clang/Parse/DeclSpec.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000021#include "clang/Parse/Template.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregorb7bfe792009-09-02 22:59:36 +000027/// \brief Determine whether the declaration found is acceptable as the name
28/// of a template and, if so, return that template declaration. Otherwise,
29/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000030static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
31 NamedDecl *Orig) {
32 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000033
Douglas Gregorb7bfe792009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
John McCalle9cccd82010-06-16 08:42:20 +000035 return Orig;
Mike Stump11289f42009-09-09 15:08:12 +000036
Douglas Gregorb7bfe792009-09-02 22:59:36 +000037 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
38 // C++ [temp.local]p1:
39 // Like normal (non-template) classes, class templates have an
40 // injected-class-name (Clause 9). The injected-class-name
41 // can be used with or without a template-argument-list. When
42 // it is used without a template-argument-list, it is
43 // equivalent to the injected-class-name followed by the
44 // template-parameters of the class template enclosed in
45 // <>. When it is used with a template-argument-list, it
46 // refers to the specified class template specialization,
47 // which could be the current specialization or another
48 // specialization.
49 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000051 if (Record->getDescribedClassTemplate())
52 return Record->getDescribedClassTemplate();
53
54 if (ClassTemplateSpecializationDecl *Spec
55 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
56 return Spec->getSpecializedTemplate();
57 }
Mike Stump11289f42009-09-09 15:08:12 +000058
Douglas Gregorb7bfe792009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump11289f42009-09-09 15:08:12 +000061
Douglas Gregorb7bfe792009-09-02 22:59:36 +000062 return 0;
63}
64
John McCalle66edc12009-11-24 19:00:30 +000065static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor41f90302010-04-12 20:54:26 +000066 // The set of class templates we've already seen.
67 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000068 LookupResult::Filter filter = R.makeFilter();
69 while (filter.hasNext()) {
70 NamedDecl *Orig = filter.next();
John McCalle9cccd82010-06-16 08:42:20 +000071 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
John McCalle66edc12009-11-24 19:00:30 +000072 if (!Repl)
73 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +000074 else if (Repl != Orig) {
75
76 // C++ [temp.local]p3:
77 // A lookup that finds an injected-class-name (10.2) can result in an
78 // ambiguity in certain cases (for example, if it is found in more than
79 // one base class). If all of the injected-class-names that are found
80 // refer to specializations of the same class template, and if the name
81 // is followed by a template-argument-list, the reference refers to the
82 // class template itself and not a specialization thereof, and is not
83 // ambiguous.
84 //
85 // FIXME: Will we eventually have to do the same for alias templates?
86 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
87 if (!ClassTemplates.insert(ClassTmpl)) {
88 filter.erase();
89 continue;
90 }
91
John McCalle66edc12009-11-24 19:00:30 +000092 filter.replace(Repl);
Douglas Gregor41f90302010-04-12 20:54:26 +000093 }
John McCalle66edc12009-11-24 19:00:30 +000094 }
95 filter.done();
96}
97
Douglas Gregorb7bfe792009-09-02 22:59:36 +000098TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +000099 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000100 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000101 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000102 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000103 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000104 TemplateTy &TemplateResult,
105 bool &MemberOfUnknownSpecialization) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000106 assert(getLangOptions().CPlusPlus && "No template names in C!");
107
Douglas Gregor3cf81312009-11-03 23:16:33 +0000108 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000109 MemberOfUnknownSpecialization = false;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000110
111 switch (Name.getKind()) {
112 case UnqualifiedId::IK_Identifier:
113 TName = DeclarationName(Name.Identifier);
114 break;
115
116 case UnqualifiedId::IK_OperatorFunctionId:
117 TName = Context.DeclarationNames.getCXXOperatorName(
118 Name.OperatorFunctionId.Operator);
119 break;
120
Alexis Hunted0530f2009-11-28 08:58:14 +0000121 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000122 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
123 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000124
Douglas Gregor3cf81312009-11-03 23:16:33 +0000125 default:
126 return TNK_Non_template;
127 }
Mike Stump11289f42009-09-09 15:08:12 +0000128
John McCalle66edc12009-11-24 19:00:30 +0000129 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump11289f42009-09-09 15:08:12 +0000130
Douglas Gregorff18cc12009-12-31 08:11:17 +0000131 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
132 LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +0000133 R.suppressDiagnostics();
Douglas Gregor786123d2010-05-21 23:18:07 +0000134 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
135 MemberOfUnknownSpecialization);
Douglas Gregor41f90302010-04-12 20:54:26 +0000136 if (R.empty() || R.isAmbiguous())
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000137 return TNK_Non_template;
138
John McCalld28ae272009-12-02 08:04:21 +0000139 TemplateName Template;
140 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000141
John McCalld28ae272009-12-02 08:04:21 +0000142 unsigned ResultCount = R.end() - R.begin();
143 if (ResultCount > 1) {
144 // We assume that we'll preserve the qualifier from a function
145 // template name in other ways.
146 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
147 TemplateKind = TNK_Function_template;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000148 } else {
John McCalld28ae272009-12-02 08:04:21 +0000149 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
150
151 if (SS.isSet() && !SS.isInvalid()) {
152 NestedNameSpecifier *Qualifier
153 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000154 Template = Context.getQualifiedTemplateName(Qualifier,
155 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000156 } else {
157 Template = TemplateName(TD);
158 }
159
160 if (isa<FunctionTemplateDecl>(TD))
161 TemplateKind = TNK_Function_template;
162 else {
163 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
164 TemplateKind = TNK_Type_template;
165 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000166 }
Mike Stump11289f42009-09-09 15:08:12 +0000167
John McCalld28ae272009-12-02 08:04:21 +0000168 TemplateResult = TemplateTy::make(Template);
169 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000170}
171
Douglas Gregor18473f32010-01-12 21:28:44 +0000172bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
173 SourceLocation IILoc,
174 Scope *S,
175 const CXXScopeSpec *SS,
176 TemplateTy &SuggestedTemplate,
177 TemplateNameKind &SuggestedKind) {
178 // We can't recover unless there's a dependent scope specifier preceding the
179 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000180 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000181 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
182 computeDeclContext(*SS))
183 return false;
184
185 // The code is missing a 'template' keyword prior to the dependent template
186 // name.
187 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
188 Diag(IILoc, diag::err_template_kw_missing)
189 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000190 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor18473f32010-01-12 21:28:44 +0000191 SuggestedTemplate
192 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
193 SuggestedKind = TNK_Dependent_template_name;
194 return true;
195}
196
John McCalle66edc12009-11-24 19:00:30 +0000197void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000198 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000199 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000200 bool EnteringContext,
201 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000202 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000203 MemberOfUnknownSpecialization = false;
John McCalle66edc12009-11-24 19:00:30 +0000204 DeclContext *LookupCtx = 0;
205 bool isDependent = false;
206 if (!ObjectType.isNull()) {
207 // This nested-name-specifier occurs in a member access expression, e.g.,
208 // x->B::f, and we are looking into the type of the object.
209 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
210 LookupCtx = computeDeclContext(ObjectType);
211 isDependent = ObjectType->isDependentType();
212 assert((isDependent || !ObjectType->isIncompleteType()) &&
213 "Caller should have completed object type");
214 } else if (SS.isSet()) {
215 // This nested-name-specifier occurs after another nested-name-specifier,
216 // so long into the context associated with the prior nested-name-specifier.
217 LookupCtx = computeDeclContext(SS, EnteringContext);
218 isDependent = isDependentScopeSpecifier(SS);
219
220 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000221 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000222 return;
223 }
224
225 bool ObjectTypeSearchedInScope = false;
226 if (LookupCtx) {
227 // Perform "qualified" name lookup into the declaration context we
228 // computed, which is either the type of the base of a member access
229 // expression or the declaration context associated with a prior
230 // nested-name-specifier.
231 LookupQualifiedName(Found, LookupCtx);
232
233 if (!ObjectType.isNull() && Found.empty()) {
234 // C++ [basic.lookup.classref]p1:
235 // In a class member access expression (5.2.5), if the . or -> token is
236 // immediately followed by an identifier followed by a <, the
237 // identifier must be looked up to determine whether the < is the
238 // beginning of a template argument list (14.2) or a less-than operator.
239 // The identifier is first looked up in the class of the object
240 // expression. If the identifier is not found, it is then looked up in
241 // the context of the entire postfix-expression and shall name a class
242 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000243 if (S) LookupName(Found, S);
244 ObjectTypeSearchedInScope = true;
245 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000246 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000247 // We cannot look into a dependent object type or nested nme
248 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000249 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000250 return;
251 } else {
252 // Perform unqualified name lookup in the current scope.
253 LookupName(Found, S);
254 }
255
Douglas Gregorc119dd52010-01-12 17:06:20 +0000256 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000257 // If we did not find any names, attempt to correct any typos.
258 DeclarationName Name = Found.getLookupName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000259 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregorc048c522010-06-29 19:27:42 +0000260 false, CTC_CXXCasts)) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000261 FilterAcceptableTemplateNames(Context, Found);
John McCalle9cccd82010-06-16 08:42:20 +0000262 if (!Found.empty()) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000263 if (LookupCtx)
264 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
265 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000266 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000267 Found.getLookupName().getAsString());
268 else
269 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
270 << Name << Found.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +0000271 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000272 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000273 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
274 Diag(Template->getLocation(), diag::note_previous_decl)
275 << Template->getDeclName();
John McCalle9cccd82010-06-16 08:42:20 +0000276 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000277 } else {
278 Found.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +0000279 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000280 }
281 }
282
John McCalle66edc12009-11-24 19:00:30 +0000283 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000284 if (Found.empty()) {
285 if (isDependent)
286 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000287 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000288 }
John McCalle66edc12009-11-24 19:00:30 +0000289
290 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
291 // C++ [basic.lookup.classref]p1:
292 // [...] If the lookup in the class of the object expression finds a
293 // template, the name is also looked up in the context of the entire
294 // postfix-expression and [...]
295 //
296 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
297 LookupOrdinaryName);
298 LookupName(FoundOuter, S);
299 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor41f90302010-04-12 20:54:26 +0000300
John McCalle66edc12009-11-24 19:00:30 +0000301 if (FoundOuter.empty()) {
302 // - if the name is not found, the name found in the class of the
303 // object expression is used, otherwise
304 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
305 // - if the name is found in the context of the entire
306 // postfix-expression and does not name a class template, the name
307 // found in the class of the object expression is used, otherwise
John McCalle9cccd82010-06-16 08:42:20 +0000308 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000309 // - if the name found is a class template, it must refer to the same
310 // entity as the one found in the class of the object expression,
311 // otherwise the program is ill-formed.
312 if (!Found.isSingleResult() ||
313 Found.getFoundDecl()->getCanonicalDecl()
314 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
315 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000316 diag::ext_nested_name_member_ref_lookup_ambiguous)
317 << Found.getLookupName()
318 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000319 Diag(Found.getRepresentativeDecl()->getLocation(),
320 diag::note_ambig_member_ref_object_type)
321 << ObjectType;
322 Diag(FoundOuter.getFoundDecl()->getLocation(),
323 diag::note_ambig_member_ref_scope);
324
325 // Recover by taking the template that we found in the object
326 // expression's type.
327 }
328 }
329 }
330}
331
John McCallcd4b4772009-12-02 03:53:29 +0000332/// ActOnDependentIdExpression - Handle a dependent id-expression that
333/// was just parsed. This is only possible with an explicit scope
334/// specifier naming a dependent type.
John McCalle66edc12009-11-24 19:00:30 +0000335Sema::OwningExprResult
336Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000337 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000338 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000339 const TemplateArgumentListInfo *TemplateArgs) {
340 NestedNameSpecifier *Qualifier
341 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall87fe5d52010-05-20 01:18:31 +0000342
343 DeclContext *DC = getFunctionLevelDeclContext();
John McCalle66edc12009-11-24 19:00:30 +0000344
John McCallcd4b4772009-12-02 03:53:29 +0000345 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000346 isa<CXXMethodDecl>(DC) &&
347 cast<CXXMethodDecl>(DC)->isInstance()) {
348 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCallcd4b4772009-12-02 03:53:29 +0000349
John McCalle66edc12009-11-24 19:00:30 +0000350 // Since the 'this' expression is synthesized, we don't need to
351 // perform the double-lookup check.
352 NamedDecl *FirstQualifierInScope = 0;
353
John McCall2d74de92009-12-01 22:10:20 +0000354 return Owned(CXXDependentScopeMemberExpr::Create(Context,
355 /*This*/ 0, ThisType,
356 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000357 /*Op*/ SourceLocation(),
358 Qualifier, SS.getRange(),
359 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000360 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000361 TemplateArgs));
362 }
363
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000364 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000365}
366
367Sema::OwningExprResult
368Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000369 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000370 const TemplateArgumentListInfo *TemplateArgs) {
371 return Owned(DependentScopeDeclRefExpr::Create(Context,
372 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
373 SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000374 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000375 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000376}
377
Douglas Gregor5101c242008-12-05 18:15:24 +0000378/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
379/// that the template parameter 'PrevDecl' is being shadowed by a new
380/// declaration at location Loc. Returns true to indicate that this is
381/// an error, and false otherwise.
382bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000383 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000384
385 // Microsoft Visual C++ permits template parameters to be shadowed.
386 if (getLangOptions().Microsoft)
387 return false;
388
389 // C++ [temp.local]p4:
390 // A template-parameter shall not be redeclared within its
391 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000392 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000393 << cast<NamedDecl>(PrevDecl)->getDeclName();
394 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
395 return true;
396}
397
Douglas Gregor463421d2009-03-03 04:44:36 +0000398/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000399/// the parameter D to reference the templated declaration and return a pointer
400/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000401TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000402 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000403 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000404 return Temp;
405 }
406 return 0;
407}
408
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000409static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
410 const ParsedTemplateArgument &Arg) {
411
412 switch (Arg.getKind()) {
413 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000414 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000415 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
416 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000417 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000418 return TemplateArgumentLoc(TemplateArgument(T), DI);
419 }
420
421 case ParsedTemplateArgument::NonType: {
422 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
423 return TemplateArgumentLoc(TemplateArgument(E), E);
424 }
425
426 case ParsedTemplateArgument::Template: {
427 TemplateName Template
428 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
429 return TemplateArgumentLoc(TemplateArgument(Template),
430 Arg.getScopeSpec().getRange(),
431 Arg.getLocation());
432 }
433 }
434
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000435 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000436 return TemplateArgumentLoc();
437}
438
439/// \brief Translates template arguments as provided by the parser
440/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000441void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
442 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000443 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000444 TemplateArgs.addArgument(translateTemplateArgument(*this,
445 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000446}
447
Douglas Gregor5101c242008-12-05 18:15:24 +0000448/// ActOnTypeParameter - Called when a C++ template type parameter
449/// (e.g., "typename T") has been parsed. Typename specifies whether
450/// the keyword "typename" was used to declare the type parameter
451/// (otherwise, "class" was used), and KeyLoc is the location of the
452/// "class" or "typename" keyword. ParamName is the name of the
453/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregor2ebcae12010-06-16 15:23:05 +0000454/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000455/// If the type parameter has a default argument, it will be added
456/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000457Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000458 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000459 SourceLocation KeyLoc,
460 IdentifierInfo *ParamName,
461 SourceLocation ParamNameLoc,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000462 unsigned Depth, unsigned Position,
463 SourceLocation EqualLoc,
464 TypeTy *DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000465 assert(S->isTemplateParamScope() &&
466 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000467 bool Invalid = false;
468
469 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000470 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000471 LookupOrdinaryName,
472 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000473 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000474 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000475 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000476 }
477
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000478 SourceLocation Loc = ParamNameLoc;
479 if (!ParamName)
480 Loc = KeyLoc;
481
Douglas Gregor5101c242008-12-05 18:15:24 +0000482 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000483 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
484 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000485 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000486 if (Invalid)
487 Param->setInvalidDecl();
488
489 if (ParamName) {
490 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000491 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000492 IdResolver.AddDecl(Param);
493 }
494
Douglas Gregordc13ded2010-07-01 00:00:45 +0000495 // Handle the default argument, if provided.
496 if (DefaultArg) {
497 TypeSourceInfo *DefaultTInfo;
498 GetTypeFromParser(DefaultArg, &DefaultTInfo);
499
500 assert(DefaultTInfo && "expected source information for type");
501
502 // C++0x [temp.param]p9:
503 // A default template-argument may be specified for any kind of
504 // template-parameter that is not a template parameter pack.
505 if (Ellipsis) {
506 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
507 return DeclPtrTy::make(Param);
508 }
509
510 // Check the template argument itself.
511 if (CheckTemplateArgument(Param, DefaultTInfo)) {
512 Param->setInvalidDecl();
513 return DeclPtrTy::make(Param);;
514 }
515
516 Param->setDefaultArgument(DefaultTInfo, false);
517 }
518
Chris Lattner83f095c2009-03-28 19:18:32 +0000519 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000520}
521
Douglas Gregor463421d2009-03-03 04:44:36 +0000522/// \brief Check that the type of a non-type template parameter is
523/// well-formed.
524///
525/// \returns the (possibly-promoted) parameter type if valid;
526/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000527QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000528Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000529 // We don't allow variably-modified types as the type of non-type template
530 // parameters.
531 if (T->isVariablyModifiedType()) {
532 Diag(Loc, diag::err_variably_modified_nontype_template_param)
533 << T;
534 return QualType();
535 }
536
Douglas Gregor463421d2009-03-03 04:44:36 +0000537 // C++ [temp.param]p4:
538 //
539 // A non-type template-parameter shall have one of the following
540 // (optionally cv-qualified) types:
541 //
542 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000543 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000544 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000545 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000546 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000547 T->isReferenceType() ||
548 // -- pointer to member.
549 T->isMemberPointerType() ||
550 // If T is a dependent type, we can't do the check now, so we
551 // assume that it is well-formed.
552 T->isDependentType())
553 return T;
554 // C++ [temp.param]p8:
555 //
556 // A non-type template-parameter of type "array of T" or
557 // "function returning T" is adjusted to be of type "pointer to
558 // T" or "pointer to function returning T", respectively.
559 else if (T->isArrayType())
560 // FIXME: Keep the type prior to promotion?
561 return Context.getArrayDecayedType(T);
562 else if (T->isFunctionType())
563 // FIXME: Keep the type prior to promotion?
564 return Context.getPointerType(T);
Douglas Gregor959d5a02010-05-22 16:17:30 +0000565
Douglas Gregor463421d2009-03-03 04:44:36 +0000566 Diag(Loc, diag::err_template_nontype_parm_bad_type)
567 << T;
568
569 return QualType();
570}
571
Chris Lattner83f095c2009-03-28 19:18:32 +0000572Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000573 unsigned Depth,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000574 unsigned Position,
575 SourceLocation EqualLoc,
576 ExprArg DefaultArg) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000577 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
578 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000579
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000580 assert(S->isTemplateParamScope() &&
581 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000582 bool Invalid = false;
583
584 IdentifierInfo *ParamName = D.getIdentifier();
585 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000586 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000587 LookupOrdinaryName,
588 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000589 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000590 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000591 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000592 }
593
Douglas Gregor463421d2009-03-03 04:44:36 +0000594 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000595 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000596 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000597 Invalid = true;
598 }
Douglas Gregor81338792009-02-10 17:43:50 +0000599
Douglas Gregor5101c242008-12-05 18:15:24 +0000600 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000601 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
602 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000603 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000604 if (Invalid)
605 Param->setInvalidDecl();
606
607 if (D.getIdentifier()) {
608 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000609 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000610 IdResolver.AddDecl(Param);
611 }
Douglas Gregordc13ded2010-07-01 00:00:45 +0000612
613 // Check the well-formedness of the default template argument, if provided.
614 if (Expr *Default = static_cast<Expr *>(DefaultArg.get())) {
615 TemplateArgument Converted;
616 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
617 Param->setInvalidDecl();
618 return DeclPtrTy::make(Param);;
619 }
620
621 Param->setDefaultArgument(DefaultArg.takeAs<Expr>(), false);
622 }
623
Chris Lattner83f095c2009-03-28 19:18:32 +0000624 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000625}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000626
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000627/// ActOnTemplateTemplateParameter - Called when a C++ template template
628/// parameter (e.g. T in template <template <typename> class T> class array)
629/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000630Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
631 SourceLocation TmpLoc,
632 TemplateParamsTy *Params,
633 IdentifierInfo *Name,
634 SourceLocation NameLoc,
635 unsigned Depth,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000636 unsigned Position,
637 SourceLocation EqualLoc,
638 const ParsedTemplateArgument &Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000639 assert(S->isTemplateParamScope() &&
640 "Template template parameter not in template parameter scope!");
641
642 // Construct the parameter object.
643 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000644 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
645 TmpLoc, Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000646 (TemplateParameterList*)Params);
647
Douglas Gregordc13ded2010-07-01 00:00:45 +0000648 // If the template template parameter has a name, then link the identifier
649 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000650 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000651 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000652 IdResolver.AddDecl(Param);
653 }
654
Douglas Gregordc13ded2010-07-01 00:00:45 +0000655 if (!Default.isInvalid()) {
656 // Check only that we have a template template argument. We don't want to
657 // try to check well-formedness now, because our template template parameter
658 // might have dependent types in its template parameters, which we wouldn't
659 // be able to match now.
660 //
661 // If none of the template template parameter's template arguments mention
662 // other template parameters, we could actually perform more checking here.
663 // However, it isn't worth doing.
664 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
665 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
666 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
667 << DefaultArg.getSourceRange();
668 return DeclPtrTy::make(Param);
669 }
670
671 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000672 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000673
Douglas Gregordc13ded2010-07-01 00:00:45 +0000674 return DeclPtrTy::make(Param);
Douglas Gregordba32632009-02-10 19:49:53 +0000675}
676
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000677/// ActOnTemplateParameterList - Builds a TemplateParameterList that
678/// contains the template parameters in Params/NumParams.
679Sema::TemplateParamsTy *
680Sema::ActOnTemplateParameterList(unsigned Depth,
681 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000682 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000683 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000684 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000685 SourceLocation RAngleLoc) {
686 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000687 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000688
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000689 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000690 (NamedDecl**)Params, NumParams,
691 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000692}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000693
John McCall3e11ebe2010-03-15 10:12:16 +0000694static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
695 if (SS.isSet())
696 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
697 SS.getRange());
698}
699
Douglas Gregorc08f4892009-03-25 00:13:59 +0000700Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000701Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000702 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000703 IdentifierInfo *Name, SourceLocation NameLoc,
704 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000705 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000706 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000707 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000708 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000709 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000710 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000711
712 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000713 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000714 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000715
Abramo Bagnara6150c882010-05-11 21:36:43 +0000716 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
717 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000718
719 // There is no such thing as an unnamed class template.
720 if (!Name) {
721 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000722 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000723 }
724
725 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000726 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000727 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000728 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000729 if (SS.isNotEmpty() && !SS.isInvalid()) {
730 SemanticContext = computeDeclContext(SS, true);
731 if (!SemanticContext) {
732 // FIXME: Produce a reasonable diagnostic here
733 return true;
734 }
Mike Stump11289f42009-09-09 15:08:12 +0000735
John McCall0b66eb32010-05-01 00:40:08 +0000736 if (RequireCompleteDeclContext(SS, SemanticContext))
737 return true;
738
John McCall27b18f82009-11-17 02:14:36 +0000739 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000740 } else {
741 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000742 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000743 }
Mike Stump11289f42009-09-09 15:08:12 +0000744
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000745 if (Previous.isAmbiguous())
746 return true;
747
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000748 NamedDecl *PrevDecl = 0;
749 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000750 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000751
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000752 // If there is a previous declaration with the same name, check
753 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000754 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000755 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000756
757 // We may have found the injected-class-name of a class template,
758 // class template partial specialization, or class template specialization.
759 // In these cases, grab the template that is being defined or specialized.
760 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
761 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
762 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
763 PrevClassTemplate
764 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
765 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
766 PrevClassTemplate
767 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
768 ->getSpecializedTemplate();
769 }
770 }
771
John McCalld43784f2009-12-18 11:25:59 +0000772 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000773 // C++ [namespace.memdef]p3:
774 // [...] When looking for a prior declaration of a class or a function
775 // declared as a friend, and when the name of the friend class or
776 // function is neither a qualified name nor a template-id, scopes outside
777 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000778 if (!SS.isSet()) {
779 DeclContext *OutermostContext = CurContext;
780 while (!OutermostContext->isFileContext())
781 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000782
Douglas Gregorb74b1032010-04-18 17:37:40 +0000783 if (PrevDecl &&
784 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
785 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
786 SemanticContext = PrevDecl->getDeclContext();
787 } else {
788 // Declarations in outer scopes don't matter. However, the outermost
789 // context we computed is the semantic context for our new
790 // declaration.
791 PrevDecl = PrevClassTemplate = 0;
792 SemanticContext = OutermostContext;
793 }
John McCall90d3bb92009-12-17 23:21:11 +0000794 }
Douglas Gregorb74b1032010-04-18 17:37:40 +0000795
John McCall90d3bb92009-12-17 23:21:11 +0000796 if (CurContext->isDependentContext()) {
797 // If this is a dependent context, we don't want to link the friend
798 // class template to the template in scope, because that would perform
799 // checking of the template parameter lists that can't be performed
800 // until the outer context is instantiated.
801 PrevDecl = PrevClassTemplate = 0;
802 }
803 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
804 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000805
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000806 if (PrevClassTemplate) {
807 // Ensure that the template parameter lists are compatible.
808 if (!TemplateParameterListsAreEqual(TemplateParams,
809 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000810 /*Complain=*/true,
811 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000812 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000813
814 // C++ [temp.class]p4:
815 // In a redeclaration, partial specialization, explicit
816 // specialization or explicit instantiation of a class template,
817 // the class-key shall agree in kind with the original class
818 // template declaration (7.1.5.3).
819 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000820 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000821 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000822 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000823 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000824 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000825 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000826 }
827
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000828 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000829 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000830 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000831 Diag(NameLoc, diag::err_redefinition) << Name;
832 Diag(Def->getLocation(), diag::note_previous_definition);
833 // FIXME: Would it make sense to try to "forget" the previous
834 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000835 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000836 }
837 }
838 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
839 // Maybe we will complain about the shadowed template parameter.
840 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
841 // Just pretend that we didn't see the previous declaration.
842 PrevDecl = 0;
843 } else if (PrevDecl) {
844 // C++ [temp]p5:
845 // A class template shall not have the same name as any other
846 // template, class, function, object, enumeration, enumerator,
847 // namespace, or type in the same scope (3.3), except as specified
848 // in (14.5.4).
849 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
850 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000851 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000852 }
853
Douglas Gregordba32632009-02-10 19:49:53 +0000854 // Check the template parameter list of this declaration, possibly
855 // merging in the template parameter list from the previous class
856 // template declaration.
857 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000858 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
859 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000860 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000861
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000862 if (SS.isSet()) {
863 // If the name of the template was qualified, we must be defining the
864 // template out-of-line.
865 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
866 !(TUK == TUK_Friend && CurContext->isDependentContext()))
867 Diag(NameLoc, diag::err_member_def_does_not_match)
868 << Name << SemanticContext << SS.getRange();
869 }
870
Mike Stump11289f42009-09-09 15:08:12 +0000871 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000872 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000873 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000874 PrevClassTemplate->getTemplatedDecl() : 0,
875 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000876 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000877
878 ClassTemplateDecl *NewTemplate
879 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
880 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000881 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000882 NewClass->setDescribedClassTemplate(NewTemplate);
883
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000884 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000885 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +0000886 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000887 assert(T->isDependentType() && "Class template type is not dependent?");
888 (void)T;
889
Douglas Gregorcf915552009-10-13 16:30:37 +0000890 // If we are providing an explicit specialization of a member that is a
891 // class template, make a note of that.
892 if (PrevClassTemplate &&
893 PrevClassTemplate->getInstantiatedFromMemberTemplate())
894 PrevClassTemplate->setMemberSpecialization();
895
Anders Carlsson137108d2009-03-26 01:24:28 +0000896 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000897 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000898 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000899
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000900 // Set the lexical context of these templates
901 NewClass->setLexicalDeclContext(CurContext);
902 NewTemplate->setLexicalDeclContext(CurContext);
903
John McCall9bb74a52009-07-31 02:45:11 +0000904 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000905 NewClass->startDefinition();
906
907 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000908 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000909
John McCall27b5c252009-09-14 21:59:20 +0000910 if (TUK != TUK_Friend)
911 PushOnScopeChains(NewTemplate, S);
912 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000913 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000914 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000915 NewClass->setAccess(PrevClassTemplate->getAccess());
916 }
John McCall27b5c252009-09-14 21:59:20 +0000917
Douglas Gregor3dad8422009-09-26 06:47:28 +0000918 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
919 PrevClassTemplate != NULL);
920
John McCall27b5c252009-09-14 21:59:20 +0000921 // Friend templates are visible in fairly strange ways.
922 if (!CurContext->isDependentContext()) {
923 DeclContext *DC = SemanticContext->getLookupContext();
924 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
925 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
926 PushOnScopeChains(NewTemplate, EnclosingScope,
927 /* AddToContext = */ false);
928 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000929
930 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
931 NewClass->getLocation(),
932 NewTemplate,
933 /*FIXME:*/NewClass->getLocation());
934 Friend->setAccess(AS_public);
935 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000936 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000937
Douglas Gregordba32632009-02-10 19:49:53 +0000938 if (Invalid) {
939 NewTemplate->setInvalidDecl();
940 NewClass->setInvalidDecl();
941 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000942 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000943}
944
Douglas Gregored5731f2009-11-25 17:50:39 +0000945/// \brief Diagnose the presence of a default template argument on a
946/// template parameter, which is ill-formed in certain contexts.
947///
948/// \returns true if the default template argument should be dropped.
949static bool DiagnoseDefaultTemplateArgument(Sema &S,
950 Sema::TemplateParamListContext TPC,
951 SourceLocation ParamLoc,
952 SourceRange DefArgRange) {
953 switch (TPC) {
954 case Sema::TPC_ClassTemplate:
955 return false;
956
957 case Sema::TPC_FunctionTemplate:
958 // C++ [temp.param]p9:
959 // A default template-argument shall not be specified in a
960 // function template declaration or a function template
961 // definition [...]
962 // (This sentence is not in C++0x, per DR226).
963 if (!S.getLangOptions().CPlusPlus0x)
964 S.Diag(ParamLoc,
965 diag::err_template_parameter_default_in_function_template)
966 << DefArgRange;
967 return false;
968
969 case Sema::TPC_ClassTemplateMember:
970 // C++0x [temp.param]p9:
971 // A default template-argument shall not be specified in the
972 // template-parameter-lists of the definition of a member of a
973 // class template that appears outside of the member's class.
974 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
975 << DefArgRange;
976 return true;
977
978 case Sema::TPC_FriendFunctionTemplate:
979 // C++ [temp.param]p9:
980 // A default template-argument shall not be specified in a
981 // friend template declaration.
982 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
983 << DefArgRange;
984 return true;
985
986 // FIXME: C++0x [temp.param]p9 allows default template-arguments
987 // for friend function templates if there is only a single
988 // declaration (and it is a definition). Strange!
989 }
990
991 return false;
992}
993
Douglas Gregordba32632009-02-10 19:49:53 +0000994/// \brief Checks the validity of a template parameter list, possibly
995/// considering the template parameter list from a previous
996/// declaration.
997///
998/// If an "old" template parameter list is provided, it must be
999/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1000/// template parameter list.
1001///
1002/// \param NewParams Template parameter list for a new template
1003/// declaration. This template parameter list will be updated with any
1004/// default arguments that are carried through from the previous
1005/// template parameter list.
1006///
1007/// \param OldParams If provided, template parameter list from a
1008/// previous declaration of the same template. Default template
1009/// arguments will be merged from the old template parameter list to
1010/// the new template parameter list.
1011///
Douglas Gregored5731f2009-11-25 17:50:39 +00001012/// \param TPC Describes the context in which we are checking the given
1013/// template parameter list.
1014///
Douglas Gregordba32632009-02-10 19:49:53 +00001015/// \returns true if an error occurred, false otherwise.
1016bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001017 TemplateParameterList *OldParams,
1018 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001019 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001020
Douglas Gregordba32632009-02-10 19:49:53 +00001021 // C++ [temp.param]p10:
1022 // The set of default template-arguments available for use with a
1023 // template declaration or definition is obtained by merging the
1024 // default arguments from the definition (if in scope) and all
1025 // declarations in scope in the same way default function
1026 // arguments are (8.3.6).
1027 bool SawDefaultArgument = false;
1028 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001029
Anders Carlsson327865d2009-06-12 23:20:15 +00001030 bool SawParameterPack = false;
1031 SourceLocation ParameterPackLoc;
1032
Mike Stumpc89c8e32009-02-11 23:03:27 +00001033 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001034 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001035 if (OldParams)
1036 OldParam = OldParams->begin();
1037
1038 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1039 NewParamEnd = NewParams->end();
1040 NewParam != NewParamEnd; ++NewParam) {
1041 // Variables used to diagnose redundant default arguments
1042 bool RedundantDefaultArg = false;
1043 SourceLocation OldDefaultLoc;
1044 SourceLocation NewDefaultLoc;
1045
1046 // Variables used to diagnose missing default arguments
1047 bool MissingDefaultArg = false;
1048
Anders Carlsson327865d2009-06-12 23:20:15 +00001049 // C++0x [temp.param]p11:
1050 // If a template parameter of a class template is a template parameter pack,
1051 // it must be the last template parameter.
1052 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001053 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001054 diag::err_template_param_pack_must_be_last_template_parameter);
1055 Invalid = true;
1056 }
1057
Douglas Gregordba32632009-02-10 19:49:53 +00001058 if (TemplateTypeParmDecl *NewTypeParm
1059 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001060 // Check the presence of a default argument here.
1061 if (NewTypeParm->hasDefaultArgument() &&
1062 DiagnoseDefaultTemplateArgument(*this, TPC,
1063 NewTypeParm->getLocation(),
1064 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001065 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001066 NewTypeParm->removeDefaultArgument();
1067
1068 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001069 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001070 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001071
Anders Carlsson327865d2009-06-12 23:20:15 +00001072 if (NewTypeParm->isParameterPack()) {
1073 assert(!NewTypeParm->hasDefaultArgument() &&
1074 "Parameter packs can't have a default argument!");
1075 SawParameterPack = true;
1076 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001077 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001078 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001079 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1080 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1081 SawDefaultArgument = true;
1082 RedundantDefaultArg = true;
1083 PreviousDefaultArgLoc = NewDefaultLoc;
1084 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1085 // Merge the default argument from the old declaration to the
1086 // new declaration.
1087 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001088 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001089 true);
1090 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1091 } else if (NewTypeParm->hasDefaultArgument()) {
1092 SawDefaultArgument = true;
1093 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1094 } else if (SawDefaultArgument)
1095 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001096 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001097 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001098 // Check the presence of a default argument here.
1099 if (NewNonTypeParm->hasDefaultArgument() &&
1100 DiagnoseDefaultTemplateArgument(*this, TPC,
1101 NewNonTypeParm->getLocation(),
1102 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001103 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001104 }
1105
Mike Stump12b8ce12009-08-04 21:02:39 +00001106 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001107 NonTypeTemplateParmDecl *OldNonTypeParm
1108 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001109 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001110 NewNonTypeParm->hasDefaultArgument()) {
1111 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1112 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1113 SawDefaultArgument = true;
1114 RedundantDefaultArg = true;
1115 PreviousDefaultArgLoc = NewDefaultLoc;
1116 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1117 // Merge the default argument from the old declaration to the
1118 // new declaration.
1119 SawDefaultArgument = true;
1120 // FIXME: We need to create a new kind of "default argument"
1121 // expression that points to a previous template template
1122 // parameter.
1123 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001124 OldNonTypeParm->getDefaultArgument(),
1125 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001126 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1127 } else if (NewNonTypeParm->hasDefaultArgument()) {
1128 SawDefaultArgument = true;
1129 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1130 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001131 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001132 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001133 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001134 TemplateTemplateParmDecl *NewTemplateParm
1135 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001136 if (NewTemplateParm->hasDefaultArgument() &&
1137 DiagnoseDefaultTemplateArgument(*this, TPC,
1138 NewTemplateParm->getLocation(),
1139 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001140 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001141
1142 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001143 TemplateTemplateParmDecl *OldTemplateParm
1144 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001145 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001146 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001147 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1148 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001149 SawDefaultArgument = true;
1150 RedundantDefaultArg = true;
1151 PreviousDefaultArgLoc = NewDefaultLoc;
1152 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1153 // Merge the default argument from the old declaration to the
1154 // new declaration.
1155 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001156 // FIXME: We need to create a new kind of "default argument" expression
1157 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001158 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001159 OldTemplateParm->getDefaultArgument(),
1160 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001161 PreviousDefaultArgLoc
1162 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001163 } else if (NewTemplateParm->hasDefaultArgument()) {
1164 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001165 PreviousDefaultArgLoc
1166 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001167 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001168 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001169 }
1170
1171 if (RedundantDefaultArg) {
1172 // C++ [temp.param]p12:
1173 // A template-parameter shall not be given default arguments
1174 // by two different declarations in the same scope.
1175 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1176 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1177 Invalid = true;
1178 } else if (MissingDefaultArg) {
1179 // C++ [temp.param]p11:
1180 // If a template-parameter has a default template-argument,
1181 // all subsequent template-parameters shall have a default
1182 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001183 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001184 diag::err_template_param_default_arg_missing);
1185 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1186 Invalid = true;
1187 }
1188
1189 // If we have an old template parameter list that we're merging
1190 // in, move on to the next parameter.
1191 if (OldParams)
1192 ++OldParam;
1193 }
1194
1195 return Invalid;
1196}
Douglas Gregord32e0282009-02-09 23:23:08 +00001197
Mike Stump11289f42009-09-09 15:08:12 +00001198/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001199/// specifier, returning the template parameter list that applies to the
1200/// name.
1201///
1202/// \param DeclStartLoc the start of the declaration that has a scope
1203/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001204///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001205/// \param SS the scope specifier that will be matched to the given template
1206/// parameter lists. This scope specifier precedes a qualified name that is
1207/// being declared.
1208///
1209/// \param ParamLists the template parameter lists, from the outermost to the
1210/// innermost template parameter lists.
1211///
1212/// \param NumParamLists the number of template parameter lists in ParamLists.
1213///
John McCalle820e5e2010-04-13 20:37:33 +00001214/// \param IsFriend Whether to apply the slightly different rules for
1215/// matching template parameters to scope specifiers in friend
1216/// declarations.
1217///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001218/// \param IsExplicitSpecialization will be set true if the entity being
1219/// declared is an explicit specialization, false otherwise.
1220///
Mike Stump11289f42009-09-09 15:08:12 +00001221/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001222/// name that is preceded by the scope specifier @p SS. This template
1223/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001224/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001225/// template specialization), or may be NULL (if we were's declaring isn't
1226/// itself a template).
1227TemplateParameterList *
1228Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1229 const CXXScopeSpec &SS,
1230 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001231 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001232 bool IsFriend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001233 bool &IsExplicitSpecialization,
1234 bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001235 IsExplicitSpecialization = false;
1236
Douglas Gregord8d297c2009-07-21 23:53:31 +00001237 // Find the template-ids that occur within the nested-name-specifier. These
1238 // template-ids will match up with the template parameter lists.
1239 llvm::SmallVector<const TemplateSpecializationType *, 4>
1240 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001241 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1242 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001243 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1244 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001245 const Type *T = NNS->getAsType();
1246 if (!T) break;
1247
1248 // C++0x [temp.expl.spec]p17:
1249 // A member or a member template may be nested within many
1250 // enclosing class templates. In an explicit specialization for
1251 // such a member, the member declaration shall be preceded by a
1252 // template<> for each enclosing class template that is
1253 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001254 //
1255 // Following the existing practice of GNU and EDG, we allow a typedef of a
1256 // template specialization type.
1257 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1258 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001259
Mike Stump11289f42009-09-09 15:08:12 +00001260 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001261 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001262 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1263 if (!Template)
1264 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001265
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001266 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001267 ClassTemplateSpecializationDecl *SpecDecl
1268 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1269 // If the nested name specifier refers to an explicit specialization,
1270 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001271 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1272 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001273 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001274 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001275 }
Mike Stump11289f42009-09-09 15:08:12 +00001276
Douglas Gregord8d297c2009-07-21 23:53:31 +00001277 TemplateIdsInSpecifier.push_back(SpecType);
1278 }
1279 }
Mike Stump11289f42009-09-09 15:08:12 +00001280
Douglas Gregord8d297c2009-07-21 23:53:31 +00001281 // Reverse the list of template-ids in the scope specifier, so that we can
1282 // more easily match up the template-ids and the template parameter lists.
1283 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001284
Douglas Gregord8d297c2009-07-21 23:53:31 +00001285 SourceLocation FirstTemplateLoc = DeclStartLoc;
1286 if (NumParamLists)
1287 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001288
Douglas Gregord8d297c2009-07-21 23:53:31 +00001289 // Match the template-ids found in the specifier to the template parameter
1290 // lists.
1291 unsigned Idx = 0;
1292 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1293 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001294 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1295 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001296 if (Idx >= NumParamLists) {
1297 // We have a template-id without a corresponding template parameter
1298 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001299
1300 // ...which is fine if this is a friend declaration.
1301 if (IsFriend) {
1302 IsExplicitSpecialization = true;
1303 break;
1304 }
1305
Douglas Gregord8d297c2009-07-21 23:53:31 +00001306 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001307 // FIXME: the location information here isn't great.
1308 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001309 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001310 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001311 << SS.getRange();
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001312 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001313 } else {
1314 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1315 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001316 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001317 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001318 }
1319 return 0;
1320 }
Mike Stump11289f42009-09-09 15:08:12 +00001321
Douglas Gregord8d297c2009-07-21 23:53:31 +00001322 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001323 if (DependentTemplateId) {
John McCall2408e322010-04-27 00:57:59 +00001324 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00001325
John McCall2408e322010-04-27 00:57:59 +00001326 // Are there cases in (e.g.) friends where this won't match?
1327 if (const InjectedClassNameType *Injected
1328 = TemplateId->getAs<InjectedClassNameType>()) {
1329 CXXRecordDecl *Record = Injected->getDecl();
1330 if (ClassTemplatePartialSpecializationDecl *Partial =
1331 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1332 ExpectedTemplateParams = Partial->getTemplateParameters();
1333 else
1334 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1335 ->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001336 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001337
John McCall2408e322010-04-27 00:57:59 +00001338 if (ExpectedTemplateParams)
1339 TemplateParameterListsAreEqual(ParamLists[Idx],
1340 ExpectedTemplateParams,
1341 true, TPL_TemplateMatch);
1342
Douglas Gregored5731f2009-11-25 17:50:39 +00001343 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001344 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001345 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001346 diag::err_template_param_list_matches_nontemplate)
1347 << TemplateId
1348 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001349 else
1350 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001351 }
Mike Stump11289f42009-09-09 15:08:12 +00001352
Douglas Gregord8d297c2009-07-21 23:53:31 +00001353 // If there were at least as many template-ids as there were template
1354 // parameter lists, then there are no template parameter lists remaining for
1355 // the declaration itself.
1356 if (Idx >= NumParamLists)
1357 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001358
Douglas Gregord8d297c2009-07-21 23:53:31 +00001359 // If there were too many template parameter lists, complain about that now.
1360 if (Idx != NumParamLists - 1) {
1361 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001362 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001363 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001364 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1365 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001366 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1367 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001368
1369 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1370 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1371 diag::note_explicit_template_spec_does_not_need_header)
1372 << ExplicitSpecializationsInSpecifier.back();
1373 ExplicitSpecializationsInSpecifier.pop_back();
1374 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001375
1376 // We have a template parameter list with no corresponding scope, which
1377 // means that the resulting template declaration can't be instantiated
1378 // properly (we'll end up with dependent nodes when we shouldn't).
1379 if (!isExplicitSpecHeader)
1380 Invalid = true;
1381
Douglas Gregord8d297c2009-07-21 23:53:31 +00001382 ++Idx;
1383 }
1384 }
Mike Stump11289f42009-09-09 15:08:12 +00001385
Douglas Gregord8d297c2009-07-21 23:53:31 +00001386 // Return the last template parameter list, which corresponds to the
1387 // entity being declared.
1388 return ParamLists[NumParamLists - 1];
1389}
1390
Douglas Gregordc572a32009-03-30 22:58:21 +00001391QualType Sema::CheckTemplateIdType(TemplateName Name,
1392 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001393 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001394 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001395 if (!Template) {
1396 // The template name does not resolve to a template, so we just
1397 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001398 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001399 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001400
Douglas Gregorc40290e2009-03-09 23:48:35 +00001401 // Check that the template argument list is well-formed for this
1402 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001403 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001404 TemplateArgs.size());
1405 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001406 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001407 return QualType();
1408
Mike Stump11289f42009-09-09 15:08:12 +00001409 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001410 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001411 "Converted template argument list is too short!");
1412
1413 QualType CanonType;
1414
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001415 if (Name.isDependent() ||
1416 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001417 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001418 // This class template specialization is a dependent
1419 // type. Therefore, its canonical type is another class template
1420 // specialization type that contains all of the converted
1421 // arguments in canonical form. This ensures that, e.g., A<T> and
1422 // A<T, T> have identical types when A is declared as:
1423 //
1424 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001425 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001426 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001427 Converted.getFlatArguments(),
1428 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001429
Douglas Gregora8e02e72009-07-28 23:00:59 +00001430 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001431 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001432 // In the future, we need to teach getTemplateSpecializationType to only
1433 // build the canonical type and return that to us.
1434 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001435
1436 // This might work out to be a current instantiation, in which
1437 // case the canonical type needs to be the InjectedClassNameType.
1438 //
1439 // TODO: in theory this could be a simple hashtable lookup; most
1440 // changes to CurContext don't change the set of current
1441 // instantiations.
1442 if (isa<ClassTemplateDecl>(Template)) {
1443 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1444 // If we get out to a namespace, we're done.
1445 if (Ctx->isFileContext()) break;
1446
1447 // If this isn't a record, keep looking.
1448 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1449 if (!Record) continue;
1450
1451 // Look for one of the two cases with InjectedClassNameTypes
1452 // and check whether it's the same template.
1453 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1454 !Record->getDescribedClassTemplate())
1455 continue;
1456
1457 // Fetch the injected class name type and check whether its
1458 // injected type is equal to the type we just built.
1459 QualType ICNT = Context.getTypeDeclType(Record);
1460 QualType Injected = cast<InjectedClassNameType>(ICNT)
1461 ->getInjectedSpecializationType();
1462
1463 if (CanonType != Injected->getCanonicalTypeInternal())
1464 continue;
1465
1466 // If so, the canonical type of this TST is the injected
1467 // class name type of the record we just found.
1468 assert(ICNT.isCanonical());
1469 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00001470 break;
1471 }
1472 }
Mike Stump11289f42009-09-09 15:08:12 +00001473 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001474 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001475 // Find the class template specialization declaration that
1476 // corresponds to these arguments.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001477 void *InsertPos = 0;
1478 ClassTemplateSpecializationDecl *Decl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001479 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
1480 Converted.flatSize(), InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001481 if (!Decl) {
1482 // This is the first time we have referenced this class template
1483 // specialization. Create the canonical declaration and add it to
1484 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001485 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001486 ClassTemplate->getTemplatedDecl()->getTagKind(),
1487 ClassTemplate->getDeclContext(),
1488 ClassTemplate->getLocation(),
1489 ClassTemplate,
1490 Converted, 0);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001491 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001492 Decl->setLexicalDeclContext(CurContext);
1493 }
1494
1495 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001496 assert(isa<RecordType>(CanonType) &&
1497 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001498 }
Mike Stump11289f42009-09-09 15:08:12 +00001499
Douglas Gregorc40290e2009-03-09 23:48:35 +00001500 // Build the fully-sugared type for this class template
1501 // specialization, which refers back to the class template
1502 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00001503 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001504}
1505
Douglas Gregor67a65642009-02-17 23:15:12 +00001506Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001507Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001508 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001509 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001510 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001511 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001512
Douglas Gregorc40290e2009-03-09 23:48:35 +00001513 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001514 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001515 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001516
John McCall6b51f282009-11-23 01:53:49 +00001517 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001518 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001519
1520 if (Result.isNull())
1521 return true;
1522
John McCallbcd03502009-12-07 02:54:59 +00001523 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001524 TemplateSpecializationTypeLoc TL
1525 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1526 TL.setTemplateNameLoc(TemplateLoc);
1527 TL.setLAngleLoc(LAngleLoc);
1528 TL.setRAngleLoc(RAngleLoc);
1529 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1530 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1531
1532 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001533}
John McCall06f6fe8d2009-09-04 01:14:41 +00001534
John McCalld8fe9af2009-09-08 17:47:29 +00001535Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1536 TagUseKind TUK,
1537 DeclSpec::TST TagSpec,
1538 SourceLocation TagLoc) {
1539 if (TypeResult.isInvalid())
1540 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001541
John McCall0ad16662009-10-29 08:12:44 +00001542 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001543 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001544 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001545
John McCalld8fe9af2009-09-08 17:47:29 +00001546 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001547 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001548
John McCalld8fe9af2009-09-08 17:47:29 +00001549 if (const RecordType *RT = Type->getAs<RecordType>()) {
1550 RecordDecl *D = RT->getDecl();
1551
1552 IdentifierInfo *Id = D->getIdentifier();
1553 assert(Id && "templated class must have an identifier");
1554
1555 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1556 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001557 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001558 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001559 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001560 }
1561 }
1562
Abramo Bagnara6150c882010-05-11 21:36:43 +00001563 ElaboratedTypeKeyword Keyword
1564 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1565 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001566
1567 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001568}
1569
John McCalle66edc12009-11-24 19:00:30 +00001570Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1571 LookupResult &R,
1572 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001573 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001574 // FIXME: Can we do any checking at this point? I guess we could check the
1575 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001576 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001577 // though.
John McCalle66edc12009-11-24 19:00:30 +00001578
1579 // These should be filtered out by our callers.
1580 assert(!R.empty() && "empty lookup results when building templateid");
1581 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1582
1583 NestedNameSpecifier *Qualifier = 0;
1584 SourceRange QualifierRange;
1585 if (SS.isSet()) {
1586 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1587 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001588 }
John McCall58cc69d2010-01-27 01:50:18 +00001589
1590 // We don't want lookup warnings at this point.
1591 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001592
John McCalle66edc12009-11-24 19:00:30 +00001593 bool Dependent
1594 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1595 &TemplateArgs);
1596 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001597 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001598 Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001599 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001600 RequiresADL, TemplateArgs,
1601 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001602
1603 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001604}
1605
John McCalle66edc12009-11-24 19:00:30 +00001606// We actually only call this from template instantiation.
1607Sema::OwningExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001608Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001609 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +00001610 const TemplateArgumentListInfo &TemplateArgs) {
1611 DeclContext *DC;
1612 if (!(DC = computeDeclContext(SS, false)) ||
1613 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001614 RequireCompleteDeclContext(SS, DC))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001615 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001616
Douglas Gregor786123d2010-05-21 23:18:07 +00001617 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001618 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00001619 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1620 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00001621
John McCalle66edc12009-11-24 19:00:30 +00001622 if (R.isAmbiguous())
1623 return ExprError();
1624
1625 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001626 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1627 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001628 return ExprError();
1629 }
1630
1631 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001632 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1633 << (NestedNameSpecifier*) SS.getScopeRep()
1634 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001635 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1636 return ExprError();
1637 }
1638
1639 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001640}
1641
Douglas Gregorb67535d2009-03-31 00:43:58 +00001642/// \brief Form a dependent template name.
1643///
1644/// This action forms a dependent template name given the template
1645/// name and its (presumably dependent) scope specifier. For
1646/// example, given "MetaFun::template apply", the scope specifier \p
1647/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1648/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregorbb119652010-06-16 23:00:59 +00001649TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1650 SourceLocation TemplateKWLoc,
1651 CXXScopeSpec &SS,
1652 UnqualifiedId &Name,
1653 TypeTy *ObjectType,
1654 bool EnteringContext,
1655 TemplateTy &Result) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00001656 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1657 !getLangOptions().CPlusPlus0x)
1658 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1659 << FixItHint::CreateRemoval(TemplateKWLoc);
1660
Douglas Gregor9abe2372010-01-19 16:01:07 +00001661 DeclContext *LookupCtx = 0;
1662 if (SS.isSet())
1663 LookupCtx = computeDeclContext(SS, EnteringContext);
1664 if (!LookupCtx && ObjectType)
1665 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1666 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001667 // C++0x [temp.names]p5:
1668 // If a name prefixed by the keyword template is not the name of
1669 // a template, the program is ill-formed. [Note: the keyword
1670 // template may not be applied to non-template members of class
1671 // templates. -end note ] [ Note: as is the case with the
1672 // typename prefix, the template prefix is allowed in cases
1673 // where it is not strictly necessary; i.e., when the
1674 // nested-name-specifier or the expression on the left of the ->
1675 // or . is not dependent on a template-parameter, or the use
1676 // does not appear in the scope of a template. -end note]
1677 //
1678 // Note: C++03 was more strict here, because it banned the use of
1679 // the "template" keyword prior to a template-name that was not a
1680 // dependent name. C++ DR468 relaxed this requirement (the
1681 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00001682 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00001683 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001684 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1685 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00001686 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001687 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1688 isa<CXXRecordDecl>(LookupCtx) &&
1689 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregorbb119652010-06-16 23:00:59 +00001690 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00001691 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001692 Diag(Name.getSourceRange().getBegin(),
1693 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001694 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001695 << Name.getSourceRange()
1696 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001697 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00001698 } else {
1699 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00001700 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001701 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001702 }
1703
Mike Stump11289f42009-09-09 15:08:12 +00001704 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001705 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001706
1707 switch (Name.getKind()) {
1708 case UnqualifiedId::IK_Identifier:
Douglas Gregorbb119652010-06-16 23:00:59 +00001709 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1710 Name.Identifier));
1711 return TNK_Dependent_template_name;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001712
Douglas Gregor71395fa2009-11-04 00:56:37 +00001713 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00001714 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00001715 Name.OperatorFunctionId.Operator));
Douglas Gregorbb119652010-06-16 23:00:59 +00001716 return TNK_Dependent_template_name;
Alexis Hunted0530f2009-11-28 08:58:14 +00001717
1718 case UnqualifiedId::IK_LiteralOperatorId:
1719 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1720
Douglas Gregor3cf81312009-11-03 23:16:33 +00001721 default:
1722 break;
1723 }
1724
1725 Diag(Name.getSourceRange().getBegin(),
1726 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001727 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001728 << Name.getSourceRange()
1729 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001730 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001731}
1732
Mike Stump11289f42009-09-09 15:08:12 +00001733bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001734 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001735 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001736 const TemplateArgument &Arg = AL.getArgument();
1737
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001738 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001739 switch(Arg.getKind()) {
1740 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001741 // C++ [temp.arg.type]p1:
1742 // A template-argument for a template-parameter which is a
1743 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001744 break;
1745 case TemplateArgument::Template: {
1746 // We have a template type parameter but the template argument
1747 // is a template without any arguments.
1748 SourceRange SR = AL.getSourceRange();
1749 TemplateName Name = Arg.getAsTemplate();
1750 Diag(SR.getBegin(), diag::err_template_missing_args)
1751 << Name << SR;
1752 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1753 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001754
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001755 return true;
1756 }
1757 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001758 // We have a template type parameter but the template argument
1759 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001760 SourceRange SR = AL.getSourceRange();
1761 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001762 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001763
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001764 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001765 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001766 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001767
John McCallbcd03502009-12-07 02:54:59 +00001768 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001769 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001770
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001771 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001772 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001773 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001774 return false;
1775}
1776
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001777/// \brief Substitute template arguments into the default template argument for
1778/// the given template type parameter.
1779///
1780/// \param SemaRef the semantic analysis object for which we are performing
1781/// the substitution.
1782///
1783/// \param Template the template that we are synthesizing template arguments
1784/// for.
1785///
1786/// \param TemplateLoc the location of the template name that started the
1787/// template-id we are checking.
1788///
1789/// \param RAngleLoc the location of the right angle bracket ('>') that
1790/// terminates the template-id.
1791///
1792/// \param Param the template template parameter whose default we are
1793/// substituting into.
1794///
1795/// \param Converted the list of template arguments provided for template
1796/// parameters that precede \p Param in the template parameter list.
1797///
1798/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001799static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001800SubstDefaultTemplateArgument(Sema &SemaRef,
1801 TemplateDecl *Template,
1802 SourceLocation TemplateLoc,
1803 SourceLocation RAngleLoc,
1804 TemplateTypeParmDecl *Param,
1805 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001806 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001807
1808 // If the argument type is dependent, instantiate it now based
1809 // on the previously-computed template arguments.
1810 if (ArgType->getType()->isDependentType()) {
1811 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1812 /*TakeArgs=*/false);
1813
1814 MultiLevelTemplateArgumentList AllTemplateArgs
1815 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1816
1817 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1818 Template, Converted.getFlatArguments(),
1819 Converted.flatSize(),
1820 SourceRange(TemplateLoc, RAngleLoc));
1821
1822 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1823 Param->getDefaultArgumentLoc(),
1824 Param->getDeclName());
1825 }
1826
1827 return ArgType;
1828}
1829
1830/// \brief Substitute template arguments into the default template argument for
1831/// the given non-type template parameter.
1832///
1833/// \param SemaRef the semantic analysis object for which we are performing
1834/// the substitution.
1835///
1836/// \param Template the template that we are synthesizing template arguments
1837/// for.
1838///
1839/// \param TemplateLoc the location of the template name that started the
1840/// template-id we are checking.
1841///
1842/// \param RAngleLoc the location of the right angle bracket ('>') that
1843/// terminates the template-id.
1844///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001845/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001846/// substituting into.
1847///
1848/// \param Converted the list of template arguments provided for template
1849/// parameters that precede \p Param in the template parameter list.
1850///
1851/// \returns the substituted template argument, or NULL if an error occurred.
1852static Sema::OwningExprResult
1853SubstDefaultTemplateArgument(Sema &SemaRef,
1854 TemplateDecl *Template,
1855 SourceLocation TemplateLoc,
1856 SourceLocation RAngleLoc,
1857 NonTypeTemplateParmDecl *Param,
1858 TemplateArgumentListBuilder &Converted) {
1859 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1860 /*TakeArgs=*/false);
1861
1862 MultiLevelTemplateArgumentList AllTemplateArgs
1863 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1864
1865 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1866 Template, Converted.getFlatArguments(),
1867 Converted.flatSize(),
1868 SourceRange(TemplateLoc, RAngleLoc));
1869
1870 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1871}
1872
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001873/// \brief Substitute template arguments into the default template argument for
1874/// the given template template parameter.
1875///
1876/// \param SemaRef the semantic analysis object for which we are performing
1877/// the substitution.
1878///
1879/// \param Template the template that we are synthesizing template arguments
1880/// for.
1881///
1882/// \param TemplateLoc the location of the template name that started the
1883/// template-id we are checking.
1884///
1885/// \param RAngleLoc the location of the right angle bracket ('>') that
1886/// terminates the template-id.
1887///
1888/// \param Param the template template parameter whose default we are
1889/// substituting into.
1890///
1891/// \param Converted the list of template arguments provided for template
1892/// parameters that precede \p Param in the template parameter list.
1893///
1894/// \returns the substituted template argument, or NULL if an error occurred.
1895static TemplateName
1896SubstDefaultTemplateArgument(Sema &SemaRef,
1897 TemplateDecl *Template,
1898 SourceLocation TemplateLoc,
1899 SourceLocation RAngleLoc,
1900 TemplateTemplateParmDecl *Param,
1901 TemplateArgumentListBuilder &Converted) {
1902 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1903 /*TakeArgs=*/false);
1904
1905 MultiLevelTemplateArgumentList AllTemplateArgs
1906 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1907
1908 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1909 Template, Converted.getFlatArguments(),
1910 Converted.flatSize(),
1911 SourceRange(TemplateLoc, RAngleLoc));
1912
1913 return SemaRef.SubstTemplateName(
1914 Param->getDefaultArgument().getArgument().getAsTemplate(),
1915 Param->getDefaultArgument().getTemplateNameLoc(),
1916 AllTemplateArgs);
1917}
1918
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001919/// \brief If the given template parameter has a default template
1920/// argument, substitute into that default template argument and
1921/// return the corresponding template argument.
1922TemplateArgumentLoc
1923Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1924 SourceLocation TemplateLoc,
1925 SourceLocation RAngleLoc,
1926 Decl *Param,
1927 TemplateArgumentListBuilder &Converted) {
1928 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1929 if (!TypeParm->hasDefaultArgument())
1930 return TemplateArgumentLoc();
1931
John McCallbcd03502009-12-07 02:54:59 +00001932 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001933 TemplateLoc,
1934 RAngleLoc,
1935 TypeParm,
1936 Converted);
1937 if (DI)
1938 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1939
1940 return TemplateArgumentLoc();
1941 }
1942
1943 if (NonTypeTemplateParmDecl *NonTypeParm
1944 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1945 if (!NonTypeParm->hasDefaultArgument())
1946 return TemplateArgumentLoc();
1947
1948 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1949 TemplateLoc,
1950 RAngleLoc,
1951 NonTypeParm,
1952 Converted);
1953 if (Arg.isInvalid())
1954 return TemplateArgumentLoc();
1955
1956 Expr *ArgE = Arg.takeAs<Expr>();
1957 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1958 }
1959
1960 TemplateTemplateParmDecl *TempTempParm
1961 = cast<TemplateTemplateParmDecl>(Param);
1962 if (!TempTempParm->hasDefaultArgument())
1963 return TemplateArgumentLoc();
1964
1965 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1966 TemplateLoc,
1967 RAngleLoc,
1968 TempTempParm,
1969 Converted);
1970 if (TName.isNull())
1971 return TemplateArgumentLoc();
1972
1973 return TemplateArgumentLoc(TemplateArgument(TName),
1974 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1975 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1976}
1977
Douglas Gregorda0fb532009-11-11 19:31:23 +00001978/// \brief Check that the given template argument corresponds to the given
1979/// template parameter.
1980bool Sema::CheckTemplateArgument(NamedDecl *Param,
1981 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001982 TemplateDecl *Template,
1983 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001984 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001985 TemplateArgumentListBuilder &Converted,
1986 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001987 // Check template type parameters.
1988 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001989 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001990
Douglas Gregoreebed722009-11-11 19:41:09 +00001991 // Check non-type template parameters.
1992 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001993 // Do substitution on the type of the non-type template parameter
1994 // with the template arguments we've seen thus far.
1995 QualType NTTPType = NTTP->getType();
1996 if (NTTPType->isDependentType()) {
1997 // Do substitution on the type of the non-type template parameter.
1998 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1999 NTTP, Converted.getFlatArguments(),
2000 Converted.flatSize(),
2001 SourceRange(TemplateLoc, RAngleLoc));
2002
2003 TemplateArgumentList TemplateArgs(Context, Converted,
2004 /*TakeArgs=*/false);
2005 NTTPType = SubstType(NTTPType,
2006 MultiLevelTemplateArgumentList(TemplateArgs),
2007 NTTP->getLocation(),
2008 NTTP->getDeclName());
2009 // If that worked, check the non-type template parameter type
2010 // for validity.
2011 if (!NTTPType.isNull())
2012 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2013 NTTP->getLocation());
2014 if (NTTPType.isNull())
2015 return true;
2016 }
2017
2018 switch (Arg.getArgument().getKind()) {
2019 case TemplateArgument::Null:
2020 assert(false && "Should never see a NULL template argument here");
2021 return true;
2022
2023 case TemplateArgument::Expression: {
2024 Expr *E = Arg.getArgument().getAsExpr();
2025 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002026 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002027 return true;
2028
2029 Converted.Append(Result);
2030 break;
2031 }
2032
2033 case TemplateArgument::Declaration:
2034 case TemplateArgument::Integral:
2035 // We've already checked this template argument, so just copy
2036 // it to the list of converted arguments.
2037 Converted.Append(Arg.getArgument());
2038 break;
2039
2040 case TemplateArgument::Template:
2041 // We were given a template template argument. It may not be ill-formed;
2042 // see below.
2043 if (DependentTemplateName *DTN
2044 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2045 // We have a template argument such as \c T::template X, which we
2046 // parsed as a template template argument. However, since we now
2047 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002048 // template name into an expression.
2049
2050 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2051 Arg.getTemplateNameLoc());
2052
John McCalle66edc12009-11-24 19:00:30 +00002053 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2054 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002055 Arg.getTemplateQualifierRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002056 NameInfo);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002057
2058 TemplateArgument Result;
2059 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2060 return true;
2061
2062 Converted.Append(Result);
2063 break;
2064 }
2065
2066 // We have a template argument that actually does refer to a class
2067 // template, template alias, or template template parameter, and
2068 // therefore cannot be a non-type template argument.
2069 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2070 << Arg.getSourceRange();
2071
2072 Diag(Param->getLocation(), diag::note_template_param_here);
2073 return true;
2074
2075 case TemplateArgument::Type: {
2076 // We have a non-type template parameter but the template
2077 // argument is a type.
2078
2079 // C++ [temp.arg]p2:
2080 // In a template-argument, an ambiguity between a type-id and
2081 // an expression is resolved to a type-id, regardless of the
2082 // form of the corresponding template-parameter.
2083 //
2084 // We warn specifically about this case, since it can be rather
2085 // confusing for users.
2086 QualType T = Arg.getArgument().getAsType();
2087 SourceRange SR = Arg.getSourceRange();
2088 if (T->isFunctionType())
2089 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2090 else
2091 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2092 Diag(Param->getLocation(), diag::note_template_param_here);
2093 return true;
2094 }
2095
2096 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002097 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002098 break;
2099 }
2100
2101 return false;
2102 }
2103
2104
2105 // Check template template parameters.
2106 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2107
2108 // Substitute into the template parameter list of the template
2109 // template parameter, since previously-supplied template arguments
2110 // may appear within the template template parameter.
2111 {
2112 // Set up a template instantiation context.
2113 LocalInstantiationScope Scope(*this);
2114 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2115 TempParm, Converted.getFlatArguments(),
2116 Converted.flatSize(),
2117 SourceRange(TemplateLoc, RAngleLoc));
2118
2119 TemplateArgumentList TemplateArgs(Context, Converted,
2120 /*TakeArgs=*/false);
2121 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2122 SubstDecl(TempParm, CurContext,
2123 MultiLevelTemplateArgumentList(TemplateArgs)));
2124 if (!TempParm)
2125 return true;
2126
2127 // FIXME: TempParam is leaked.
2128 }
2129
2130 switch (Arg.getArgument().getKind()) {
2131 case TemplateArgument::Null:
2132 assert(false && "Should never see a NULL template argument here");
2133 return true;
2134
2135 case TemplateArgument::Template:
2136 if (CheckTemplateArgument(TempParm, Arg))
2137 return true;
2138
2139 Converted.Append(Arg.getArgument());
2140 break;
2141
2142 case TemplateArgument::Expression:
2143 case TemplateArgument::Type:
2144 // We have a template template parameter but the template
2145 // argument does not refer to a template.
2146 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2147 return true;
2148
2149 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002150 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002151 "Declaration argument with template template parameter");
2152 break;
2153 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002154 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002155 "Integral argument with template template parameter");
2156 break;
2157
2158 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002159 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002160 break;
2161 }
2162
2163 return false;
2164}
2165
Douglas Gregord32e0282009-02-09 23:23:08 +00002166/// \brief Check that the given template argument list is well-formed
2167/// for specializing the given template.
2168bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2169 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002170 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002171 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002172 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002173 TemplateParameterList *Params = Template->getTemplateParameters();
2174 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002175 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002176 bool Invalid = false;
2177
John McCall6b51f282009-11-23 01:53:49 +00002178 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2179
Mike Stump11289f42009-09-09 15:08:12 +00002180 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002181 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002182
Anders Carlsson15201f12009-06-13 02:08:00 +00002183 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002184 (NumArgs < Params->getMinRequiredArguments() &&
2185 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002186 // FIXME: point at either the first arg beyond what we can handle,
2187 // or the '>', depending on whether we have too many or too few
2188 // arguments.
2189 SourceRange Range;
2190 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002191 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002192 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2193 << (NumArgs > NumParams)
2194 << (isa<ClassTemplateDecl>(Template)? 0 :
2195 isa<FunctionTemplateDecl>(Template)? 1 :
2196 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2197 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002198 Diag(Template->getLocation(), diag::note_template_decl_here)
2199 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002200 Invalid = true;
2201 }
Mike Stump11289f42009-09-09 15:08:12 +00002202
2203 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002204 // [...] The type and form of each template-argument specified in
2205 // a template-id shall match the type and form specified for the
2206 // corresponding parameter declared by the template in its
2207 // template-parameter-list.
2208 unsigned ArgIdx = 0;
2209 for (TemplateParameterList::iterator Param = Params->begin(),
2210 ParamEnd = Params->end();
2211 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002212 if (ArgIdx > NumArgs && PartialTemplateArgs)
2213 break;
Mike Stump11289f42009-09-09 15:08:12 +00002214
Douglas Gregoreebed722009-11-11 19:41:09 +00002215 // If we have a template parameter pack, check every remaining template
2216 // argument against that template parameter pack.
2217 if ((*Param)->isTemplateParameterPack()) {
2218 Converted.BeginPack();
2219 for (; ArgIdx < NumArgs; ++ArgIdx) {
2220 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2221 TemplateLoc, RAngleLoc, Converted)) {
2222 Invalid = true;
2223 break;
2224 }
2225 }
2226 Converted.EndPack();
2227 continue;
2228 }
2229
Douglas Gregor84d49a22009-11-11 21:54:23 +00002230 if (ArgIdx < NumArgs) {
2231 // Check the template argument we were given.
2232 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2233 TemplateLoc, RAngleLoc, Converted))
2234 return true;
2235
2236 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002237 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002238
Douglas Gregor84d49a22009-11-11 21:54:23 +00002239 // We have a default template argument that we will use.
2240 TemplateArgumentLoc Arg;
2241
2242 // Retrieve the default template argument from the template
2243 // parameter. For each kind of template parameter, we substitute the
2244 // template arguments provided thus far and any "outer" template arguments
2245 // (when the template parameter was part of a nested template) into
2246 // the default argument.
2247 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2248 if (!TTP->hasDefaultArgument()) {
2249 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2250 break;
2251 }
2252
John McCallbcd03502009-12-07 02:54:59 +00002253 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002254 Template,
2255 TemplateLoc,
2256 RAngleLoc,
2257 TTP,
2258 Converted);
2259 if (!ArgType)
2260 return true;
2261
2262 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2263 ArgType);
2264 } else if (NonTypeTemplateParmDecl *NTTP
2265 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2266 if (!NTTP->hasDefaultArgument()) {
2267 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2268 break;
2269 }
2270
2271 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2272 TemplateLoc,
2273 RAngleLoc,
2274 NTTP,
2275 Converted);
2276 if (E.isInvalid())
2277 return true;
2278
2279 Expr *Ex = E.takeAs<Expr>();
2280 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2281 } else {
2282 TemplateTemplateParmDecl *TempParm
2283 = cast<TemplateTemplateParmDecl>(*Param);
2284
2285 if (!TempParm->hasDefaultArgument()) {
2286 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2287 break;
2288 }
2289
2290 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2291 TemplateLoc,
2292 RAngleLoc,
2293 TempParm,
2294 Converted);
2295 if (Name.isNull())
2296 return true;
2297
2298 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2299 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2300 TempParm->getDefaultArgument().getTemplateNameLoc());
2301 }
2302
2303 // Introduce an instantiation record that describes where we are using
2304 // the default template argument.
2305 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2306 Converted.getFlatArguments(),
2307 Converted.flatSize(),
2308 SourceRange(TemplateLoc, RAngleLoc));
2309
2310 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002311 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002312 RAngleLoc, Converted))
2313 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002314 }
2315
2316 return Invalid;
2317}
2318
2319/// \brief Check a template argument against its corresponding
2320/// template type parameter.
2321///
2322/// This routine implements the semantics of C++ [temp.arg.type]. It
2323/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002324bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002325 TypeSourceInfo *ArgInfo) {
2326 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002327 QualType Arg = ArgInfo->getType();
2328
Douglas Gregord32e0282009-02-09 23:23:08 +00002329 // C++ [temp.arg.type]p2:
2330 // A local type, a type with no linkage, an unnamed type or a type
2331 // compounded from any of these types shall not be used as a
2332 // template-argument for a template type-parameter.
2333 //
Douglas Gregor959d5a02010-05-22 16:17:30 +00002334 // FIXME: Perform the unnamed type check.
2335 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002336 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002337 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002338 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002339 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002340 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002341 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002342 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall0ad16662009-10-29 08:12:44 +00002343 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2344 << QualType(Tag, 0) << SR;
2345 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002346 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002347 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002348 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2349 return true;
Douglas Gregor959d5a02010-05-22 16:17:30 +00002350 } else if (Arg->isVariablyModifiedType()) {
2351 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2352 << Arg;
2353 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002354 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002355 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002356 }
2357
2358 return false;
2359}
2360
Douglas Gregorccb07762009-02-11 19:52:55 +00002361/// \brief Checks whether the given template argument is the address
2362/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002363static bool
2364CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2365 NonTypeTemplateParmDecl *Param,
2366 QualType ParamType,
2367 Expr *ArgIn,
2368 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002369 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002370 Expr *Arg = ArgIn;
2371 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002372
2373 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002374 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002375 Arg = Cast->getSubExpr();
2376
2377 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002378 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002379 // A template-argument for a non-type, non-template
2380 // template-parameter shall be one of: [...]
2381 //
2382 // -- the address of an object or function with external
2383 // linkage, including function templates and function
2384 // template-ids but excluding non-static class members,
2385 // expressed as & id-expression where the & is optional if
2386 // the name refers to a function or array, or if the
2387 // corresponding template-parameter is a reference; or
2388 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002389
Douglas Gregorccb07762009-02-11 19:52:55 +00002390 // Ignore (and complain about) any excess parentheses.
2391 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2392 if (!Invalid) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002393 S.Diag(Arg->getSourceRange().getBegin(),
2394 diag::err_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002395 << Arg->getSourceRange();
2396 Invalid = true;
2397 }
2398
2399 Arg = Parens->getSubExpr();
2400 }
2401
Douglas Gregorb242683d2010-04-01 18:32:35 +00002402 bool AddressTaken = false;
2403 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002404 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002405 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002406 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002407 AddressTaken = true;
2408 AddrOpLoc = UnOp->getOperatorLoc();
2409 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002410 } else
2411 DRE = dyn_cast<DeclRefExpr>(Arg);
2412
Douglas Gregorb242683d2010-04-01 18:32:35 +00002413 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002414 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2415 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002416 S.Diag(Param->getLocation(), diag::note_template_param_here);
2417 return true;
2418 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002419
2420 // Stop checking the precise nature of the argument if it is value dependent,
2421 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002422 if (Arg->isValueDependent()) {
2423 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002424 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002425 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002426
Douglas Gregorb242683d2010-04-01 18:32:35 +00002427 if (!isa<ValueDecl>(DRE->getDecl())) {
2428 S.Diag(Arg->getSourceRange().getBegin(),
2429 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002430 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002431 S.Diag(Param->getLocation(), diag::note_template_param_here);
2432 return true;
2433 }
2434
2435 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002436
2437 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002438 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2439 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002440 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002441 S.Diag(Param->getLocation(), diag::note_template_param_here);
2442 return true;
2443 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002444
2445 // Cannot refer to non-static member functions
2446 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002447 if (!Method->isStatic()) {
2448 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002449 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002450 S.Diag(Param->getLocation(), diag::note_template_param_here);
2451 return true;
2452 }
Mike Stump11289f42009-09-09 15:08:12 +00002453
Douglas Gregorccb07762009-02-11 19:52:55 +00002454 // Functions must have external linkage.
2455 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002456 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002457 S.Diag(Arg->getSourceRange().getBegin(),
2458 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002459 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002460 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002461 << true;
2462 return true;
2463 }
2464
2465 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002466 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002467
Douglas Gregorb242683d2010-04-01 18:32:35 +00002468 // If the template parameter has pointer type, the function decays.
2469 if (ParamType->isPointerType() && !AddressTaken)
2470 ArgType = S.Context.getPointerType(Func->getType());
2471 else if (AddressTaken && ParamType->isReferenceType()) {
2472 // If we originally had an address-of operator, but the
2473 // parameter has reference type, complain and (if things look
2474 // like they will work) drop the address-of operator.
2475 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2476 ParamType.getNonReferenceType())) {
2477 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2478 << ParamType;
2479 S.Diag(Param->getLocation(), diag::note_template_param_here);
2480 return true;
2481 }
2482
2483 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2484 << ParamType
2485 << FixItHint::CreateRemoval(AddrOpLoc);
2486 S.Diag(Param->getLocation(), diag::note_template_param_here);
2487
2488 ArgType = Func->getType();
2489 }
2490 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002491 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002492 S.Diag(Arg->getSourceRange().getBegin(),
2493 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002494 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002495 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002496 << true;
2497 return true;
2498 }
2499
Douglas Gregorb242683d2010-04-01 18:32:35 +00002500 // A value of reference type is not an object.
2501 if (Var->getType()->isReferenceType()) {
2502 S.Diag(Arg->getSourceRange().getBegin(),
2503 diag::err_template_arg_reference_var)
2504 << Var->getType() << Arg->getSourceRange();
2505 S.Diag(Param->getLocation(), diag::note_template_param_here);
2506 return true;
2507 }
2508
Douglas Gregorccb07762009-02-11 19:52:55 +00002509 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002510 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002511
2512 // If the template parameter has pointer type, we must have taken
2513 // the address of this object.
2514 if (ParamType->isReferenceType()) {
2515 if (AddressTaken) {
2516 // If we originally had an address-of operator, but the
2517 // parameter has reference type, complain and (if things look
2518 // like they will work) drop the address-of operator.
2519 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2520 ParamType.getNonReferenceType())) {
2521 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2522 << ParamType;
2523 S.Diag(Param->getLocation(), diag::note_template_param_here);
2524 return true;
2525 }
2526
2527 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2528 << ParamType
2529 << FixItHint::CreateRemoval(AddrOpLoc);
2530 S.Diag(Param->getLocation(), diag::note_template_param_here);
2531
2532 ArgType = Var->getType();
2533 }
2534 } else if (!AddressTaken && ParamType->isPointerType()) {
2535 if (Var->getType()->isArrayType()) {
2536 // Array-to-pointer decay.
2537 ArgType = S.Context.getArrayDecayedType(Var->getType());
2538 } else {
2539 // If the template parameter has pointer type but the address of
2540 // this object was not taken, complain and (possibly) recover by
2541 // taking the address of the entity.
2542 ArgType = S.Context.getPointerType(Var->getType());
2543 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2544 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2545 << ParamType;
2546 S.Diag(Param->getLocation(), diag::note_template_param_here);
2547 return true;
2548 }
2549
2550 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2551 << ParamType
2552 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2553
2554 S.Diag(Param->getLocation(), diag::note_template_param_here);
2555 }
2556 }
2557 } else {
2558 // We found something else, but we don't know specifically what it is.
2559 S.Diag(Arg->getSourceRange().getBegin(),
2560 diag::err_template_arg_not_object_or_func)
2561 << Arg->getSourceRange();
2562 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2563 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002564 }
Mike Stump11289f42009-09-09 15:08:12 +00002565
Douglas Gregorb242683d2010-04-01 18:32:35 +00002566 if (ParamType->isPointerType() &&
2567 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2568 S.IsQualificationConversion(ArgType, ParamType)) {
2569 // For pointer-to-object types, qualification conversions are
2570 // permitted.
2571 } else {
2572 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2573 if (!ParamRef->getPointeeType()->isFunctionType()) {
2574 // C++ [temp.arg.nontype]p5b3:
2575 // For a non-type template-parameter of type reference to
2576 // object, no conversions apply. The type referred to by the
2577 // reference may be more cv-qualified than the (otherwise
2578 // identical) type of the template- argument. The
2579 // template-parameter is bound directly to the
2580 // template-argument, which shall be an lvalue.
2581
2582 // FIXME: Other qualifiers?
2583 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2584 unsigned ArgQuals = ArgType.getCVRQualifiers();
2585
2586 if ((ParamQuals | ArgQuals) != ParamQuals) {
2587 S.Diag(Arg->getSourceRange().getBegin(),
2588 diag::err_template_arg_ref_bind_ignores_quals)
2589 << ParamType << Arg->getType()
2590 << Arg->getSourceRange();
2591 S.Diag(Param->getLocation(), diag::note_template_param_here);
2592 return true;
2593 }
2594 }
2595 }
2596
2597 // At this point, the template argument refers to an object or
2598 // function with external linkage. We now need to check whether the
2599 // argument and parameter types are compatible.
2600 if (!S.Context.hasSameUnqualifiedType(ArgType,
2601 ParamType.getNonReferenceType())) {
2602 // We can't perform this conversion or binding.
2603 if (ParamType->isReferenceType())
2604 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2605 << ParamType << Arg->getType() << Arg->getSourceRange();
2606 else
2607 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2608 << Arg->getType() << ParamType << Arg->getSourceRange();
2609 S.Diag(Param->getLocation(), diag::note_template_param_here);
2610 return true;
2611 }
2612 }
2613
2614 // Create the template argument.
2615 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002616 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002617 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002618}
2619
2620/// \brief Checks whether the given template argument is a pointer to
2621/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002622bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2623 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002624 bool Invalid = false;
2625
2626 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002627 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002628 Arg = Cast->getSubExpr();
2629
2630 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002631 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002632 // A template-argument for a non-type, non-template
2633 // template-parameter shall be one of: [...]
2634 //
2635 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002636 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002637
2638 // Ignore (and complain about) any excess parentheses.
2639 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2640 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002641 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002642 diag::err_template_arg_extra_parens)
2643 << Arg->getSourceRange();
2644 Invalid = true;
2645 }
2646
2647 Arg = Parens->getSubExpr();
2648 }
2649
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002650 // A pointer-to-member constant written &Class::member.
2651 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002652 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2653 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2654 if (DRE && !DRE->getQualifier())
2655 DRE = 0;
2656 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002657 }
2658 // A constant of pointer-to-member type.
2659 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2660 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2661 if (VD->getType()->isMemberPointerType()) {
2662 if (isa<NonTypeTemplateParmDecl>(VD) ||
2663 (isa<VarDecl>(VD) &&
2664 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2665 if (Arg->isTypeDependent() || Arg->isValueDependent())
2666 Converted = TemplateArgument(Arg->Retain());
2667 else
2668 Converted = TemplateArgument(VD->getCanonicalDecl());
2669 return Invalid;
2670 }
2671 }
2672 }
2673
2674 DRE = 0;
2675 }
2676
Douglas Gregorccb07762009-02-11 19:52:55 +00002677 if (!DRE)
2678 return Diag(Arg->getSourceRange().getBegin(),
2679 diag::err_template_arg_not_pointer_to_member_form)
2680 << Arg->getSourceRange();
2681
2682 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2683 assert((isa<FieldDecl>(DRE->getDecl()) ||
2684 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2685 "Only non-static member pointers can make it here");
2686
2687 // Okay: this is the address of a non-static member, and therefore
2688 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002689 if (Arg->isTypeDependent() || Arg->isValueDependent())
2690 Converted = TemplateArgument(Arg->Retain());
2691 else
2692 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002693 return Invalid;
2694 }
2695
2696 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002697 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002698 diag::err_template_arg_not_pointer_to_member_form)
2699 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002700 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002701 diag::note_template_arg_refers_here);
2702 return true;
2703}
2704
Douglas Gregord32e0282009-02-09 23:23:08 +00002705/// \brief Check a template argument against its corresponding
2706/// non-type template parameter.
2707///
Douglas Gregor463421d2009-03-03 04:44:36 +00002708/// This routine implements the semantics of C++ [temp.arg.nontype].
2709/// It returns true if an error occurred, and false otherwise. \p
2710/// InstantiatedParamType is the type of the non-type template
2711/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002712///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002713/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002714bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002715 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002716 TemplateArgument &Converted,
2717 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002718 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2719
Douglas Gregor86560402009-02-10 23:36:10 +00002720 // If either the parameter has a dependent type or the argument is
2721 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002722 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2723 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002724 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002725 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002726 }
Douglas Gregor86560402009-02-10 23:36:10 +00002727
2728 // C++ [temp.arg.nontype]p5:
2729 // The following conversions are performed on each expression used
2730 // as a non-type template-argument. If a non-type
2731 // template-argument cannot be converted to the type of the
2732 // corresponding template-parameter then the program is
2733 // ill-formed.
2734 //
2735 // -- for a non-type template-parameter of integral or
2736 // enumeration type, integral promotions (4.5) and integral
2737 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002738 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002739 QualType ArgType = Arg->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +00002740 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002741 // C++ [temp.arg.nontype]p1:
2742 // A template-argument for a non-type, non-template
2743 // template-parameter shall be one of:
2744 //
2745 // -- an integral constant-expression of integral or enumeration
2746 // type; or
2747 // -- the name of a non-type template-parameter; or
2748 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002749 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00002750 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002751 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002752 diag::err_template_arg_not_integral_or_enumeral)
2753 << ArgType << Arg->getSourceRange();
2754 Diag(Param->getLocation(), diag::note_template_param_here);
2755 return true;
2756 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002757 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002758 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2759 << ArgType << Arg->getSourceRange();
2760 return true;
2761 }
2762
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002763 // From here on out, all we care about are the unqualified forms
2764 // of the parameter and argument types.
2765 ParamType = ParamType.getUnqualifiedType();
2766 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00002767
2768 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002769 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002770 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002771 } else if (CTAK == CTAK_Deduced) {
2772 // C++ [temp.deduct.type]p17:
2773 // If, in the declaration of a function template with a non-type
2774 // template-parameter, the non-type template- parameter is used
2775 // in an expression in the function parameter-list and, if the
2776 // corresponding template-argument is deduced, the
2777 // template-argument type shall match the type of the
2778 // template-parameter exactly, except that a template-argument
2779 // deduced from an array bound may be of any integral type.
2780 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2781 << ArgType << ParamType;
2782 Diag(Param->getLocation(), diag::note_template_param_here);
2783 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00002784 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2785 !ParamType->isEnumeralType()) {
2786 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002787 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002788 } else {
2789 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002790 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002791 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002792 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002793 Diag(Param->getLocation(), diag::note_template_param_here);
2794 return true;
2795 }
2796
Douglas Gregor52aba872009-03-14 00:20:21 +00002797 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002798 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002799 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002800
2801 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002802 llvm::APSInt OldValue = Value;
2803
2804 // Coerce the template argument's value to the value it will have
2805 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002806 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002807 if (Value.getBitWidth() != AllowedBits)
2808 Value.extOrTrunc(AllowedBits);
2809 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002810
2811 // Complain if an unsigned parameter received a negative value.
2812 if (IntegerType->isUnsignedIntegerType()
2813 && (OldValue.isSigned() && OldValue.isNegative())) {
2814 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2815 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2816 << Arg->getSourceRange();
2817 Diag(Param->getLocation(), diag::note_template_param_here);
2818 }
2819
2820 // Complain if we overflowed the template parameter's type.
2821 unsigned RequiredBits;
2822 if (IntegerType->isUnsignedIntegerType())
2823 RequiredBits = OldValue.getActiveBits();
2824 else if (OldValue.isUnsigned())
2825 RequiredBits = OldValue.getActiveBits() + 1;
2826 else
2827 RequiredBits = OldValue.getMinSignedBits();
2828 if (RequiredBits > AllowedBits) {
2829 Diag(Arg->getSourceRange().getBegin(),
2830 diag::warn_template_arg_too_large)
2831 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2832 << Arg->getSourceRange();
2833 Diag(Param->getLocation(), diag::note_template_param_here);
2834 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002835 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002836
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002837 // Add the value of this argument to the list of converted
2838 // arguments. We use the bitwidth and signedness of the template
2839 // parameter.
2840 if (Arg->isValueDependent()) {
2841 // The argument is value-dependent. Create a new
2842 // TemplateArgument with the converted expression.
2843 Converted = TemplateArgument(Arg);
2844 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002845 }
2846
John McCall0ad16662009-10-29 08:12:44 +00002847 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002848 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002849 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002850 return false;
2851 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002852
John McCall16df1e52010-03-30 21:47:33 +00002853 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2854
Douglas Gregorb242683d2010-04-01 18:32:35 +00002855 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2856 // from a template argument of type std::nullptr_t to a non-type
2857 // template parameter of type pointer to object, pointer to
2858 // function, or pointer-to-member, respectively.
2859 if (ArgType->isNullPtrType() &&
2860 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2861 Converted = TemplateArgument((NamedDecl *)0);
2862 return false;
2863 }
2864
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002865 // Handle pointer-to-function, reference-to-function, and
2866 // pointer-to-member-function all in (roughly) the same way.
2867 if (// -- For a non-type template-parameter of type pointer to
2868 // function, only the function-to-pointer conversion (4.3) is
2869 // applied. If the template-argument represents a set of
2870 // overloaded functions (or a pointer to such), the matching
2871 // function is selected from the set (13.4).
2872 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002873 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002874 // -- For a non-type template-parameter of type reference to
2875 // function, no conversions apply. If the template-argument
2876 // represents a set of overloaded functions, the matching
2877 // function is selected from the set (13.4).
2878 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002879 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002880 // -- For a non-type template-parameter of type pointer to
2881 // member function, no conversions apply. If the
2882 // template-argument represents a set of overloaded member
2883 // functions, the matching member function is selected from
2884 // the set (13.4).
2885 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002886 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002887 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002888
Douglas Gregor064fdb22010-04-14 23:11:21 +00002889 if (Arg->getType() == Context.OverloadTy) {
2890 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2891 true,
2892 FoundResult)) {
2893 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2894 return true;
2895
2896 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2897 ArgType = Arg->getType();
2898 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00002899 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002900 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002901
Douglas Gregorb242683d2010-04-01 18:32:35 +00002902 if (!ParamType->isMemberPointerType())
2903 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2904 ParamType,
2905 Arg, Converted);
2906
2907 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002908 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp, CastCategory(Arg));
Douglas Gregorb242683d2010-04-01 18:32:35 +00002909 } else if (!Context.hasSameUnqualifiedType(ArgType,
2910 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002911 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002912 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002913 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002914 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002915 Diag(Param->getLocation(), diag::note_template_param_here);
2916 return true;
2917 }
Mike Stump11289f42009-09-09 15:08:12 +00002918
Douglas Gregorb242683d2010-04-01 18:32:35 +00002919 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002920 }
2921
Chris Lattner696197c2009-02-20 21:37:53 +00002922 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002923 // -- for a non-type template-parameter of type pointer to
2924 // object, qualification conversions (4.4) and the
2925 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002926 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00002927 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002928 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002929
Douglas Gregorb242683d2010-04-01 18:32:35 +00002930 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2931 ParamType,
2932 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00002933 }
Mike Stump11289f42009-09-09 15:08:12 +00002934
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002935 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002936 // -- For a non-type template-parameter of type reference to
2937 // object, no conversions apply. The type referred to by the
2938 // reference may be more cv-qualified than the (otherwise
2939 // identical) type of the template-argument. The
2940 // template-parameter is bound directly to the
2941 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00002942 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002943 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002944
Douglas Gregor064fdb22010-04-14 23:11:21 +00002945 if (Arg->getType() == Context.OverloadTy) {
2946 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2947 ParamRefType->getPointeeType(),
2948 true,
2949 FoundResult)) {
2950 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2951 return true;
2952
2953 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2954 ArgType = Arg->getType();
2955 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00002956 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002957 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002958
Douglas Gregorb242683d2010-04-01 18:32:35 +00002959 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2960 ParamType,
2961 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002962 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002963
2964 // -- For a non-type template-parameter of type pointer to data
2965 // member, qualification conversions (4.4) are applied.
2966 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2967
Douglas Gregor1515f762009-02-11 18:22:40 +00002968 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002969 // Types match exactly: nothing more to do here.
2970 } else if (IsQualificationConversion(ArgType, ParamType)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002971 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp, CastCategory(Arg));
Douglas Gregor0e558532009-02-11 16:16:59 +00002972 } else {
2973 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002974 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002975 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002976 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002977 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002978 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002979 }
2980
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002981 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002982}
2983
2984/// \brief Check a template argument against its corresponding
2985/// template template parameter.
2986///
2987/// This routine implements the semantics of C++ [temp.arg.template].
2988/// It returns true if an error occurred, and false otherwise.
2989bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002990 const TemplateArgumentLoc &Arg) {
2991 TemplateName Name = Arg.getArgument().getAsTemplate();
2992 TemplateDecl *Template = Name.getAsTemplateDecl();
2993 if (!Template) {
2994 // Any dependent template name is fine.
2995 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2996 return false;
2997 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002998
2999 // C++ [temp.arg.template]p1:
3000 // A template-argument for a template template-parameter shall be
3001 // the name of a class template, expressed as id-expression. Only
3002 // primary class templates are considered when matching the
3003 // template template argument with the corresponding parameter;
3004 // partial specializations are not considered even if their
3005 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003006 //
3007 // Note that we also allow template template parameters here, which
3008 // will happen when we are dealing with, e.g., class template
3009 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003010 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003011 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003012 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003013 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003014 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003015 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003016 << Template;
3017 }
3018
3019 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3020 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003021 true,
3022 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003023 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003024}
3025
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003026/// \brief Given a non-type template argument that refers to a
3027/// declaration and the type of its corresponding non-type template
3028/// parameter, produce an expression that properly refers to that
3029/// declaration.
3030Sema::OwningExprResult
3031Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3032 QualType ParamType,
3033 SourceLocation Loc) {
3034 assert(Arg.getKind() == TemplateArgument::Declaration &&
3035 "Only declaration template arguments permitted here");
3036 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3037
3038 if (VD->getDeclContext()->isRecord() &&
3039 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3040 // If the value is a class member, we might have a pointer-to-member.
3041 // Determine whether the non-type template template parameter is of
3042 // pointer-to-member type. If so, we need to build an appropriate
3043 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3044 // would refer to the member itself.
3045 if (ParamType->isMemberPointerType()) {
3046 QualType ClassType
3047 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3048 NestedNameSpecifier *Qualifier
3049 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
3050 CXXScopeSpec SS;
3051 SS.setScopeRep(Qualifier);
3052 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
3053 VD->getType().getNonReferenceType(),
3054 Loc,
3055 &SS);
3056 if (RefExpr.isInvalid())
3057 return ExprError();
3058
3059 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003060
3061 // We might need to perform a trailing qualification conversion, since
3062 // the element type on the parameter could be more qualified than the
3063 // element type in the expression we constructed.
3064 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3065 ParamType.getUnqualifiedType())) {
3066 Expr *RefE = RefExpr.takeAs<Expr>();
3067 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(),
3068 CastExpr::CK_NoOp);
3069 RefExpr = Owned(RefE);
3070 }
3071
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003072 assert(!RefExpr.isInvalid() &&
3073 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003074 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003075 return move(RefExpr);
3076 }
3077 }
3078
3079 QualType T = VD->getType().getNonReferenceType();
3080 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003081 // When the non-type template parameter is a pointer, take the
3082 // address of the declaration.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003083 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3084 if (RefExpr.isInvalid())
3085 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003086
3087 if (T->isFunctionType() || T->isArrayType()) {
3088 // Decay functions and arrays.
3089 Expr *RefE = (Expr *)RefExpr.get();
3090 DefaultFunctionArrayConversion(RefE);
3091 if (RefE != RefExpr.get()) {
3092 RefExpr.release();
3093 RefExpr = Owned(RefE);
3094 }
3095
3096 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003097 }
3098
Douglas Gregorb242683d2010-04-01 18:32:35 +00003099 // Take the address of everything else
3100 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003101 }
3102
3103 // If the non-type template parameter has reference type, qualify the
3104 // resulting declaration reference with the extra qualifiers on the
3105 // type that the reference refers to.
3106 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3107 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3108
3109 return BuildDeclRefExpr(VD, T, Loc);
3110}
3111
3112/// \brief Construct a new expression that refers to the given
3113/// integral template argument with the given source-location
3114/// information.
3115///
3116/// This routine takes care of the mapping from an integral template
3117/// argument (which may have any integral type) to the appropriate
3118/// literal value.
3119Sema::OwningExprResult
3120Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3121 SourceLocation Loc) {
3122 assert(Arg.getKind() == TemplateArgument::Integral &&
3123 "Operation is only value for integral template arguments");
3124 QualType T = Arg.getIntegralType();
3125 if (T->isCharType() || T->isWideCharType())
3126 return Owned(new (Context) CharacterLiteral(
3127 Arg.getAsIntegral()->getZExtValue(),
3128 T->isWideCharType(),
3129 T,
3130 Loc));
3131 if (T->isBooleanType())
3132 return Owned(new (Context) CXXBoolLiteralExpr(
3133 Arg.getAsIntegral()->getBoolValue(),
3134 T,
3135 Loc));
3136
3137 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3138}
3139
3140
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003141/// \brief Determine whether the given template parameter lists are
3142/// equivalent.
3143///
Mike Stump11289f42009-09-09 15:08:12 +00003144/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003145/// source code as part of a new template declaration.
3146///
3147/// \param Old The old template parameter list, typically found via
3148/// name lookup of the template declared with this template parameter
3149/// list.
3150///
3151/// \param Complain If true, this routine will produce a diagnostic if
3152/// the template parameter lists are not equivalent.
3153///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003154/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003155///
3156/// \param TemplateArgLoc If this source location is valid, then we
3157/// are actually checking the template parameter list of a template
3158/// argument (New) against the template parameter list of its
3159/// corresponding template template parameter (Old). We produce
3160/// slightly different diagnostics in this scenario.
3161///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003162/// \returns True if the template parameter lists are equal, false
3163/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003164bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003165Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3166 TemplateParameterList *Old,
3167 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003168 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003169 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003170 if (Old->size() != New->size()) {
3171 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003172 unsigned NextDiag = diag::err_template_param_list_different_arity;
3173 if (TemplateArgLoc.isValid()) {
3174 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3175 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003176 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003177 Diag(New->getTemplateLoc(), NextDiag)
3178 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003179 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003180 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003181 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003182 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003183 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3184 }
3185
3186 return false;
3187 }
3188
3189 for (TemplateParameterList::iterator OldParm = Old->begin(),
3190 OldParmEnd = Old->end(), NewParm = New->begin();
3191 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3192 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003193 if (Complain) {
3194 unsigned NextDiag = diag::err_template_param_different_kind;
3195 if (TemplateArgLoc.isValid()) {
3196 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3197 NextDiag = diag::note_template_param_different_kind;
3198 }
3199 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003200 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003201 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003202 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003203 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003204 return false;
3205 }
3206
Douglas Gregor2e87ca22010-06-04 08:34:32 +00003207 if (TemplateTypeParmDecl *OldTTP
3208 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3209 // Template type parameters are equivalent if either both are template
3210 // type parameter packs or neither are (since we know we're at the same
3211 // index).
3212 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3213 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3214 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3215 // allow one to match a template parameter pack in the template
3216 // parameter list of a template template parameter to one or more
3217 // template parameters in the template parameter list of the
3218 // corresponding template template argument.
3219 if (Complain) {
3220 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3221 if (TemplateArgLoc.isValid()) {
3222 Diag(TemplateArgLoc,
3223 diag::err_template_arg_template_params_mismatch);
3224 NextDiag = diag::note_template_parameter_pack_non_pack;
3225 }
3226 Diag(NewTTP->getLocation(), NextDiag)
3227 << 0 << NewTTP->isParameterPack();
3228 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3229 << 0 << OldTTP->isParameterPack();
3230 }
3231 return false;
3232 }
Mike Stump11289f42009-09-09 15:08:12 +00003233 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003234 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3235 // The types of non-type template parameters must agree.
3236 NonTypeTemplateParmDecl *NewNTTP
3237 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003238
3239 // If we are matching a template template argument to a template
3240 // template parameter and one of the non-type template parameter types
3241 // is dependent, then we must wait until template instantiation time
3242 // to actually compare the arguments.
3243 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3244 (OldNTTP->getType()->isDependentType() ||
3245 NewNTTP->getType()->isDependentType()))
3246 continue;
3247
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003248 if (Context.getCanonicalType(OldNTTP->getType()) !=
3249 Context.getCanonicalType(NewNTTP->getType())) {
3250 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003251 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3252 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003253 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003254 diag::err_template_arg_template_params_mismatch);
3255 NextDiag = diag::note_template_nontype_parm_different_type;
3256 }
3257 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003258 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003259 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003260 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003261 diag::note_template_nontype_parm_prev_declaration)
3262 << OldNTTP->getType();
3263 }
3264 return false;
3265 }
3266 } else {
3267 // The template parameter lists of template template
3268 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003269 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003270 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003271 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003272 = cast<TemplateTemplateParmDecl>(*OldParm);
3273 TemplateTemplateParmDecl *NewTTP
3274 = cast<TemplateTemplateParmDecl>(*NewParm);
3275 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3276 OldTTP->getTemplateParameters(),
3277 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003278 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003279 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003280 return false;
3281 }
3282 }
3283
3284 return true;
3285}
3286
3287/// \brief Check whether a template can be declared within this scope.
3288///
3289/// If the template declaration is valid in this scope, returns
3290/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003291bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003292Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003293 // Find the nearest enclosing declaration scope.
3294 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3295 (S->getFlags() & Scope::TemplateParamScope) != 0)
3296 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003297
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003298 // C++ [temp]p2:
3299 // A template-declaration can appear only as a namespace scope or
3300 // class scope declaration.
3301 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003302 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3303 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003304 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003305 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003306
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003307 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003308 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003309
3310 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3311 return false;
3312
Mike Stump11289f42009-09-09 15:08:12 +00003313 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003314 diag::err_template_outside_namespace_or_class_scope)
3315 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003316}
Douglas Gregor67a65642009-02-17 23:15:12 +00003317
Douglas Gregor54888652009-10-07 00:13:32 +00003318/// \brief Determine what kind of template specialization the given declaration
3319/// is.
3320static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3321 if (!D)
3322 return TSK_Undeclared;
3323
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003324 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3325 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003326 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3327 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003328 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3329 return Var->getTemplateSpecializationKind();
3330
Douglas Gregor54888652009-10-07 00:13:32 +00003331 return TSK_Undeclared;
3332}
3333
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003334/// \brief Check whether a specialization is well-formed in the current
3335/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003336///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003337/// This routine determines whether a template specialization can be declared
3338/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003339///
3340/// \param S the semantic analysis object for which this check is being
3341/// performed.
3342///
3343/// \param Specialized the entity being specialized or instantiated, which
3344/// may be a kind of template (class template, function template, etc.) or
3345/// a member of a class template (member function, static data member,
3346/// member class).
3347///
3348/// \param PrevDecl the previous declaration of this entity, if any.
3349///
3350/// \param Loc the location of the explicit specialization or instantiation of
3351/// this entity.
3352///
3353/// \param IsPartialSpecialization whether this is a partial specialization of
3354/// a class template.
3355///
Douglas Gregor54888652009-10-07 00:13:32 +00003356/// \returns true if there was an error that we cannot recover from, false
3357/// otherwise.
3358static bool CheckTemplateSpecializationScope(Sema &S,
3359 NamedDecl *Specialized,
3360 NamedDecl *PrevDecl,
3361 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003362 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003363 // Keep these "kind" numbers in sync with the %select statements in the
3364 // various diagnostics emitted by this routine.
3365 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003366 bool isTemplateSpecialization = false;
3367 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003368 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003369 isTemplateSpecialization = true;
3370 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003371 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003372 isTemplateSpecialization = true;
3373 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003374 EntityKind = 3;
3375 else if (isa<VarDecl>(Specialized))
3376 EntityKind = 4;
3377 else if (isa<RecordDecl>(Specialized))
3378 EntityKind = 5;
3379 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003380 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3381 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003382 return true;
3383 }
3384
Douglas Gregorf47b9112009-02-25 22:02:03 +00003385 // C++ [temp.expl.spec]p2:
3386 // An explicit specialization shall be declared in the namespace
3387 // of which the template is a member, or, for member templates, in
3388 // the namespace of which the enclosing class or enclosing class
3389 // template is a member. An explicit specialization of a member
3390 // function, member class or static data member of a class
3391 // template shall be declared in the namespace of which the class
3392 // template is a member. Such a declaration may also be a
3393 // definition. If the declaration is not a definition, the
3394 // specialization may be defined later in the name- space in which
3395 // the explicit specialization was declared, or in a namespace
3396 // that encloses the one in which the explicit specialization was
3397 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003398 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3399 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003400 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003401 return true;
3402 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003403
Douglas Gregor40fb7442009-10-07 17:30:37 +00003404 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3405 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003406 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003407 return true;
3408 }
3409
Douglas Gregore4b05162009-10-07 17:21:34 +00003410 // C++ [temp.class.spec]p6:
3411 // A class template partial specialization may be declared or redeclared
3412 // in any namespace scope in which its definition may be defined (14.5.1
3413 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003414 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003415 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003416 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003417 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003418 if ((!PrevDecl ||
3419 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3420 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3421 // There is no prior declaration of this entity, so this
3422 // specialization must be in the same context as the template
3423 // itself.
3424 if (!DC->Equals(SpecializedContext)) {
3425 if (isa<TranslationUnitDecl>(SpecializedContext))
3426 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3427 << EntityKind << Specialized;
3428 else if (isa<NamespaceDecl>(SpecializedContext))
3429 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3430 << EntityKind << Specialized
3431 << cast<NamedDecl>(SpecializedContext);
3432
3433 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3434 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003435 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003436 }
Douglas Gregor54888652009-10-07 00:13:32 +00003437
3438 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003439 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003440 // Note that HandleDeclarator() performs this check for explicit
3441 // specializations of function templates, static data members, and member
3442 // functions, so we skip the check here for those kinds of entities.
3443 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003444 // Should we refactor that check, so that it occurs later?
3445 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003446 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3447 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003448 if (isa<TranslationUnitDecl>(SpecializedContext))
3449 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3450 << EntityKind << Specialized;
3451 else if (isa<NamespaceDecl>(SpecializedContext))
3452 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3453 << EntityKind << Specialized
3454 << cast<NamedDecl>(SpecializedContext);
3455
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003456 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003457 }
Douglas Gregor54888652009-10-07 00:13:32 +00003458
3459 // FIXME: check for specialization-after-instantiation errors and such.
3460
Douglas Gregorf47b9112009-02-25 22:02:03 +00003461 return false;
3462}
Douglas Gregor54888652009-10-07 00:13:32 +00003463
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003464/// \brief Check the non-type template arguments of a class template
3465/// partial specialization according to C++ [temp.class.spec]p9.
3466///
Douglas Gregor09a30232009-06-12 22:08:06 +00003467/// \param TemplateParams the template parameters of the primary class
3468/// template.
3469///
3470/// \param TemplateArg the template arguments of the class template
3471/// partial specialization.
3472///
3473/// \param MirrorsPrimaryTemplate will be set true if the class
3474/// template partial specialization arguments are identical to the
3475/// implicit template arguments of the primary template. This is not
3476/// necessarily an error (C++0x), and it is left to the caller to diagnose
3477/// this condition when it is an error.
3478///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003479/// \returns true if there was an error, false otherwise.
3480bool Sema::CheckClassTemplatePartialSpecializationArgs(
3481 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003482 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003483 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003484 // FIXME: the interface to this function will have to change to
3485 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003486 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003487
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003488 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003489
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003490 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003491 // Determine whether the template argument list of the partial
3492 // specialization is identical to the implicit argument list of
3493 // the primary template. The caller may need to diagnostic this as
3494 // an error per C++ [temp.class.spec]p9b3.
3495 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003496 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003497 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3498 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003499 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003500 MirrorsPrimaryTemplate = false;
3501 } else if (TemplateTemplateParmDecl *TTP
3502 = dyn_cast<TemplateTemplateParmDecl>(
3503 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003504 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003505 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003506 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003507 if (!ArgDecl ||
3508 ArgDecl->getIndex() != TTP->getIndex() ||
3509 ArgDecl->getDepth() != TTP->getDepth())
3510 MirrorsPrimaryTemplate = false;
3511 }
3512 }
3513
Mike Stump11289f42009-09-09 15:08:12 +00003514 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003515 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003516 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003517 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003518 }
3519
Anders Carlsson40c1d492009-06-13 18:20:51 +00003520 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003521 if (!ArgExpr) {
3522 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003523 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003524 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003525
3526 // C++ [temp.class.spec]p8:
3527 // A non-type argument is non-specialized if it is the name of a
3528 // non-type parameter. All other non-type arguments are
3529 // specialized.
3530 //
3531 // Below, we check the two conditions that only apply to
3532 // specialized non-type arguments, so skip any non-specialized
3533 // arguments.
3534 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003535 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003536 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003537 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003538 (Param->getIndex() != NTTP->getIndex() ||
3539 Param->getDepth() != NTTP->getDepth()))
3540 MirrorsPrimaryTemplate = false;
3541
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003542 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003543 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003544
3545 // C++ [temp.class.spec]p9:
3546 // Within the argument list of a class template partial
3547 // specialization, the following restrictions apply:
3548 // -- A partially specialized non-type argument expression
3549 // shall not involve a template parameter of the partial
3550 // specialization except when the argument expression is a
3551 // simple identifier.
3552 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003553 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003554 diag::err_dependent_non_type_arg_in_partial_spec)
3555 << ArgExpr->getSourceRange();
3556 return true;
3557 }
3558
3559 // -- The type of a template parameter corresponding to a
3560 // specialized non-type argument shall not be dependent on a
3561 // parameter of the specialization.
3562 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003563 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003564 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3565 << Param->getType()
3566 << ArgExpr->getSourceRange();
3567 Diag(Param->getLocation(), diag::note_template_param_here);
3568 return true;
3569 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003570
3571 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003572 }
3573
3574 return false;
3575}
3576
Douglas Gregorc854c662010-02-26 06:03:23 +00003577/// \brief Retrieve the previous declaration of the given declaration.
3578static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3579 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3580 return VD->getPreviousDeclaration();
3581 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3582 return FD->getPreviousDeclaration();
3583 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3584 return TD->getPreviousDeclaration();
3585 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3586 return TD->getPreviousDeclaration();
3587 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3588 return FTD->getPreviousDeclaration();
3589 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3590 return CTD->getPreviousDeclaration();
3591 return 0;
3592}
3593
Douglas Gregorc08f4892009-03-25 00:13:59 +00003594Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003595Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3596 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003597 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003598 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003599 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003600 SourceLocation TemplateNameLoc,
3601 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003602 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003603 SourceLocation RAngleLoc,
3604 AttributeList *Attr,
3605 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003606 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003607
Douglas Gregor67a65642009-02-17 23:15:12 +00003608 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003609 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003610 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003611 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3612
3613 if (!ClassTemplate) {
3614 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3615 << (Name.getAsTemplateDecl() &&
3616 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3617 return true;
3618 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003619
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003620 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003621 bool isPartialSpecialization = false;
3622
Douglas Gregorf47b9112009-02-25 22:02:03 +00003623 // Check the validity of the template headers that introduce this
3624 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003625 // FIXME: We probably shouldn't complain about these headers for
3626 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003627 bool Invalid = false;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003628 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003629 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3630 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003631 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003632 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003633 isExplicitSpecialization,
3634 Invalid);
3635 if (Invalid)
3636 return true;
3637
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003638 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3639 if (TemplateParams)
3640 --NumMatchedTemplateParamLists;
3641
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003642 if (TemplateParams && TemplateParams->size() > 0) {
3643 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003644
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003645 // C++ [temp.class.spec]p10:
3646 // The template parameter list of a specialization shall not
3647 // contain default template argument values.
3648 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3649 Decl *Param = TemplateParams->getParam(I);
3650 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3651 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003652 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003653 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003654 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003655 }
3656 } else if (NonTypeTemplateParmDecl *NTTP
3657 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3658 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003659 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003660 diag::err_default_arg_in_partial_spec)
3661 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003662 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003663 }
3664 } else {
3665 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003666 if (TTP->hasDefaultArgument()) {
3667 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003668 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003669 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003670 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00003671 }
3672 }
3673 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003674 } else if (TemplateParams) {
3675 if (TUK == TUK_Friend)
3676 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003677 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003678 SourceRange(TemplateParams->getTemplateLoc(),
3679 TemplateParams->getRAngleLoc()))
3680 << SourceRange(LAngleLoc, RAngleLoc);
3681 else
3682 isExplicitSpecialization = true;
3683 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003684 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003685 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003686 isExplicitSpecialization = true;
3687 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003688
Douglas Gregor67a65642009-02-17 23:15:12 +00003689 // Check that the specialization uses the same tag kind as the
3690 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003691 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3692 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00003693 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003694 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003695 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003696 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003697 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003698 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003699 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003700 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003701 diag::note_previous_use);
3702 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3703 }
3704
Douglas Gregorc40290e2009-03-09 23:48:35 +00003705 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003706 TemplateArgumentListInfo TemplateArgs;
3707 TemplateArgs.setLAngleLoc(LAngleLoc);
3708 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003709 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003710
Douglas Gregor67a65642009-02-17 23:15:12 +00003711 // Check that the template argument list is well-formed for this
3712 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003713 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3714 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003715 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3716 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003717 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003718
Mike Stump11289f42009-09-09 15:08:12 +00003719 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003720 ClassTemplate->getTemplateParameters()->size()) &&
3721 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003722
Douglas Gregor2373c592009-05-31 09:31:02 +00003723 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003724 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00003725 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003726 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003727 if (CheckClassTemplatePartialSpecializationArgs(
3728 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003729 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003730 return true;
3731
Douglas Gregor09a30232009-06-12 22:08:06 +00003732 if (MirrorsPrimaryTemplate) {
3733 // C++ [temp.class.spec]p9b3:
3734 //
Mike Stump11289f42009-09-09 15:08:12 +00003735 // -- The argument list of the specialization shall not be identical
3736 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003737 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003738 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003739 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003740 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003741 ClassTemplate->getIdentifier(),
3742 TemplateNameLoc,
3743 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003744 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003745 AS_none);
3746 }
3747
Douglas Gregor2208a292009-09-26 20:57:03 +00003748 // FIXME: Diagnose friend partial specializations
3749
Douglas Gregor92354b62010-02-09 00:37:32 +00003750 if (!Name.isDependent() &&
3751 !TemplateSpecializationType::anyDependentTemplateArguments(
3752 TemplateArgs.getArgumentArray(),
3753 TemplateArgs.size())) {
3754 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3755 << ClassTemplate->getDeclName();
3756 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00003757 }
3758 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003759
Douglas Gregor67a65642009-02-17 23:15:12 +00003760 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003761 ClassTemplateSpecializationDecl *PrevDecl = 0;
3762
3763 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003764 // FIXME: Template parameter list matters, too
Douglas Gregor2373c592009-05-31 09:31:02 +00003765 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003766 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
3767 Converted.flatSize(),
3768 InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00003769 else
3770 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003771 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
3772 Converted.flatSize(), InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003773
3774 ClassTemplateSpecializationDecl *Specialization = 0;
3775
Douglas Gregorf47b9112009-02-25 22:02:03 +00003776 // Check whether we can declare a class template specialization in
3777 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003778 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003779 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003780 TemplateNameLoc,
3781 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003782 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003783
Douglas Gregor15301382009-07-30 17:40:51 +00003784 // The canonical type
3785 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003786 if (PrevDecl &&
3787 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003788 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003789 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003790 // arguments was referenced but not declared, or we're only
3791 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003792 // declaration node as our own, updating its source location to
3793 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003794 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003795 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003796 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003797 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003798 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003799 // Build the canonical type that describes the converted template
3800 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003801 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3802 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003803 Converted.getFlatArguments(),
3804 Converted.flatSize());
3805
Douglas Gregor2373c592009-05-31 09:31:02 +00003806 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003807 ClassTemplatePartialSpecializationDecl *PrevPartial
3808 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00003809 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003810 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump11289f42009-09-09 15:08:12 +00003811 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00003812 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00003813 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003814 TemplateNameLoc,
3815 TemplateParams,
3816 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003817 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003818 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003819 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00003820 PrevPartial,
3821 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00003822 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00003823 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003824 Partial->setTemplateParameterListsInfo(Context,
3825 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003826 (TemplateParameterList**) TemplateParameterLists.release());
3827 }
Douglas Gregor2373c592009-05-31 09:31:02 +00003828
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003829 if (!PrevPartial)
3830 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00003831 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003832
Douglas Gregor21610382009-10-29 00:04:11 +00003833 // If we are providing an explicit specialization of a member class
3834 // template specialization, make a note of that.
3835 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3836 PrevPartial->setMemberSpecialization();
3837
Douglas Gregor91772d12009-06-13 00:26:55 +00003838 // Check that all of the template parameters of the class template
3839 // partial specialization are deducible from the template
3840 // arguments. If not, this class template partial specialization
3841 // will never be used.
3842 llvm::SmallVector<bool, 8> DeducibleParams;
3843 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003844 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003845 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003846 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003847 unsigned NumNonDeducible = 0;
3848 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3849 if (!DeducibleParams[I])
3850 ++NumNonDeducible;
3851
3852 if (NumNonDeducible) {
3853 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3854 << (NumNonDeducible > 1)
3855 << SourceRange(TemplateNameLoc, RAngleLoc);
3856 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3857 if (!DeducibleParams[I]) {
3858 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3859 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003860 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003861 diag::note_partial_spec_unused_parameter)
3862 << Param->getDeclName();
3863 else
Mike Stump11289f42009-09-09 15:08:12 +00003864 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003865 diag::note_partial_spec_unused_parameter)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003866 << "<anonymous>";
Douglas Gregor91772d12009-06-13 00:26:55 +00003867 }
3868 }
3869 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003870 } else {
3871 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003872 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003873 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00003874 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00003875 ClassTemplate->getDeclContext(),
3876 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003877 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003878 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003879 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00003880 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00003881 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003882 Specialization->setTemplateParameterListsInfo(Context,
3883 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003884 (TemplateParameterList**) TemplateParameterLists.release());
3885 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003886
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003887 if (!PrevDecl)
3888 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00003889
3890 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003891 }
3892
Douglas Gregor06db9f52009-10-12 20:18:28 +00003893 // C++ [temp.expl.spec]p6:
3894 // If a template, a member template or the member of a class template is
3895 // explicitly specialized then that specialization shall be declared
3896 // before the first use of that specialization that would cause an implicit
3897 // instantiation to take place, in every translation unit in which such a
3898 // use occurs; no diagnostic is required.
3899 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003900 bool Okay = false;
3901 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3902 // Is there any previous explicit specialization declaration?
3903 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3904 Okay = true;
3905 break;
3906 }
3907 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003908
Douglas Gregorc854c662010-02-26 06:03:23 +00003909 if (!Okay) {
3910 SourceRange Range(TemplateNameLoc, RAngleLoc);
3911 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3912 << Context.getTypeDeclType(Specialization) << Range;
3913
3914 Diag(PrevDecl->getPointOfInstantiation(),
3915 diag::note_instantiation_required_here)
3916 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003917 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003918 return true;
3919 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003920 }
3921
Douglas Gregor2208a292009-09-26 20:57:03 +00003922 // If this is not a friend, note that this is an explicit specialization.
3923 if (TUK != TUK_Friend)
3924 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003925
3926 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003927 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003928 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003929 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003930 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003931 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003932 Diag(Def->getLocation(), diag::note_previous_definition);
3933 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003934 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003935 }
3936 }
3937
Douglas Gregord56a91e2009-02-26 22:19:44 +00003938 // Build the fully-sugared type for this class template
3939 // specialization as the user wrote in the specialization
3940 // itself. This means that we'll pretty-print the type retrieved
3941 // from the specialization's declaration the way that the user
3942 // actually wrote the specialization, rather than formatting the
3943 // name based on the "canonical" representation used to store the
3944 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003945 TypeSourceInfo *WrittenTy
3946 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3947 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00003948 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003949 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregord890b732010-07-06 18:33:12 +00003950 if (TemplateParams)
3951 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnara8075c852010-06-12 07:44:57 +00003952 }
Douglas Gregorc40290e2009-03-09 23:48:35 +00003953 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003954
Douglas Gregor1e249f82009-02-25 22:18:32 +00003955 // C++ [temp.expl.spec]p9:
3956 // A template explicit specialization is in the scope of the
3957 // namespace in which the template was defined.
3958 //
3959 // We actually implement this paragraph where we set the semantic
3960 // context (in the creation of the ClassTemplateSpecializationDecl),
3961 // but we also maintain the lexical context where the actual
3962 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003963 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003964
Douglas Gregor67a65642009-02-17 23:15:12 +00003965 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003966 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003967 Specialization->startDefinition();
3968
Douglas Gregor2208a292009-09-26 20:57:03 +00003969 if (TUK == TUK_Friend) {
3970 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3971 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00003972 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00003973 /*FIXME:*/KWLoc);
3974 Friend->setAccess(AS_public);
3975 CurContext->addDecl(Friend);
3976 } else {
3977 // Add the specialization into its lexical context, so that it can
3978 // be seen when iterating through the list of declarations in that
3979 // context. However, specializations are not found by name lookup.
3980 CurContext->addDecl(Specialization);
3981 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003982 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003983}
Douglas Gregor333489b2009-03-27 23:10:48 +00003984
Mike Stump11289f42009-09-09 15:08:12 +00003985Sema::DeclPtrTy
3986Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003987 MultiTemplateParamsArg TemplateParameterLists,
3988 Declarator &D) {
3989 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3990}
3991
Mike Stump11289f42009-09-09 15:08:12 +00003992Sema::DeclPtrTy
3993Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003994 MultiTemplateParamsArg TemplateParameterLists,
3995 Declarator &D) {
3996 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3997 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3998 "Not a function declarator!");
3999 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00004000
Douglas Gregor17a7c122009-06-24 00:54:41 +00004001 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004002 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004003 }
Mike Stump11289f42009-09-09 15:08:12 +00004004
Douglas Gregor17a7c122009-06-24 00:54:41 +00004005 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004006
4007 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004008 move(TemplateParameterLists),
4009 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004010 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00004011 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00004012 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004013 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00004014 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
4015 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004016 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00004017}
4018
John McCall4f7ced62010-02-11 01:33:53 +00004019/// \brief Strips various properties off an implicit instantiation
4020/// that has just been explicitly specialized.
4021static void StripImplicitInstantiation(NamedDecl *D) {
4022 D->invalidateAttrs();
4023
4024 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4025 FD->setInlineSpecified(false);
4026 }
4027}
4028
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004029/// \brief Diagnose cases where we have an explicit template specialization
4030/// before/after an explicit template instantiation, producing diagnostics
4031/// for those cases where they are required and determining whether the
4032/// new specialization/instantiation will have any effect.
4033///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004034/// \param NewLoc the location of the new explicit specialization or
4035/// instantiation.
4036///
4037/// \param NewTSK the kind of the new explicit specialization or instantiation.
4038///
4039/// \param PrevDecl the previous declaration of the entity.
4040///
4041/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4042///
4043/// \param PrevPointOfInstantiation if valid, indicates where the previus
4044/// declaration was instantiated (either implicitly or explicitly).
4045///
Abramo Bagnara8075c852010-06-12 07:44:57 +00004046/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004047/// specialization or instantiation has no effect and should be ignored.
4048///
4049/// \returns true if there was an error that should prevent the introduction of
4050/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004051bool
4052Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4053 TemplateSpecializationKind NewTSK,
4054 NamedDecl *PrevDecl,
4055 TemplateSpecializationKind PrevTSK,
4056 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004057 bool &HasNoEffect) {
4058 HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004059
4060 switch (NewTSK) {
4061 case TSK_Undeclared:
4062 case TSK_ImplicitInstantiation:
4063 assert(false && "Don't check implicit instantiations here");
4064 return false;
4065
4066 case TSK_ExplicitSpecialization:
4067 switch (PrevTSK) {
4068 case TSK_Undeclared:
4069 case TSK_ExplicitSpecialization:
4070 // Okay, we're just specializing something that is either already
4071 // explicitly specialized or has merely been mentioned without any
4072 // instantiation.
4073 return false;
4074
4075 case TSK_ImplicitInstantiation:
4076 if (PrevPointOfInstantiation.isInvalid()) {
4077 // The declaration itself has not actually been instantiated, so it is
4078 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004079 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004080 return false;
4081 }
4082 // Fall through
4083
4084 case TSK_ExplicitInstantiationDeclaration:
4085 case TSK_ExplicitInstantiationDefinition:
4086 assert((PrevTSK == TSK_ImplicitInstantiation ||
4087 PrevPointOfInstantiation.isValid()) &&
4088 "Explicit instantiation without point of instantiation?");
4089
4090 // C++ [temp.expl.spec]p6:
4091 // If a template, a member template or the member of a class template
4092 // is explicitly specialized then that specialization shall be declared
4093 // before the first use of that specialization that would cause an
4094 // implicit instantiation to take place, in every translation unit in
4095 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004096 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4097 // Is there any previous explicit specialization declaration?
4098 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4099 return false;
4100 }
4101
Douglas Gregor1d957a32009-10-27 18:42:08 +00004102 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004103 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004104 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004105 << (PrevTSK != TSK_ImplicitInstantiation);
4106
4107 return true;
4108 }
4109 break;
4110
4111 case TSK_ExplicitInstantiationDeclaration:
4112 switch (PrevTSK) {
4113 case TSK_ExplicitInstantiationDeclaration:
4114 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00004115 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004116 return false;
4117
4118 case TSK_Undeclared:
4119 case TSK_ImplicitInstantiation:
4120 // We're explicitly instantiating something that may have already been
4121 // implicitly instantiated; that's fine.
4122 return false;
4123
4124 case TSK_ExplicitSpecialization:
4125 // C++0x [temp.explicit]p4:
4126 // For a given set of template parameters, if an explicit instantiation
4127 // of a template appears after a declaration of an explicit
4128 // specialization for that template, the explicit instantiation has no
4129 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00004130 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004131 return false;
4132
4133 case TSK_ExplicitInstantiationDefinition:
4134 // C++0x [temp.explicit]p10:
4135 // If an entity is the subject of both an explicit instantiation
4136 // declaration and an explicit instantiation definition in the same
4137 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004138 Diag(NewLoc,
4139 diag::err_explicit_instantiation_declaration_after_definition);
4140 Diag(PrevPointOfInstantiation,
4141 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004142 assert(PrevPointOfInstantiation.isValid() &&
4143 "Explicit instantiation without point of instantiation?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00004144 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004145 return false;
4146 }
4147 break;
4148
4149 case TSK_ExplicitInstantiationDefinition:
4150 switch (PrevTSK) {
4151 case TSK_Undeclared:
4152 case TSK_ImplicitInstantiation:
4153 // We're explicitly instantiating something that may have already been
4154 // implicitly instantiated; that's fine.
4155 return false;
4156
4157 case TSK_ExplicitSpecialization:
4158 // C++ DR 259, C++0x [temp.explicit]p4:
4159 // For a given set of template parameters, if an explicit
4160 // instantiation of a template appears after a declaration of
4161 // an explicit specialization for that template, the explicit
4162 // instantiation has no effect.
4163 //
4164 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004165 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004166 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004167 if (!getLangOptions().CPlusPlus0x) {
4168 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004169 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004170 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004171 diag::note_previous_template_specialization);
4172 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004173 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004174 return false;
4175
4176 case TSK_ExplicitInstantiationDeclaration:
4177 // We're explicity instantiating a definition for something for which we
4178 // were previously asked to suppress instantiations. That's fine.
4179 return false;
4180
4181 case TSK_ExplicitInstantiationDefinition:
4182 // C++0x [temp.spec]p5:
4183 // For a given template and a given set of template-arguments,
4184 // - an explicit instantiation definition shall appear at most once
4185 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004186 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004187 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004188 Diag(PrevPointOfInstantiation,
4189 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004190 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004191 return false;
4192 }
4193 break;
4194 }
4195
4196 assert(false && "Missing specialization/instantiation case?");
4197
4198 return false;
4199}
4200
John McCallb9c78482010-04-08 09:05:18 +00004201/// \brief Perform semantic analysis for the given dependent function
4202/// template specialization. The only possible way to get a dependent
4203/// function template specialization is with a friend declaration,
4204/// like so:
4205///
4206/// template <class T> void foo(T);
4207/// template <class T> class A {
4208/// friend void foo<>(T);
4209/// };
4210///
4211/// There really isn't any useful analysis we can do here, so we
4212/// just store the information.
4213bool
4214Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4215 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4216 LookupResult &Previous) {
4217 // Remove anything from Previous that isn't a function template in
4218 // the correct context.
4219 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4220 LookupResult::Filter F = Previous.makeFilter();
4221 while (F.hasNext()) {
4222 NamedDecl *D = F.next()->getUnderlyingDecl();
4223 if (!isa<FunctionTemplateDecl>(D) ||
4224 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4225 F.erase();
4226 }
4227 F.done();
4228
4229 // Should this be diagnosed here?
4230 if (Previous.empty()) return true;
4231
4232 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4233 ExplicitTemplateArgs);
4234 return false;
4235}
4236
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004237/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004238/// specialization.
4239///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004240/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004241/// explicit function template specialization. On successful completion,
4242/// the function declaration \p FD will become a function template
4243/// specialization.
4244///
4245/// \param FD the function declaration, which will be updated to become a
4246/// function template specialization.
4247///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004248/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4249/// if any. Note that this may be valid info even when 0 arguments are
4250/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4251/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004252///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004253/// \param PrevDecl the set of declarations that may be specialized by
4254/// this function specialization.
4255bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004256Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004257 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004258 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004259 // The set of function template specializations that could match this
4260 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004261 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004262
4263 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00004264 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4265 I != E; ++I) {
4266 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4267 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004268 // Only consider templates found within the same semantic lookup scope as
4269 // FD.
4270 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4271 continue;
4272
4273 // C++ [temp.expl.spec]p11:
4274 // A trailing template-argument can be left unspecified in the
4275 // template-id naming an explicit function template specialization
4276 // provided it can be deduced from the function argument type.
4277 // Perform template argument deduction to determine whether we may be
4278 // specializing this template.
4279 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004280 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004281 FunctionDecl *Specialization = 0;
4282 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004283 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004284 FD->getType(),
4285 Specialization,
4286 Info)) {
4287 // FIXME: Template argument deduction failed; record why it failed, so
4288 // that we can provide nifty diagnostics.
4289 (void)TDK;
4290 continue;
4291 }
4292
4293 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004294 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004295 }
4296 }
4297
Douglas Gregor5de279c2009-09-26 03:41:46 +00004298 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004299 UnresolvedSetIterator Result
4300 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4301 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004302 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004303 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004304 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004305 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004306 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004307 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004308 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004309
4310 // Ignore access information; it doesn't figure into redeclaration checking.
4311 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004312 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004313
4314 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004315 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004316
4317 // If this is a friend declaration, then we're not really declaring
4318 // an explicit specialization.
4319 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004320
Douglas Gregor54888652009-10-07 00:13:32 +00004321 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004322 if (!isFriend &&
4323 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004324 Specialization->getPrimaryTemplate(),
4325 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004326 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004327 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004328
4329 // C++ [temp.expl.spec]p6:
4330 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004331 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004332 // before the first use of that specialization that would cause an implicit
4333 // instantiation to take place, in every translation unit in which such a
4334 // use occurs; no diagnostic is required.
4335 FunctionTemplateSpecializationInfo *SpecInfo
4336 = Specialization->getTemplateSpecializationInfo();
4337 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004338
Abramo Bagnara8075c852010-06-12 07:44:57 +00004339 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00004340 if (!isFriend &&
4341 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004342 TSK_ExplicitSpecialization,
4343 Specialization,
4344 SpecInfo->getTemplateSpecializationKind(),
4345 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004346 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004347 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004348
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004349 // Mark the prior declaration as an explicit specialization, so that later
4350 // clients know that this is an explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004351 if (!isFriend)
4352 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004353
4354 // Turn the given function declaration into a function template
4355 // specialization, with the template arguments from the previous
4356 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004357 // Take copies of (semantic and syntactic) template argument lists.
4358 const TemplateArgumentList* TemplArgs = new (Context)
4359 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4360 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4361 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004362 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004363 TemplArgs, /*InsertPos=*/0,
4364 SpecInfo->getTemplateSpecializationKind(),
4365 TemplArgsAsWritten);
4366
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004367 // The "previous declaration" for this function template specialization is
4368 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004369 Previous.clear();
4370 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004371 return false;
4372}
4373
Douglas Gregor86d142a2009-10-08 07:24:58 +00004374/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004375/// specialization.
4376///
4377/// This routine performs all of the semantic analysis required for an
4378/// explicit member function specialization. On successful completion,
4379/// the function declaration \p FD will become a member function
4380/// specialization.
4381///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004382/// \param Member the member declaration, which will be updated to become a
4383/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004384///
John McCall1f82f242009-11-18 22:49:29 +00004385/// \param Previous the set of declarations, one of which may be specialized
4386/// by this function specialization; the set will be modified to contain the
4387/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004388bool
John McCall1f82f242009-11-18 22:49:29 +00004389Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004390 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004391
Douglas Gregor86d142a2009-10-08 07:24:58 +00004392 // Try to find the member we are instantiating.
4393 NamedDecl *Instantiation = 0;
4394 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004395 MemberSpecializationInfo *MSInfo = 0;
4396
John McCall1f82f242009-11-18 22:49:29 +00004397 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004398 // Nowhere to look anyway.
4399 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004400 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4401 I != E; ++I) {
4402 NamedDecl *D = (*I)->getUnderlyingDecl();
4403 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004404 if (Context.hasSameType(Function->getType(), Method->getType())) {
4405 Instantiation = Method;
4406 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004407 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004408 break;
4409 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004410 }
4411 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004412 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004413 VarDecl *PrevVar;
4414 if (Previous.isSingleResult() &&
4415 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004416 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004417 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004418 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004419 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004420 }
4421 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004422 CXXRecordDecl *PrevRecord;
4423 if (Previous.isSingleResult() &&
4424 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4425 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004426 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004427 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004428 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004429 }
4430
4431 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004432 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004433 // specializations are always out-of-line, the caller will complain about
4434 // this mismatch later.
4435 return false;
4436 }
John McCalle820e5e2010-04-13 20:37:33 +00004437
4438 // If this is a friend, just bail out here before we start turning
4439 // things into explicit specializations.
4440 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4441 // Preserve instantiation information.
4442 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4443 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4444 cast<CXXMethodDecl>(InstantiatedFrom),
4445 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4446 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4447 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4448 cast<CXXRecordDecl>(InstantiatedFrom),
4449 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4450 }
4451
4452 Previous.clear();
4453 Previous.addDecl(Instantiation);
4454 return false;
4455 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004456
Douglas Gregor86d142a2009-10-08 07:24:58 +00004457 // Make sure that this is a specialization of a member.
4458 if (!InstantiatedFrom) {
4459 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4460 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004461 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4462 return true;
4463 }
4464
Douglas Gregor06db9f52009-10-12 20:18:28 +00004465 // C++ [temp.expl.spec]p6:
4466 // If a template, a member template or the member of a class template is
4467 // explicitly specialized then that spe- cialization shall be declared
4468 // before the first use of that specialization that would cause an implicit
4469 // instantiation to take place, in every translation unit in which such a
4470 // use occurs; no diagnostic is required.
4471 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004472
Abramo Bagnara8075c852010-06-12 07:44:57 +00004473 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00004474 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4475 TSK_ExplicitSpecialization,
4476 Instantiation,
4477 MSInfo->getTemplateSpecializationKind(),
4478 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004479 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004480 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004481
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004482 // Check the scope of this explicit specialization.
4483 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004484 InstantiatedFrom,
4485 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004486 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004487 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004488
Douglas Gregor86d142a2009-10-08 07:24:58 +00004489 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004490 // the original declaration to note that it is an explicit specialization
4491 // (if it was previously an implicit instantiation). This latter step
4492 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004493 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004494 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4495 if (InstantiationFunction->getTemplateSpecializationKind() ==
4496 TSK_ImplicitInstantiation) {
4497 InstantiationFunction->setTemplateSpecializationKind(
4498 TSK_ExplicitSpecialization);
4499 InstantiationFunction->setLocation(Member->getLocation());
4500 }
4501
Douglas Gregor86d142a2009-10-08 07:24:58 +00004502 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4503 cast<CXXMethodDecl>(InstantiatedFrom),
4504 TSK_ExplicitSpecialization);
4505 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004506 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4507 if (InstantiationVar->getTemplateSpecializationKind() ==
4508 TSK_ImplicitInstantiation) {
4509 InstantiationVar->setTemplateSpecializationKind(
4510 TSK_ExplicitSpecialization);
4511 InstantiationVar->setLocation(Member->getLocation());
4512 }
4513
Douglas Gregor86d142a2009-10-08 07:24:58 +00004514 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4515 cast<VarDecl>(InstantiatedFrom),
4516 TSK_ExplicitSpecialization);
4517 } else {
4518 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004519 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4520 if (InstantiationClass->getTemplateSpecializationKind() ==
4521 TSK_ImplicitInstantiation) {
4522 InstantiationClass->setTemplateSpecializationKind(
4523 TSK_ExplicitSpecialization);
4524 InstantiationClass->setLocation(Member->getLocation());
4525 }
4526
Douglas Gregor86d142a2009-10-08 07:24:58 +00004527 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004528 cast<CXXRecordDecl>(InstantiatedFrom),
4529 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004530 }
4531
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004532 // Save the caller the trouble of having to figure out which declaration
4533 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004534 Previous.clear();
4535 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004536 return false;
4537}
4538
Douglas Gregore47f5a72009-10-14 23:41:34 +00004539/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004540///
4541/// \returns true if a serious error occurs, false otherwise.
4542static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00004543 SourceLocation InstLoc,
4544 bool WasQualifiedName) {
4545 DeclContext *ExpectedContext
4546 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4547 DeclContext *CurContext = S.CurContext->getLookupContext();
4548
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004549 if (CurContext->isRecord()) {
4550 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4551 << D;
4552 return true;
4553 }
4554
Douglas Gregore47f5a72009-10-14 23:41:34 +00004555 // C++0x [temp.explicit]p2:
4556 // An explicit instantiation shall appear in an enclosing namespace of its
4557 // template.
4558 //
4559 // This is DR275, which we do not retroactively apply to C++98/03.
4560 if (S.getLangOptions().CPlusPlus0x &&
4561 !CurContext->Encloses(ExpectedContext)) {
4562 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004563 S.Diag(InstLoc,
4564 S.getLangOptions().CPlusPlus0x?
4565 diag::err_explicit_instantiation_out_of_scope
4566 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004567 << D << NS;
4568 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004569 S.Diag(InstLoc,
4570 S.getLangOptions().CPlusPlus0x?
4571 diag::err_explicit_instantiation_must_be_global
4572 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004573 << D;
4574 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004575 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004576 }
4577
4578 // C++0x [temp.explicit]p2:
4579 // If the name declared in the explicit instantiation is an unqualified
4580 // name, the explicit instantiation shall appear in the namespace where
4581 // its template is declared or, if that namespace is inline (7.3.1), any
4582 // namespace from its enclosing namespace set.
4583 if (WasQualifiedName)
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004584 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004585
4586 if (CurContext->Equals(ExpectedContext))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004587 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004588
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004589 S.Diag(InstLoc,
4590 S.getLangOptions().CPlusPlus0x?
4591 diag::err_explicit_instantiation_unqualified_wrong_namespace
4592 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004593 << D << ExpectedContext;
4594 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004595 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004596}
4597
4598/// \brief Determine whether the given scope specifier has a template-id in it.
4599static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4600 if (!SS.isSet())
4601 return false;
4602
4603 // C++0x [temp.explicit]p2:
4604 // If the explicit instantiation is for a member function, a member class
4605 // or a static data member of a class template specialization, the name of
4606 // the class template specialization in the qualified-id for the member
4607 // name shall be a simple-template-id.
4608 //
4609 // C++98 has the same restriction, just worded differently.
4610 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4611 NNS; NNS = NNS->getPrefix())
4612 if (Type *T = NNS->getAsType())
4613 if (isa<TemplateSpecializationType>(T))
4614 return true;
4615
4616 return false;
4617}
4618
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004619// Explicit instantiation of a class template specialization
Douglas Gregora1f49972009-05-13 00:25:59 +00004620Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004621Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004622 SourceLocation ExternLoc,
4623 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004624 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004625 SourceLocation KWLoc,
4626 const CXXScopeSpec &SS,
4627 TemplateTy TemplateD,
4628 SourceLocation TemplateNameLoc,
4629 SourceLocation LAngleLoc,
4630 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004631 SourceLocation RAngleLoc,
4632 AttributeList *Attr) {
4633 // Find the class template we're specializing
4634 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004635 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004636 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4637
4638 // Check that the specialization uses the same tag kind as the
4639 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004640 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4641 assert(Kind != TTK_Enum &&
4642 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004643 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004644 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004645 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004646 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004647 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004648 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004649 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004650 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004651 diag::note_previous_use);
4652 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4653 }
4654
Douglas Gregore47f5a72009-10-14 23:41:34 +00004655 // C++0x [temp.explicit]p2:
4656 // There are two forms of explicit instantiation: an explicit instantiation
4657 // definition and an explicit instantiation declaration. An explicit
4658 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004659 TemplateSpecializationKind TSK
4660 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4661 : TSK_ExplicitInstantiationDeclaration;
4662
Douglas Gregora1f49972009-05-13 00:25:59 +00004663 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004664 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004665 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004666
4667 // Check that the template argument list is well-formed for this
4668 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004669 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4670 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004671 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4672 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004673 return true;
4674
Mike Stump11289f42009-09-09 15:08:12 +00004675 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004676 ClassTemplate->getTemplateParameters()->size()) &&
4677 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004678
Douglas Gregora1f49972009-05-13 00:25:59 +00004679 // Find the class template specialization declaration that
4680 // corresponds to these arguments.
Douglas Gregora1f49972009-05-13 00:25:59 +00004681 void *InsertPos = 0;
4682 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004683 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4684 Converted.flatSize(), InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004685
Abramo Bagnara8075c852010-06-12 07:44:57 +00004686 TemplateSpecializationKind PrevDecl_TSK
4687 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4688
Douglas Gregor54888652009-10-07 00:13:32 +00004689 // C++0x [temp.explicit]p2:
4690 // [...] An explicit instantiation shall appear in an enclosing
4691 // namespace of its template. [...]
4692 //
4693 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004694 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4695 SS.isSet()))
4696 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004697
Douglas Gregora1f49972009-05-13 00:25:59 +00004698 ClassTemplateSpecializationDecl *Specialization = 0;
4699
Douglas Gregor0681a352009-11-25 06:01:46 +00004700 bool ReusedDecl = false;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004701 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004702 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00004703 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004704 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004705 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004706 HasNoEffect))
Douglas Gregora1f49972009-05-13 00:25:59 +00004707 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004708
Abramo Bagnara8075c852010-06-12 07:44:57 +00004709 // Even though HasNoEffect == true means that this explicit instantiation
4710 // has no effect on semantics, we go on to put its syntax in the AST.
4711
4712 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4713 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004714 // Since the only prior class template specialization with these
4715 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00004716 // declaration node as our own, updating the source location
4717 // for the template name to reflect our new declaration.
4718 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004719 Specialization = PrevDecl;
4720 Specialization->setLocation(TemplateNameLoc);
4721 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004722 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004723 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004724 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004725
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004726 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004727 // Create a new class template specialization declaration node for
4728 // this explicit specialization.
4729 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004730 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00004731 ClassTemplate->getDeclContext(),
4732 TemplateNameLoc,
4733 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004734 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004735 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004736
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004737 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00004738 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004739 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004740 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004741 }
4742
4743 // Build the fully-sugared type for this explicit instantiation as
4744 // the user wrote in the explicit instantiation itself. This means
4745 // that we'll pretty-print the type retrieved from the
4746 // specialization's declaration the way that the user actually wrote
4747 // the explicit instantiation, rather than formatting the name based
4748 // on the "canonical" representation used to store the template
4749 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004750 TypeSourceInfo *WrittenTy
4751 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4752 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004753 Context.getTypeDeclType(Specialization));
4754 Specialization->setTypeAsWritten(WrittenTy);
4755 TemplateArgsIn.release();
4756
Abramo Bagnara8075c852010-06-12 07:44:57 +00004757 // Set source locations for keywords.
4758 Specialization->setExternLoc(ExternLoc);
4759 Specialization->setTemplateKeywordLoc(TemplateLoc);
4760
4761 // Add the explicit instantiation into its lexical context. However,
4762 // since explicit instantiations are never found by name lookup, we
4763 // just put it into the declaration context directly.
4764 Specialization->setLexicalDeclContext(CurContext);
4765 CurContext->addDecl(Specialization);
4766
4767 // Syntax is now OK, so return if it has no other effect on semantics.
4768 if (HasNoEffect) {
4769 // Set the template specialization kind.
4770 Specialization->setTemplateSpecializationKind(TSK);
4771 return DeclPtrTy::make(Specialization);
Douglas Gregor0681a352009-11-25 06:01:46 +00004772 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004773
4774 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004775 // A definition of a class template or class member template
4776 // shall be in scope at the point of the explicit instantiation of
4777 // the class template or class member template.
4778 //
4779 // This check comes when we actually try to perform the
4780 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004781 ClassTemplateSpecializationDecl *Def
4782 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004783 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004784 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004785 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004786 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00004787 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004788 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
4789 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004790
Douglas Gregor1d957a32009-10-27 18:42:08 +00004791 // Instantiate the members of this class template specialization.
4792 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004793 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004794 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004795 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4796
4797 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4798 // TSK_ExplicitInstantiationDefinition
4799 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4800 TSK == TSK_ExplicitInstantiationDefinition)
4801 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004802
Douglas Gregor12e49d32009-10-15 22:53:21 +00004803 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004804 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004805
Abramo Bagnara8075c852010-06-12 07:44:57 +00004806 // Set the template specialization kind.
4807 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00004808 return DeclPtrTy::make(Specialization);
4809}
4810
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004811// Explicit instantiation of a member class of a class template.
4812Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004813Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004814 SourceLocation ExternLoc,
4815 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004816 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004817 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004818 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004819 IdentifierInfo *Name,
4820 SourceLocation NameLoc,
4821 AttributeList *Attr) {
4822
Douglas Gregord6ab8742009-05-28 23:31:59 +00004823 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004824 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004825 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004826 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004827 MultiTemplateParamsArg(*this, 0, 0),
4828 Owned, IsDependent);
4829 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4830
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004831 if (!TagD)
4832 return true;
4833
4834 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4835 if (Tag->isEnum()) {
4836 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4837 << Context.getTypeDeclType(Tag);
4838 return true;
4839 }
4840
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004841 if (Tag->isInvalidDecl())
4842 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004843
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004844 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4845 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4846 if (!Pattern) {
4847 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4848 << Context.getTypeDeclType(Record);
4849 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4850 return true;
4851 }
4852
Douglas Gregore47f5a72009-10-14 23:41:34 +00004853 // C++0x [temp.explicit]p2:
4854 // If the explicit instantiation is for a class or member class, the
4855 // elaborated-type-specifier in the declaration shall include a
4856 // simple-template-id.
4857 //
4858 // C++98 has the same restriction, just worded differently.
4859 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00004860 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004861 << Record << SS.getRange();
4862
4863 // C++0x [temp.explicit]p2:
4864 // There are two forms of explicit instantiation: an explicit instantiation
4865 // definition and an explicit instantiation declaration. An explicit
4866 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004867 TemplateSpecializationKind TSK
4868 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4869 : TSK_ExplicitInstantiationDeclaration;
4870
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004871 // C++0x [temp.explicit]p2:
4872 // [...] An explicit instantiation shall appear in an enclosing
4873 // namespace of its template. [...]
4874 //
4875 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004876 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004877
4878 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004879 CXXRecordDecl *PrevDecl
4880 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004881 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004882 PrevDecl = Record;
4883 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004884 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00004885 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004886 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004887 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004888 PrevDecl,
4889 MSInfo->getTemplateSpecializationKind(),
4890 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004891 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004892 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004893 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004894 return TagD;
4895 }
4896
Douglas Gregor12e49d32009-10-15 22:53:21 +00004897 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004898 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004899 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004900 // C++ [temp.explicit]p3:
4901 // A definition of a member class of a class template shall be in scope
4902 // at the point of an explicit instantiation of the member class.
4903 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004904 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004905 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004906 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4907 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004908 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4909 << Pattern;
4910 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004911 } else {
4912 if (InstantiateClass(NameLoc, Record, Def,
4913 getTemplateInstantiationArgs(Record),
4914 TSK))
4915 return true;
4916
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004917 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004918 if (!RecordDef)
4919 return true;
4920 }
4921 }
4922
4923 // Instantiate all of the members of the class.
4924 InstantiateClassMembers(NameLoc, RecordDef,
4925 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004926
Douglas Gregor88d292c2010-05-13 16:44:06 +00004927 if (TSK == TSK_ExplicitInstantiationDefinition)
4928 MarkVTableUsed(NameLoc, RecordDef, true);
4929
Mike Stump87c57ac2009-05-16 07:39:55 +00004930 // FIXME: We don't have any representation for explicit instantiations of
4931 // member classes. Such a representation is not needed for compilation, but it
4932 // should be available for clients that want to see all of the declarations in
4933 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004934 return TagD;
4935}
4936
Douglas Gregor450f00842009-09-25 18:43:00 +00004937Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4938 SourceLocation ExternLoc,
4939 SourceLocation TemplateLoc,
4940 Declarator &D) {
4941 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004942 // TODO: check if/when DNInfo should replace Name.
4943 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4944 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00004945 if (!Name) {
4946 if (!D.isInvalidType())
4947 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4948 diag::err_explicit_instantiation_requires_name)
4949 << D.getDeclSpec().getSourceRange()
4950 << D.getSourceRange();
4951
4952 return true;
4953 }
4954
4955 // The scope passed in may not be a decl scope. Zip up the scope tree until
4956 // we find one that is.
4957 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4958 (S->getFlags() & Scope::TemplateParamScope) != 0)
4959 S = S->getParent();
4960
4961 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00004962 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
4963 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00004964 if (R.isNull())
4965 return true;
4966
4967 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4968 // Cannot explicitly instantiate a typedef.
4969 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4970 << Name;
4971 return true;
4972 }
4973
Douglas Gregor3c74d412009-10-14 20:14:33 +00004974 // C++0x [temp.explicit]p1:
4975 // [...] An explicit instantiation of a function template shall not use the
4976 // inline or constexpr specifiers.
4977 // Presumably, this also applies to member functions of class templates as
4978 // well.
4979 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4980 Diag(D.getDeclSpec().getInlineSpecLoc(),
4981 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00004982 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004983
4984 // FIXME: check for constexpr specifier.
4985
Douglas Gregore47f5a72009-10-14 23:41:34 +00004986 // C++0x [temp.explicit]p2:
4987 // There are two forms of explicit instantiation: an explicit instantiation
4988 // definition and an explicit instantiation declaration. An explicit
4989 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004990 TemplateSpecializationKind TSK
4991 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4992 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004993
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004994 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00004995 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004996
4997 if (!R->isFunctionType()) {
4998 // C++ [temp.explicit]p1:
4999 // A [...] static data member of a class template can be explicitly
5000 // instantiated from the member definition associated with its class
5001 // template.
John McCall27b18f82009-11-17 02:14:36 +00005002 if (Previous.isAmbiguous())
5003 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00005004
John McCall67c00872009-12-02 08:25:40 +00005005 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005006 if (!Prev || !Prev->isStaticDataMember()) {
5007 // We expect to see a data data member here.
5008 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5009 << Name;
5010 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5011 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005012 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005013 return true;
5014 }
5015
5016 if (!Prev->getInstantiatedFromStaticDataMember()) {
5017 // FIXME: Check for explicit specialization?
5018 Diag(D.getIdentifierLoc(),
5019 diag::err_explicit_instantiation_data_member_not_instantiated)
5020 << Prev;
5021 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5022 // FIXME: Can we provide a note showing where this was declared?
5023 return true;
5024 }
5025
Douglas Gregore47f5a72009-10-14 23:41:34 +00005026 // C++0x [temp.explicit]p2:
5027 // If the explicit instantiation is for a member function, a member class
5028 // or a static data member of a class template specialization, the name of
5029 // the class template specialization in the qualified-id for the member
5030 // name shall be a simple-template-id.
5031 //
5032 // C++98 has the same restriction, just worded differently.
5033 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5034 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005035 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005036 << Prev << D.getCXXScopeSpec().getRange();
5037
5038 // Check the scope of this explicit instantiation.
5039 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5040
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005041 // Verify that it is okay to explicitly instantiate here.
5042 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5043 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00005044 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005045 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005046 MSInfo->getTemplateSpecializationKind(),
5047 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005048 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005049 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005050 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005051 return DeclPtrTy();
5052
Douglas Gregor450f00842009-09-25 18:43:00 +00005053 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005054 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005055 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00005056 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
5057 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00005058
5059 // FIXME: Create an ExplicitInstantiation node?
5060 return DeclPtrTy();
5061 }
5062
Douglas Gregor0e876e02009-09-25 23:53:26 +00005063 // If the declarator is a template-id, translate the parser's template
5064 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005065 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005066 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005067 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5068 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005069 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5070 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005071 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5072 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005073 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005074 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005075 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005076 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005077 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005078
Douglas Gregor450f00842009-09-25 18:43:00 +00005079 // C++ [temp.explicit]p1:
5080 // A [...] function [...] can be explicitly instantiated from its template.
5081 // A member function [...] of a class template can be explicitly
5082 // instantiated from the member definition associated with its class
5083 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005084 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005085 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5086 P != PEnd; ++P) {
5087 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005088 if (!HasExplicitTemplateArgs) {
5089 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5090 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5091 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005092
John McCall58cc69d2010-01-27 01:50:18 +00005093 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005094 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5095 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005096 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005097 }
5098 }
5099
5100 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5101 if (!FunTmpl)
5102 continue;
5103
John McCallbc077cf2010-02-08 23:07:23 +00005104 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005105 FunctionDecl *Specialization = 0;
5106 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005107 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005108 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005109 R, Specialization, Info)) {
5110 // FIXME: Keep track of almost-matches?
5111 (void)TDK;
5112 continue;
5113 }
5114
John McCall58cc69d2010-01-27 01:50:18 +00005115 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005116 }
5117
5118 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005119 UnresolvedSetIterator Result
5120 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005121 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005122 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5123 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5124 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005125
John McCall58cc69d2010-01-27 01:50:18 +00005126 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005127 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005128
5129 // Ignore access control bits, we don't need them for redeclaration checking.
5130 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005131
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005132 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005133 Diag(D.getIdentifierLoc(),
5134 diag::err_explicit_instantiation_member_function_not_instantiated)
5135 << Specialization
5136 << (Specialization->getTemplateSpecializationKind() ==
5137 TSK_ExplicitSpecialization);
5138 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5139 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005140 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005141
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005142 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005143 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5144 PrevDecl = Specialization;
5145
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005146 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005147 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005148 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005149 PrevDecl,
5150 PrevDecl->getTemplateSpecializationKind(),
5151 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005152 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005153 return true;
5154
5155 // FIXME: We may still want to build some representation of this
5156 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00005157 if (HasNoEffect)
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005158 return DeclPtrTy();
5159 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005160
5161 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005162
5163 if (TSK == TSK_ExplicitInstantiationDefinition)
5164 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5165 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005166
Douglas Gregore47f5a72009-10-14 23:41:34 +00005167 // C++0x [temp.explicit]p2:
5168 // If the explicit instantiation is for a member function, a member class
5169 // or a static data member of a class template specialization, the name of
5170 // the class template specialization in the qualified-id for the member
5171 // name shall be a simple-template-id.
5172 //
5173 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005174 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005175 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005176 D.getCXXScopeSpec().isSet() &&
5177 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5178 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005179 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005180 << Specialization << D.getCXXScopeSpec().getRange();
5181
5182 CheckExplicitInstantiationScope(*this,
5183 FunTmpl? (NamedDecl *)FunTmpl
5184 : Specialization->getInstantiatedFromMemberFunction(),
5185 D.getIdentifierLoc(),
5186 D.getCXXScopeSpec().isSet());
5187
Douglas Gregor450f00842009-09-25 18:43:00 +00005188 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5189 return DeclPtrTy();
5190}
5191
Douglas Gregor333489b2009-03-27 23:10:48 +00005192Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005193Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5194 const CXXScopeSpec &SS, IdentifierInfo *Name,
5195 SourceLocation TagLoc, SourceLocation NameLoc) {
5196 // This has to hold, because SS is expected to be defined.
5197 assert(Name && "Expected a name in a dependent tag");
5198
5199 NestedNameSpecifier *NNS
5200 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5201 if (!NNS)
5202 return true;
5203
Abramo Bagnara6150c882010-05-11 21:36:43 +00005204 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005205
Douglas Gregorba41d012010-04-24 16:38:41 +00005206 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5207 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005208 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005209 return true;
5210 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005211
5212 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5213 return Context.getDependentNameType(Kwd, NNS, Name).getAsOpaquePtr();
John McCall7f41d982009-09-11 04:59:25 +00005214}
5215
5216Sema::TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005217Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5218 const CXXScopeSpec &SS, const IdentifierInfo &II,
5219 SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005220 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005221 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5222 if (!NNS)
5223 return true;
5224
Douglas Gregorf7d77712010-06-16 22:31:08 +00005225 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5226 !getLangOptions().CPlusPlus0x)
5227 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5228 << FixItHint::CreateRemoval(TypenameLoc);
5229
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005230 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005231 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005232 if (T.isNull())
5233 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005234
5235 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5236 if (isa<DependentNameType>(T)) {
5237 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005238 TL.setKeywordLoc(TypenameLoc);
5239 TL.setQualifierRange(SS.getRange());
5240 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005241 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005242 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005243 TL.setKeywordLoc(TypenameLoc);
5244 TL.setQualifierRange(SS.getRange());
5245 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005246 }
5247
5248 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor333489b2009-03-27 23:10:48 +00005249}
5250
Douglas Gregordce2b622009-04-01 00:28:59 +00005251Sema::TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005252Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5253 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
5254 TypeTy *Ty) {
5255 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5256 !getLangOptions().CPlusPlus0x)
5257 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5258 << FixItHint::CreateRemoval(TypenameLoc);
5259
John McCallf7bcc812010-05-28 23:32:21 +00005260 TypeSourceInfo *InnerTSI = 0;
5261 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCallf7bcc812010-05-28 23:32:21 +00005262
5263 assert(isa<TemplateSpecializationType>(T) &&
5264 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005265
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005266 if (computeDeclContext(SS, false)) {
5267 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005268 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005269 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005270
5271 // Push the inner type, preserving its source locations if possible.
5272 TypeLocBuilder Builder;
5273 if (InnerTSI)
5274 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5275 else
5276 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5277
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005278 /* Note: NNS already embedded in template specialization type T. */
5279 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCallf7bcc812010-05-28 23:32:21 +00005280 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5281 TL.setKeywordLoc(TypenameLoc);
5282 TL.setQualifierRange(SS.getRange());
5283
5284 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCall99b2fe52010-04-29 23:50:39 +00005285 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005286 }
Mike Stump11289f42009-09-09 15:08:12 +00005287
John McCallc392f372010-06-11 00:33:02 +00005288 // TODO: it's really silly that we make a template specialization
5289 // type earlier only to drop it again here.
5290 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5291 DependentTemplateName *DTN =
5292 TST->getTemplateName().getAsDependentTemplateName();
5293 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005294 assert(DTN->getQualifier()
5295 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5296 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5297 DTN->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00005298 DTN->getIdentifier(),
5299 TST->getNumArgs(),
5300 TST->getArgs());
John McCall99b2fe52010-04-29 23:50:39 +00005301 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCallc392f372010-06-11 00:33:02 +00005302 DependentTemplateSpecializationTypeLoc TL =
5303 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5304 if (InnerTSI) {
5305 TemplateSpecializationTypeLoc TSTL =
5306 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5307 TL.setLAngleLoc(TSTL.getLAngleLoc());
5308 TL.setRAngleLoc(TSTL.getRAngleLoc());
5309 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5310 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5311 } else {
5312 TL.initializeLocal(SourceLocation());
5313 }
John McCallf7bcc812010-05-28 23:32:21 +00005314 TL.setKeywordLoc(TypenameLoc);
5315 TL.setQualifierRange(SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005316 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00005317}
5318
Douglas Gregor333489b2009-03-27 23:10:48 +00005319/// \brief Build the type that describes a C++ typename specifier,
5320/// e.g., "typename T::type".
5321QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005322Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5323 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005324 SourceLocation KeywordLoc, SourceRange NNSRange,
5325 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005326 CXXScopeSpec SS;
5327 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005328 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005329
John McCall0b66eb32010-05-01 00:40:08 +00005330 DeclContext *Ctx = computeDeclContext(SS);
5331 if (!Ctx) {
5332 // If the nested-name-specifier is dependent and couldn't be
5333 // resolved to a type, build a typename type.
5334 assert(NNS->isDependent());
5335 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005336 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005337
John McCall0b66eb32010-05-01 00:40:08 +00005338 // If the nested-name-specifier refers to the current instantiation,
5339 // the "typename" keyword itself is superfluous. In C++03, the
5340 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5341 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00005342 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005343
John McCall0b66eb32010-05-01 00:40:08 +00005344 if (RequireCompleteDeclContext(SS, Ctx))
5345 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005346
5347 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005348 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005349 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005350 unsigned DiagID = 0;
5351 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005352 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005353 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005354 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005355 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005356
5357 case LookupResult::NotFoundInCurrentInstantiation:
5358 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005359 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005360
5361 case LookupResult::Found:
Douglas Gregorf7d77712010-06-16 22:31:08 +00005362 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005363 // We found a type. Build an ElaboratedType, since the
5364 // typename-specifier was just sugar.
5365 return Context.getElaboratedType(ETK_Typename, NNS,
5366 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005367 }
5368
5369 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005370 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005371 break;
5372
John McCalle61f2ba2009-11-18 02:36:19 +00005373 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005374 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005375 return QualType();
5376
Douglas Gregor333489b2009-03-27 23:10:48 +00005377 case LookupResult::FoundOverloaded:
5378 DiagID = diag::err_typename_nested_not_type;
5379 Referenced = *Result.begin();
5380 break;
5381
John McCall6538c932009-10-10 05:48:19 +00005382 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005383 return QualType();
5384 }
5385
5386 // If we get here, it's because name lookup did not find a
5387 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005388 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5389 IILoc);
5390 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005391 if (Referenced)
5392 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5393 << Name;
5394 return QualType();
5395}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005396
5397namespace {
5398 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005399 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005400 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005401 SourceLocation Loc;
5402 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005403
Douglas Gregor15acfb92009-08-06 16:20:37 +00005404 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005405 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5406
Mike Stump11289f42009-09-09 15:08:12 +00005407 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005408 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005409 DeclarationName Entity)
5410 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005411 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005412
5413 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005414 /// transformed.
5415 ///
5416 /// For the purposes of type reconstruction, a type has already been
5417 /// transformed if it is NULL or if it is not dependent.
5418 bool AlreadyTransformed(QualType T) {
5419 return T.isNull() || !T->isDependentType();
5420 }
Mike Stump11289f42009-09-09 15:08:12 +00005421
5422 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005423 /// rebuilt.
5424 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005425
Douglas Gregor15acfb92009-08-06 16:20:37 +00005426 /// \brief Returns the name of the entity whose type is being rebuilt.
5427 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005428
Douglas Gregoref6ab412009-10-27 06:26:26 +00005429 /// \brief Sets the "base" location and entity when that
5430 /// information is known based on another transformation.
5431 void setBase(SourceLocation Loc, DeclarationName Entity) {
5432 this->Loc = Loc;
5433 this->Entity = Entity;
5434 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00005435 };
5436}
5437
Douglas Gregor15acfb92009-08-06 16:20:37 +00005438/// \brief Rebuilds a type within the context of the current instantiation.
5439///
Mike Stump11289f42009-09-09 15:08:12 +00005440/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005441/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005442/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005443/// partial specialization thereof). This routine will rebuild that type now
5444/// that we have entered the declarator's scope, which may produce different
5445/// canonical types, e.g.,
5446///
5447/// \code
5448/// template<typename T>
5449/// struct X {
5450/// typedef T* pointer;
5451/// pointer data();
5452/// };
5453///
5454/// template<typename T>
5455/// typename X<T>::pointer X<T>::data() { ... }
5456/// \endcode
5457///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005458/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005459/// since we do not know that we can look into X<T> when we parsed the type.
5460/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005461/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005462/// as the canonical type of T*, allowing the return types of the out-of-line
5463/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005464TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5465 SourceLocation Loc,
5466 DeclarationName Name) {
5467 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005468 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005469
Douglas Gregor15acfb92009-08-06 16:20:37 +00005470 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5471 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005472}
Douglas Gregorbe999392009-09-15 16:23:51 +00005473
John McCall99b2fe52010-04-29 23:50:39 +00005474bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5475 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005476
5477 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5478 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5479 DeclarationName());
5480 NestedNameSpecifier *Rebuilt =
5481 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005482 if (!Rebuilt) return true;
5483
5484 SS.setScopeRep(Rebuilt);
5485 return false;
John McCall2408e322010-04-27 00:57:59 +00005486}
5487
Douglas Gregorbe999392009-09-15 16:23:51 +00005488/// \brief Produces a formatted string that describes the binding of
5489/// template parameters to template arguments.
5490std::string
5491Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5492 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005493 // FIXME: For variadic templates, we'll need to get the structured list.
5494 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5495 Args.flat_size());
5496}
5497
5498std::string
5499Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5500 const TemplateArgument *Args,
5501 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005502 std::string Result;
5503
Douglas Gregore62e6a02009-11-11 19:13:48 +00005504 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005505 return Result;
5506
5507 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005508 if (I >= NumArgs)
5509 break;
5510
Douglas Gregorbe999392009-09-15 16:23:51 +00005511 if (I == 0)
5512 Result += "[with ";
5513 else
5514 Result += ", ";
5515
5516 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5517 Result += Id->getName();
5518 } else {
5519 Result += '$';
5520 Result += llvm::utostr(I);
5521 }
5522
5523 Result += " = ";
5524
5525 switch (Args[I].getKind()) {
5526 case TemplateArgument::Null:
5527 Result += "<no value>";
5528 break;
5529
5530 case TemplateArgument::Type: {
5531 std::string TypeStr;
5532 Args[I].getAsType().getAsStringInternal(TypeStr,
5533 Context.PrintingPolicy);
5534 Result += TypeStr;
5535 break;
5536 }
5537
5538 case TemplateArgument::Declaration: {
5539 bool Unnamed = true;
5540 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5541 if (ND->getDeclName()) {
5542 Unnamed = false;
5543 Result += ND->getNameAsString();
5544 }
5545 }
5546
5547 if (Unnamed) {
5548 Result += "<anonymous>";
5549 }
5550 break;
5551 }
5552
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005553 case TemplateArgument::Template: {
5554 std::string Str;
5555 llvm::raw_string_ostream OS(Str);
5556 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5557 Result += OS.str();
5558 break;
5559 }
5560
Douglas Gregorbe999392009-09-15 16:23:51 +00005561 case TemplateArgument::Integral: {
5562 Result += Args[I].getAsIntegral()->toString(10);
5563 break;
5564 }
5565
5566 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005567 // FIXME: This is non-optimal, since we're regurgitating the
5568 // expression we were given.
5569 std::string Str;
5570 {
5571 llvm::raw_string_ostream OS(Str);
5572 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5573 Context.PrintingPolicy);
5574 }
5575 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005576 break;
5577 }
5578
5579 case TemplateArgument::Pack:
5580 // FIXME: Format template argument packs
5581 Result += "<template argument pack>";
5582 break;
5583 }
5584 }
5585
5586 Result += ']';
5587 return Result;
5588}