blob: c05f5d3818ead5d7fa97d3bf9ad8e454d8652c2a [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
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000012#include "clang/Sema/Sema.h"
13#include "clang/Sema/Lookup.h"
John McCallde6836a2010-08-24 07:21:54 +000014#include "clang/Sema/Template.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000015#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000016#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000017#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000018#include "clang/AST/ExprCXX.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000019#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000020#include "clang/AST/DeclTemplate.h"
John McCall8b0666c2010-08-20 18:27:03 +000021#include "clang/Sema/DeclSpec.h"
22#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000023#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000025#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000026using namespace clang;
27
Douglas Gregorb7bfe792009-09-02 22:59:36 +000028/// \brief Determine whether the declaration found is acceptable as the name
29/// of a template and, if so, return that template declaration. Otherwise,
30/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000031static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
32 NamedDecl *Orig) {
33 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000034
Douglas Gregorb7bfe792009-09-02 22:59:36 +000035 if (isa<TemplateDecl>(D))
John McCalle9cccd82010-06-16 08:42:20 +000036 return Orig;
Mike Stump11289f42009-09-09 15:08:12 +000037
Douglas Gregorb7bfe792009-09-02 22:59:36 +000038 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
39 // C++ [temp.local]p1:
40 // Like normal (non-template) classes, class templates have an
41 // injected-class-name (Clause 9). The injected-class-name
42 // can be used with or without a template-argument-list. When
43 // it is used without a template-argument-list, it is
44 // equivalent to the injected-class-name followed by the
45 // template-parameters of the class template enclosed in
46 // <>. When it is used with a template-argument-list, it
47 // refers to the specified class template specialization,
48 // which could be the current specialization or another
49 // specialization.
50 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000051 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000052 if (Record->getDescribedClassTemplate())
53 return Record->getDescribedClassTemplate();
54
55 if (ClassTemplateSpecializationDecl *Spec
56 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
57 return Spec->getSpecializedTemplate();
58 }
Mike Stump11289f42009-09-09 15:08:12 +000059
Douglas Gregorb7bfe792009-09-02 22:59:36 +000060 return 0;
61 }
Mike Stump11289f42009-09-09 15:08:12 +000062
Douglas Gregorb7bfe792009-09-02 22:59:36 +000063 return 0;
64}
65
John McCalle66edc12009-11-24 19:00:30 +000066static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor41f90302010-04-12 20:54:26 +000067 // The set of class templates we've already seen.
68 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000069 LookupResult::Filter filter = R.makeFilter();
70 while (filter.hasNext()) {
71 NamedDecl *Orig = filter.next();
John McCalle9cccd82010-06-16 08:42:20 +000072 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
John McCalle66edc12009-11-24 19:00:30 +000073 if (!Repl)
74 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +000075 else if (Repl != Orig) {
76
77 // C++ [temp.local]p3:
78 // A lookup that finds an injected-class-name (10.2) can result in an
79 // ambiguity in certain cases (for example, if it is found in more than
80 // one base class). If all of the injected-class-names that are found
81 // refer to specializations of the same class template, and if the name
82 // is followed by a template-argument-list, the reference refers to the
83 // class template itself and not a specialization thereof, and is not
84 // ambiguous.
85 //
86 // FIXME: Will we eventually have to do the same for alias templates?
87 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
88 if (!ClassTemplates.insert(ClassTmpl)) {
89 filter.erase();
90 continue;
91 }
John McCallbd8062d2010-08-13 07:02:08 +000092
93 // FIXME: we promote access to public here as a workaround to
94 // the fact that LookupResult doesn't let us remember that we
95 // found this template through a particular injected class name,
96 // which means we end up doing nasty things to the invariants.
97 // Pretending that access is public is *much* safer.
98 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +000099 }
John McCalle66edc12009-11-24 19:00:30 +0000100 }
101 filter.done();
102}
103
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000104TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000105 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000106 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000107 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000108 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000109 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000110 TemplateTy &TemplateResult,
111 bool &MemberOfUnknownSpecialization) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000112 assert(getLangOptions().CPlusPlus && "No template names in C!");
113
Douglas Gregor3cf81312009-11-03 23:16:33 +0000114 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000115 MemberOfUnknownSpecialization = false;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000116
117 switch (Name.getKind()) {
118 case UnqualifiedId::IK_Identifier:
119 TName = DeclarationName(Name.Identifier);
120 break;
121
122 case UnqualifiedId::IK_OperatorFunctionId:
123 TName = Context.DeclarationNames.getCXXOperatorName(
124 Name.OperatorFunctionId.Operator);
125 break;
126
Alexis Hunted0530f2009-11-28 08:58:14 +0000127 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000128 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
129 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000130
Douglas Gregor3cf81312009-11-03 23:16:33 +0000131 default:
132 return TNK_Non_template;
133 }
Mike Stump11289f42009-09-09 15:08:12 +0000134
John McCallba7bf592010-08-24 05:47:05 +0000135 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000136
Douglas Gregorff18cc12009-12-31 08:11:17 +0000137 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
138 LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000139 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
140 MemberOfUnknownSpecialization);
John McCalldcc71402010-08-13 02:23:42 +0000141 if (R.empty() || R.isAmbiguous()) {
142 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000143 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000144 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000145
John McCalld28ae272009-12-02 08:04:21 +0000146 TemplateName Template;
147 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000148
John McCalld28ae272009-12-02 08:04:21 +0000149 unsigned ResultCount = R.end() - R.begin();
150 if (ResultCount > 1) {
151 // We assume that we'll preserve the qualifier from a function
152 // template name in other ways.
153 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
154 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000155
156 // We'll do this lookup again later.
157 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000158 } else {
John McCalld28ae272009-12-02 08:04:21 +0000159 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
160
161 if (SS.isSet() && !SS.isInvalid()) {
162 NestedNameSpecifier *Qualifier
163 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000164 Template = Context.getQualifiedTemplateName(Qualifier,
165 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000166 } else {
167 Template = TemplateName(TD);
168 }
169
John McCalldcc71402010-08-13 02:23:42 +0000170 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000171 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000172
173 // We'll do this lookup again later.
174 R.suppressDiagnostics();
175 } else {
John McCalld28ae272009-12-02 08:04:21 +0000176 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
177 TemplateKind = TNK_Type_template;
178 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000179 }
Mike Stump11289f42009-09-09 15:08:12 +0000180
John McCalld28ae272009-12-02 08:04:21 +0000181 TemplateResult = TemplateTy::make(Template);
182 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000183}
184
Douglas Gregor18473f32010-01-12 21:28:44 +0000185bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
186 SourceLocation IILoc,
187 Scope *S,
188 const CXXScopeSpec *SS,
189 TemplateTy &SuggestedTemplate,
190 TemplateNameKind &SuggestedKind) {
191 // We can't recover unless there's a dependent scope specifier preceding the
192 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000193 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000194 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
195 computeDeclContext(*SS))
196 return false;
197
198 // The code is missing a 'template' keyword prior to the dependent template
199 // name.
200 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
201 Diag(IILoc, diag::err_template_kw_missing)
202 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000203 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor18473f32010-01-12 21:28:44 +0000204 SuggestedTemplate
205 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
206 SuggestedKind = TNK_Dependent_template_name;
207 return true;
208}
209
John McCalle66edc12009-11-24 19:00:30 +0000210void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000211 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000212 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000213 bool EnteringContext,
214 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000215 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000216 MemberOfUnknownSpecialization = false;
John McCalle66edc12009-11-24 19:00:30 +0000217 DeclContext *LookupCtx = 0;
218 bool isDependent = false;
219 if (!ObjectType.isNull()) {
220 // This nested-name-specifier occurs in a member access expression, e.g.,
221 // x->B::f, and we are looking into the type of the object.
222 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
223 LookupCtx = computeDeclContext(ObjectType);
224 isDependent = ObjectType->isDependentType();
225 assert((isDependent || !ObjectType->isIncompleteType()) &&
226 "Caller should have completed object type");
227 } else if (SS.isSet()) {
228 // This nested-name-specifier occurs after another nested-name-specifier,
229 // so long into the context associated with the prior nested-name-specifier.
230 LookupCtx = computeDeclContext(SS, EnteringContext);
231 isDependent = isDependentScopeSpecifier(SS);
232
233 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000234 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000235 return;
236 }
237
238 bool ObjectTypeSearchedInScope = false;
239 if (LookupCtx) {
240 // Perform "qualified" name lookup into the declaration context we
241 // computed, which is either the type of the base of a member access
242 // expression or the declaration context associated with a prior
243 // nested-name-specifier.
244 LookupQualifiedName(Found, LookupCtx);
245
246 if (!ObjectType.isNull() && Found.empty()) {
247 // C++ [basic.lookup.classref]p1:
248 // In a class member access expression (5.2.5), if the . or -> token is
249 // immediately followed by an identifier followed by a <, the
250 // identifier must be looked up to determine whether the < is the
251 // beginning of a template argument list (14.2) or a less-than operator.
252 // The identifier is first looked up in the class of the object
253 // expression. If the identifier is not found, it is then looked up in
254 // the context of the entire postfix-expression and shall name a class
255 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000256 if (S) LookupName(Found, S);
257 ObjectTypeSearchedInScope = true;
258 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000259 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000260 // We cannot look into a dependent object type or nested nme
261 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000262 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000263 return;
264 } else {
265 // Perform unqualified name lookup in the current scope.
266 LookupName(Found, S);
267 }
268
Douglas Gregorc119dd52010-01-12 17:06:20 +0000269 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000270 // If we did not find any names, attempt to correct any typos.
271 DeclarationName Name = Found.getLookupName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000272 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregorc048c522010-06-29 19:27:42 +0000273 false, CTC_CXXCasts)) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000274 FilterAcceptableTemplateNames(Context, Found);
John McCalle9cccd82010-06-16 08:42:20 +0000275 if (!Found.empty()) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000276 if (LookupCtx)
277 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
278 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000279 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000280 Found.getLookupName().getAsString());
281 else
282 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
283 << Name << Found.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +0000284 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000285 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000286 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
287 Diag(Template->getLocation(), diag::note_previous_decl)
288 << Template->getDeclName();
John McCalle9cccd82010-06-16 08:42:20 +0000289 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000290 } else {
291 Found.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +0000292 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000293 }
294 }
295
John McCalle66edc12009-11-24 19:00:30 +0000296 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000297 if (Found.empty()) {
298 if (isDependent)
299 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000300 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000301 }
John McCalle66edc12009-11-24 19:00:30 +0000302
303 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
304 // C++ [basic.lookup.classref]p1:
305 // [...] If the lookup in the class of the object expression finds a
306 // template, the name is also looked up in the context of the entire
307 // postfix-expression and [...]
308 //
309 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
310 LookupOrdinaryName);
311 LookupName(FoundOuter, S);
312 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor41f90302010-04-12 20:54:26 +0000313
John McCalle66edc12009-11-24 19:00:30 +0000314 if (FoundOuter.empty()) {
315 // - if the name is not found, the name found in the class of the
316 // object expression is used, otherwise
317 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
318 // - if the name is found in the context of the entire
319 // postfix-expression and does not name a class template, the name
320 // found in the class of the object expression is used, otherwise
John McCalle9cccd82010-06-16 08:42:20 +0000321 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000322 // - if the name found is a class template, it must refer to the same
323 // entity as the one found in the class of the object expression,
324 // otherwise the program is ill-formed.
325 if (!Found.isSingleResult() ||
326 Found.getFoundDecl()->getCanonicalDecl()
327 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
328 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000329 diag::ext_nested_name_member_ref_lookup_ambiguous)
330 << Found.getLookupName()
331 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000332 Diag(Found.getRepresentativeDecl()->getLocation(),
333 diag::note_ambig_member_ref_object_type)
334 << ObjectType;
335 Diag(FoundOuter.getFoundDecl()->getLocation(),
336 diag::note_ambig_member_ref_scope);
337
338 // Recover by taking the template that we found in the object
339 // expression's type.
340 }
341 }
342 }
343}
344
John McCallcd4b4772009-12-02 03:53:29 +0000345/// ActOnDependentIdExpression - Handle a dependent id-expression that
346/// was just parsed. This is only possible with an explicit scope
347/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000348ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000349Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000350 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000351 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000352 const TemplateArgumentListInfo *TemplateArgs) {
353 NestedNameSpecifier *Qualifier
354 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall87fe5d52010-05-20 01:18:31 +0000355
356 DeclContext *DC = getFunctionLevelDeclContext();
John McCalle66edc12009-11-24 19:00:30 +0000357
John McCallcd4b4772009-12-02 03:53:29 +0000358 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000359 isa<CXXMethodDecl>(DC) &&
360 cast<CXXMethodDecl>(DC)->isInstance()) {
361 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCallcd4b4772009-12-02 03:53:29 +0000362
John McCalle66edc12009-11-24 19:00:30 +0000363 // Since the 'this' expression is synthesized, we don't need to
364 // perform the double-lookup check.
365 NamedDecl *FirstQualifierInScope = 0;
366
John McCall2d74de92009-12-01 22:10:20 +0000367 return Owned(CXXDependentScopeMemberExpr::Create(Context,
368 /*This*/ 0, ThisType,
369 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000370 /*Op*/ SourceLocation(),
371 Qualifier, SS.getRange(),
372 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000373 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000374 TemplateArgs));
375 }
376
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000377 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000378}
379
John McCalldadc5752010-08-24 06:29:42 +0000380ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000381Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000382 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000383 const TemplateArgumentListInfo *TemplateArgs) {
384 return Owned(DependentScopeDeclRefExpr::Create(Context,
385 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
386 SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000387 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000388 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000389}
390
Douglas Gregor5101c242008-12-05 18:15:24 +0000391/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
392/// that the template parameter 'PrevDecl' is being shadowed by a new
393/// declaration at location Loc. Returns true to indicate that this is
394/// an error, and false otherwise.
395bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000396 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000397
398 // Microsoft Visual C++ permits template parameters to be shadowed.
399 if (getLangOptions().Microsoft)
400 return false;
401
402 // C++ [temp.local]p4:
403 // A template-parameter shall not be redeclared within its
404 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000405 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000406 << cast<NamedDecl>(PrevDecl)->getDeclName();
407 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
408 return true;
409}
410
Douglas Gregor463421d2009-03-03 04:44:36 +0000411/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000412/// the parameter D to reference the templated declaration and return a pointer
413/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000414TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
415 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
416 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000417 return Temp;
418 }
419 return 0;
420}
421
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000422static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
423 const ParsedTemplateArgument &Arg) {
424
425 switch (Arg.getKind()) {
426 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000427 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000428 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
429 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000430 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000431 return TemplateArgumentLoc(TemplateArgument(T), DI);
432 }
433
434 case ParsedTemplateArgument::NonType: {
435 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
436 return TemplateArgumentLoc(TemplateArgument(E), E);
437 }
438
439 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000440 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000441 return TemplateArgumentLoc(TemplateArgument(Template),
442 Arg.getScopeSpec().getRange(),
443 Arg.getLocation());
444 }
445 }
446
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000447 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000448 return TemplateArgumentLoc();
449}
450
451/// \brief Translates template arguments as provided by the parser
452/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000453void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
454 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000455 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000456 TemplateArgs.addArgument(translateTemplateArgument(*this,
457 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000458}
459
Douglas Gregor5101c242008-12-05 18:15:24 +0000460/// ActOnTypeParameter - Called when a C++ template type parameter
461/// (e.g., "typename T") has been parsed. Typename specifies whether
462/// the keyword "typename" was used to declare the type parameter
463/// (otherwise, "class" was used), and KeyLoc is the location of the
464/// "class" or "typename" keyword. ParamName is the name of the
465/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregor2ebcae12010-06-16 15:23:05 +0000466/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000467/// If the type parameter has a default argument, it will be added
468/// later via ActOnTypeParameterDefault.
John McCall48871652010-08-21 09:40:31 +0000469Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
470 SourceLocation EllipsisLoc,
471 SourceLocation KeyLoc,
472 IdentifierInfo *ParamName,
473 SourceLocation ParamNameLoc,
474 unsigned Depth, unsigned Position,
475 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000476 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000477 assert(S->isTemplateParamScope() &&
478 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000479 bool Invalid = false;
480
481 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000482 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000483 LookupOrdinaryName,
484 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000485 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000486 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000487 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000488 }
489
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000490 SourceLocation Loc = ParamNameLoc;
491 if (!ParamName)
492 Loc = KeyLoc;
493
Douglas Gregor5101c242008-12-05 18:15:24 +0000494 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000495 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
496 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000497 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000498 if (Invalid)
499 Param->setInvalidDecl();
500
501 if (ParamName) {
502 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000503 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000504 IdResolver.AddDecl(Param);
505 }
506
Douglas Gregordc13ded2010-07-01 00:00:45 +0000507 // Handle the default argument, if provided.
508 if (DefaultArg) {
509 TypeSourceInfo *DefaultTInfo;
510 GetTypeFromParser(DefaultArg, &DefaultTInfo);
511
512 assert(DefaultTInfo && "expected source information for type");
513
514 // C++0x [temp.param]p9:
515 // A default template-argument may be specified for any kind of
516 // template-parameter that is not a template parameter pack.
517 if (Ellipsis) {
518 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
John McCall48871652010-08-21 09:40:31 +0000519 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000520 }
521
522 // Check the template argument itself.
523 if (CheckTemplateArgument(Param, DefaultTInfo)) {
524 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000525 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000526 }
527
528 Param->setDefaultArgument(DefaultTInfo, false);
529 }
530
John McCall48871652010-08-21 09:40:31 +0000531 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000532}
533
Douglas Gregor463421d2009-03-03 04:44:36 +0000534/// \brief Check that the type of a non-type template parameter is
535/// well-formed.
536///
537/// \returns the (possibly-promoted) parameter type if valid;
538/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000539QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000540Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000541 // We don't allow variably-modified types as the type of non-type template
542 // parameters.
543 if (T->isVariablyModifiedType()) {
544 Diag(Loc, diag::err_variably_modified_nontype_template_param)
545 << T;
546 return QualType();
547 }
548
Douglas Gregor463421d2009-03-03 04:44:36 +0000549 // C++ [temp.param]p4:
550 //
551 // A non-type template-parameter shall have one of the following
552 // (optionally cv-qualified) types:
553 //
554 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000555 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000556 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000557 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000558 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000559 T->isReferenceType() ||
560 // -- pointer to member.
561 T->isMemberPointerType() ||
562 // If T is a dependent type, we can't do the check now, so we
563 // assume that it is well-formed.
564 T->isDependentType())
565 return T;
566 // C++ [temp.param]p8:
567 //
568 // A non-type template-parameter of type "array of T" or
569 // "function returning T" is adjusted to be of type "pointer to
570 // T" or "pointer to function returning T", respectively.
571 else if (T->isArrayType())
572 // FIXME: Keep the type prior to promotion?
573 return Context.getArrayDecayedType(T);
574 else if (T->isFunctionType())
575 // FIXME: Keep the type prior to promotion?
576 return Context.getPointerType(T);
Douglas Gregor959d5a02010-05-22 16:17:30 +0000577
Douglas Gregor463421d2009-03-03 04:44:36 +0000578 Diag(Loc, diag::err_template_nontype_parm_bad_type)
579 << T;
580
581 return QualType();
582}
583
John McCall48871652010-08-21 09:40:31 +0000584Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
585 unsigned Depth,
586 unsigned Position,
587 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000588 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000589 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
590 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000591
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000592 assert(S->isTemplateParamScope() &&
593 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000594 bool Invalid = false;
595
596 IdentifierInfo *ParamName = D.getIdentifier();
597 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000598 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000599 LookupOrdinaryName,
600 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000601 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000602 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000603 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000604 }
605
Douglas Gregor463421d2009-03-03 04:44:36 +0000606 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000607 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000608 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000609 Invalid = true;
610 }
Douglas Gregor81338792009-02-10 17:43:50 +0000611
Douglas Gregor5101c242008-12-05 18:15:24 +0000612 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000613 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
614 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000615 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000616 if (Invalid)
617 Param->setInvalidDecl();
618
619 if (D.getIdentifier()) {
620 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000621 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000622 IdResolver.AddDecl(Param);
623 }
Douglas Gregordc13ded2010-07-01 00:00:45 +0000624
625 // Check the well-formedness of the default template argument, if provided.
John McCallb268a282010-08-23 23:25:46 +0000626 if (Default) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000627 TemplateArgument Converted;
628 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
629 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000630 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000631 }
632
John McCallb268a282010-08-23 23:25:46 +0000633 Param->setDefaultArgument(Default, false);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000634 }
635
John McCall48871652010-08-21 09:40:31 +0000636 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000637}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000638
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000639/// ActOnTemplateTemplateParameter - Called when a C++ template template
640/// parameter (e.g. T in template <template <typename> class T> class array)
641/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000642Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
643 SourceLocation TmpLoc,
644 TemplateParamsTy *Params,
645 IdentifierInfo *Name,
646 SourceLocation NameLoc,
647 unsigned Depth,
648 unsigned Position,
649 SourceLocation EqualLoc,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000650 const ParsedTemplateArgument &Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000651 assert(S->isTemplateParamScope() &&
652 "Template template parameter not in template parameter scope!");
653
654 // Construct the parameter object.
655 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000656 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
657 TmpLoc, Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000658 (TemplateParameterList*)Params);
659
Douglas Gregordc13ded2010-07-01 00:00:45 +0000660 // If the template template parameter has a name, then link the identifier
661 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000662 if (Name) {
John McCall48871652010-08-21 09:40:31 +0000663 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000664 IdResolver.AddDecl(Param);
665 }
666
Douglas Gregordc13ded2010-07-01 00:00:45 +0000667 if (!Default.isInvalid()) {
668 // Check only that we have a template template argument. We don't want to
669 // try to check well-formedness now, because our template template parameter
670 // might have dependent types in its template parameters, which we wouldn't
671 // be able to match now.
672 //
673 // If none of the template template parameter's template arguments mention
674 // other template parameters, we could actually perform more checking here.
675 // However, it isn't worth doing.
676 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
677 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
678 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
679 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000680 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000681 }
682
683 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000684 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000685
John McCall48871652010-08-21 09:40:31 +0000686 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000687}
688
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000689/// ActOnTemplateParameterList - Builds a TemplateParameterList that
690/// contains the template parameters in Params/NumParams.
691Sema::TemplateParamsTy *
692Sema::ActOnTemplateParameterList(unsigned Depth,
693 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000694 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000695 SourceLocation LAngleLoc,
John McCall48871652010-08-21 09:40:31 +0000696 Decl **Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000697 SourceLocation RAngleLoc) {
698 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000699 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000700
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000701 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000702 (NamedDecl**)Params, NumParams,
703 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000704}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000705
John McCall3e11ebe2010-03-15 10:12:16 +0000706static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
707 if (SS.isSet())
708 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
709 SS.getRange());
710}
711
Douglas Gregorc08f4892009-03-25 00:13:59 +0000712Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000713Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000714 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000715 IdentifierInfo *Name, SourceLocation NameLoc,
716 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000717 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000718 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000719 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000720 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000721 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000722 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000723
724 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000725 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000726 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000727
Abramo Bagnara6150c882010-05-11 21:36:43 +0000728 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
729 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000730
731 // There is no such thing as an unnamed class template.
732 if (!Name) {
733 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000734 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000735 }
736
737 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000738 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000739 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000740 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000741 if (SS.isNotEmpty() && !SS.isInvalid()) {
742 SemanticContext = computeDeclContext(SS, true);
743 if (!SemanticContext) {
744 // FIXME: Produce a reasonable diagnostic here
745 return true;
746 }
Mike Stump11289f42009-09-09 15:08:12 +0000747
John McCall0b66eb32010-05-01 00:40:08 +0000748 if (RequireCompleteDeclContext(SS, SemanticContext))
749 return true;
750
John McCall27b18f82009-11-17 02:14:36 +0000751 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000752 } else {
753 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000754 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000755 }
Mike Stump11289f42009-09-09 15:08:12 +0000756
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000757 if (Previous.isAmbiguous())
758 return true;
759
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000760 NamedDecl *PrevDecl = 0;
761 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000762 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000763
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000764 // If there is a previous declaration with the same name, check
765 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000766 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000767 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000768
769 // We may have found the injected-class-name of a class template,
770 // class template partial specialization, or class template specialization.
771 // In these cases, grab the template that is being defined or specialized.
772 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
773 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
774 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
775 PrevClassTemplate
776 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
777 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
778 PrevClassTemplate
779 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
780 ->getSpecializedTemplate();
781 }
782 }
783
John McCalld43784f2009-12-18 11:25:59 +0000784 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000785 // C++ [namespace.memdef]p3:
786 // [...] When looking for a prior declaration of a class or a function
787 // declared as a friend, and when the name of the friend class or
788 // function is neither a qualified name nor a template-id, scopes outside
789 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000790 if (!SS.isSet()) {
791 DeclContext *OutermostContext = CurContext;
792 while (!OutermostContext->isFileContext())
793 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000794
Douglas Gregorb74b1032010-04-18 17:37:40 +0000795 if (PrevDecl &&
796 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
797 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
798 SemanticContext = PrevDecl->getDeclContext();
799 } else {
800 // Declarations in outer scopes don't matter. However, the outermost
801 // context we computed is the semantic context for our new
802 // declaration.
803 PrevDecl = PrevClassTemplate = 0;
804 SemanticContext = OutermostContext;
805 }
John McCall90d3bb92009-12-17 23:21:11 +0000806 }
Douglas Gregorb74b1032010-04-18 17:37:40 +0000807
John McCall90d3bb92009-12-17 23:21:11 +0000808 if (CurContext->isDependentContext()) {
809 // If this is a dependent context, we don't want to link the friend
810 // class template to the template in scope, because that would perform
811 // checking of the template parameter lists that can't be performed
812 // until the outer context is instantiated.
813 PrevDecl = PrevClassTemplate = 0;
814 }
815 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
816 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000817
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000818 if (PrevClassTemplate) {
819 // Ensure that the template parameter lists are compatible.
820 if (!TemplateParameterListsAreEqual(TemplateParams,
821 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000822 /*Complain=*/true,
823 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000824 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000825
826 // C++ [temp.class]p4:
827 // In a redeclaration, partial specialization, explicit
828 // specialization or explicit instantiation of a class template,
829 // the class-key shall agree in kind with the original class
830 // template declaration (7.1.5.3).
831 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000832 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000833 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000834 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000835 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000836 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000837 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000838 }
839
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000840 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000841 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000842 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000843 Diag(NameLoc, diag::err_redefinition) << Name;
844 Diag(Def->getLocation(), diag::note_previous_definition);
845 // FIXME: Would it make sense to try to "forget" the previous
846 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000847 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000848 }
849 }
850 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
851 // Maybe we will complain about the shadowed template parameter.
852 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
853 // Just pretend that we didn't see the previous declaration.
854 PrevDecl = 0;
855 } else if (PrevDecl) {
856 // C++ [temp]p5:
857 // A class template shall not have the same name as any other
858 // template, class, function, object, enumeration, enumerator,
859 // namespace, or type in the same scope (3.3), except as specified
860 // in (14.5.4).
861 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
862 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000863 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000864 }
865
Douglas Gregordba32632009-02-10 19:49:53 +0000866 // Check the template parameter list of this declaration, possibly
867 // merging in the template parameter list from the previous class
868 // template declaration.
869 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000870 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
871 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000872 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000873
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000874 if (SS.isSet()) {
875 // If the name of the template was qualified, we must be defining the
876 // template out-of-line.
877 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
878 !(TUK == TUK_Friend && CurContext->isDependentContext()))
879 Diag(NameLoc, diag::err_member_def_does_not_match)
880 << Name << SemanticContext << SS.getRange();
881 }
882
Mike Stump11289f42009-09-09 15:08:12 +0000883 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000884 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000885 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000886 PrevClassTemplate->getTemplatedDecl() : 0,
887 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000888 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000889
890 ClassTemplateDecl *NewTemplate
891 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
892 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000893 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000894 NewClass->setDescribedClassTemplate(NewTemplate);
895
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000896 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000897 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +0000898 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000899 assert(T->isDependentType() && "Class template type is not dependent?");
900 (void)T;
901
Douglas Gregorcf915552009-10-13 16:30:37 +0000902 // If we are providing an explicit specialization of a member that is a
903 // class template, make a note of that.
904 if (PrevClassTemplate &&
905 PrevClassTemplate->getInstantiatedFromMemberTemplate())
906 PrevClassTemplate->setMemberSpecialization();
907
Anders Carlsson137108d2009-03-26 01:24:28 +0000908 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000909 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000910 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000911
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000912 // Set the lexical context of these templates
913 NewClass->setLexicalDeclContext(CurContext);
914 NewTemplate->setLexicalDeclContext(CurContext);
915
John McCall9bb74a52009-07-31 02:45:11 +0000916 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000917 NewClass->startDefinition();
918
919 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000920 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000921
John McCall27b5c252009-09-14 21:59:20 +0000922 if (TUK != TUK_Friend)
923 PushOnScopeChains(NewTemplate, S);
924 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000925 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000926 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000927 NewClass->setAccess(PrevClassTemplate->getAccess());
928 }
John McCall27b5c252009-09-14 21:59:20 +0000929
Douglas Gregor3dad8422009-09-26 06:47:28 +0000930 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
931 PrevClassTemplate != NULL);
932
John McCall27b5c252009-09-14 21:59:20 +0000933 // Friend templates are visible in fairly strange ways.
934 if (!CurContext->isDependentContext()) {
935 DeclContext *DC = SemanticContext->getLookupContext();
936 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
937 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
938 PushOnScopeChains(NewTemplate, EnclosingScope,
939 /* AddToContext = */ false);
940 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000941
942 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
943 NewClass->getLocation(),
944 NewTemplate,
945 /*FIXME:*/NewClass->getLocation());
946 Friend->setAccess(AS_public);
947 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000948 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000949
Douglas Gregordba32632009-02-10 19:49:53 +0000950 if (Invalid) {
951 NewTemplate->setInvalidDecl();
952 NewClass->setInvalidDecl();
953 }
John McCall48871652010-08-21 09:40:31 +0000954 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000955}
956
Douglas Gregored5731f2009-11-25 17:50:39 +0000957/// \brief Diagnose the presence of a default template argument on a
958/// template parameter, which is ill-formed in certain contexts.
959///
960/// \returns true if the default template argument should be dropped.
961static bool DiagnoseDefaultTemplateArgument(Sema &S,
962 Sema::TemplateParamListContext TPC,
963 SourceLocation ParamLoc,
964 SourceRange DefArgRange) {
965 switch (TPC) {
966 case Sema::TPC_ClassTemplate:
967 return false;
968
969 case Sema::TPC_FunctionTemplate:
970 // C++ [temp.param]p9:
971 // A default template-argument shall not be specified in a
972 // function template declaration or a function template
973 // definition [...]
974 // (This sentence is not in C++0x, per DR226).
975 if (!S.getLangOptions().CPlusPlus0x)
976 S.Diag(ParamLoc,
977 diag::err_template_parameter_default_in_function_template)
978 << DefArgRange;
979 return false;
980
981 case Sema::TPC_ClassTemplateMember:
982 // C++0x [temp.param]p9:
983 // A default template-argument shall not be specified in the
984 // template-parameter-lists of the definition of a member of a
985 // class template that appears outside of the member's class.
986 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
987 << DefArgRange;
988 return true;
989
990 case Sema::TPC_FriendFunctionTemplate:
991 // C++ [temp.param]p9:
992 // A default template-argument shall not be specified in a
993 // friend template declaration.
994 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
995 << DefArgRange;
996 return true;
997
998 // FIXME: C++0x [temp.param]p9 allows default template-arguments
999 // for friend function templates if there is only a single
1000 // declaration (and it is a definition). Strange!
1001 }
1002
1003 return false;
1004}
1005
Douglas Gregordba32632009-02-10 19:49:53 +00001006/// \brief Checks the validity of a template parameter list, possibly
1007/// considering the template parameter list from a previous
1008/// declaration.
1009///
1010/// If an "old" template parameter list is provided, it must be
1011/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1012/// template parameter list.
1013///
1014/// \param NewParams Template parameter list for a new template
1015/// declaration. This template parameter list will be updated with any
1016/// default arguments that are carried through from the previous
1017/// template parameter list.
1018///
1019/// \param OldParams If provided, template parameter list from a
1020/// previous declaration of the same template. Default template
1021/// arguments will be merged from the old template parameter list to
1022/// the new template parameter list.
1023///
Douglas Gregored5731f2009-11-25 17:50:39 +00001024/// \param TPC Describes the context in which we are checking the given
1025/// template parameter list.
1026///
Douglas Gregordba32632009-02-10 19:49:53 +00001027/// \returns true if an error occurred, false otherwise.
1028bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001029 TemplateParameterList *OldParams,
1030 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001031 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001032
Douglas Gregordba32632009-02-10 19:49:53 +00001033 // C++ [temp.param]p10:
1034 // The set of default template-arguments available for use with a
1035 // template declaration or definition is obtained by merging the
1036 // default arguments from the definition (if in scope) and all
1037 // declarations in scope in the same way default function
1038 // arguments are (8.3.6).
1039 bool SawDefaultArgument = false;
1040 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001041
Anders Carlsson327865d2009-06-12 23:20:15 +00001042 bool SawParameterPack = false;
1043 SourceLocation ParameterPackLoc;
1044
Mike Stumpc89c8e32009-02-11 23:03:27 +00001045 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001046 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001047 if (OldParams)
1048 OldParam = OldParams->begin();
1049
1050 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1051 NewParamEnd = NewParams->end();
1052 NewParam != NewParamEnd; ++NewParam) {
1053 // Variables used to diagnose redundant default arguments
1054 bool RedundantDefaultArg = false;
1055 SourceLocation OldDefaultLoc;
1056 SourceLocation NewDefaultLoc;
1057
1058 // Variables used to diagnose missing default arguments
1059 bool MissingDefaultArg = false;
1060
Anders Carlsson327865d2009-06-12 23:20:15 +00001061 // C++0x [temp.param]p11:
1062 // If a template parameter of a class template is a template parameter pack,
1063 // it must be the last template parameter.
1064 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001065 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001066 diag::err_template_param_pack_must_be_last_template_parameter);
1067 Invalid = true;
1068 }
1069
Douglas Gregordba32632009-02-10 19:49:53 +00001070 if (TemplateTypeParmDecl *NewTypeParm
1071 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001072 // Check the presence of a default argument here.
1073 if (NewTypeParm->hasDefaultArgument() &&
1074 DiagnoseDefaultTemplateArgument(*this, TPC,
1075 NewTypeParm->getLocation(),
1076 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001077 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001078 NewTypeParm->removeDefaultArgument();
1079
1080 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001081 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001082 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001083
Anders Carlsson327865d2009-06-12 23:20:15 +00001084 if (NewTypeParm->isParameterPack()) {
1085 assert(!NewTypeParm->hasDefaultArgument() &&
1086 "Parameter packs can't have a default argument!");
1087 SawParameterPack = true;
1088 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001089 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001090 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001091 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1092 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1093 SawDefaultArgument = true;
1094 RedundantDefaultArg = true;
1095 PreviousDefaultArgLoc = NewDefaultLoc;
1096 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1097 // Merge the default argument from the old declaration to the
1098 // new declaration.
1099 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001100 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001101 true);
1102 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1103 } else if (NewTypeParm->hasDefaultArgument()) {
1104 SawDefaultArgument = true;
1105 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1106 } else if (SawDefaultArgument)
1107 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001108 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001109 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001110 // Check the presence of a default argument here.
1111 if (NewNonTypeParm->hasDefaultArgument() &&
1112 DiagnoseDefaultTemplateArgument(*this, TPC,
1113 NewNonTypeParm->getLocation(),
1114 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001115 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001116 }
1117
Mike Stump12b8ce12009-08-04 21:02:39 +00001118 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001119 NonTypeTemplateParmDecl *OldNonTypeParm
1120 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001121 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001122 NewNonTypeParm->hasDefaultArgument()) {
1123 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1124 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1125 SawDefaultArgument = true;
1126 RedundantDefaultArg = true;
1127 PreviousDefaultArgLoc = NewDefaultLoc;
1128 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1129 // Merge the default argument from the old declaration to the
1130 // new declaration.
1131 SawDefaultArgument = true;
1132 // FIXME: We need to create a new kind of "default argument"
1133 // expression that points to a previous template template
1134 // parameter.
1135 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001136 OldNonTypeParm->getDefaultArgument(),
1137 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001138 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1139 } else if (NewNonTypeParm->hasDefaultArgument()) {
1140 SawDefaultArgument = true;
1141 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1142 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001143 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001144 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001145 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001146 TemplateTemplateParmDecl *NewTemplateParm
1147 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001148 if (NewTemplateParm->hasDefaultArgument() &&
1149 DiagnoseDefaultTemplateArgument(*this, TPC,
1150 NewTemplateParm->getLocation(),
1151 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001152 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001153
1154 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001155 TemplateTemplateParmDecl *OldTemplateParm
1156 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001157 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001158 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001159 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1160 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001161 SawDefaultArgument = true;
1162 RedundantDefaultArg = true;
1163 PreviousDefaultArgLoc = NewDefaultLoc;
1164 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1165 // Merge the default argument from the old declaration to the
1166 // new declaration.
1167 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001168 // FIXME: We need to create a new kind of "default argument" expression
1169 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001170 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001171 OldTemplateParm->getDefaultArgument(),
1172 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001173 PreviousDefaultArgLoc
1174 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001175 } else if (NewTemplateParm->hasDefaultArgument()) {
1176 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001177 PreviousDefaultArgLoc
1178 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001179 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001180 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001181 }
1182
1183 if (RedundantDefaultArg) {
1184 // C++ [temp.param]p12:
1185 // A template-parameter shall not be given default arguments
1186 // by two different declarations in the same scope.
1187 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1188 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1189 Invalid = true;
1190 } else if (MissingDefaultArg) {
1191 // C++ [temp.param]p11:
1192 // If a template-parameter has a default template-argument,
1193 // all subsequent template-parameters shall have a default
1194 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001195 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001196 diag::err_template_param_default_arg_missing);
1197 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1198 Invalid = true;
1199 }
1200
1201 // If we have an old template parameter list that we're merging
1202 // in, move on to the next parameter.
1203 if (OldParams)
1204 ++OldParam;
1205 }
1206
1207 return Invalid;
1208}
Douglas Gregord32e0282009-02-09 23:23:08 +00001209
Mike Stump11289f42009-09-09 15:08:12 +00001210/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001211/// specifier, returning the template parameter list that applies to the
1212/// name.
1213///
1214/// \param DeclStartLoc the start of the declaration that has a scope
1215/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001216///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001217/// \param SS the scope specifier that will be matched to the given template
1218/// parameter lists. This scope specifier precedes a qualified name that is
1219/// being declared.
1220///
1221/// \param ParamLists the template parameter lists, from the outermost to the
1222/// innermost template parameter lists.
1223///
1224/// \param NumParamLists the number of template parameter lists in ParamLists.
1225///
John McCalle820e5e2010-04-13 20:37:33 +00001226/// \param IsFriend Whether to apply the slightly different rules for
1227/// matching template parameters to scope specifiers in friend
1228/// declarations.
1229///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001230/// \param IsExplicitSpecialization will be set true if the entity being
1231/// declared is an explicit specialization, false otherwise.
1232///
Mike Stump11289f42009-09-09 15:08:12 +00001233/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001234/// name that is preceded by the scope specifier @p SS. This template
1235/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001236/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001237/// template specialization), or may be NULL (if we were's declaring isn't
1238/// itself a template).
1239TemplateParameterList *
1240Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1241 const CXXScopeSpec &SS,
1242 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001243 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001244 bool IsFriend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001245 bool &IsExplicitSpecialization,
1246 bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001247 IsExplicitSpecialization = false;
1248
Douglas Gregord8d297c2009-07-21 23:53:31 +00001249 // Find the template-ids that occur within the nested-name-specifier. These
1250 // template-ids will match up with the template parameter lists.
1251 llvm::SmallVector<const TemplateSpecializationType *, 4>
1252 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001253 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1254 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001255 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1256 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001257 const Type *T = NNS->getAsType();
1258 if (!T) break;
1259
1260 // C++0x [temp.expl.spec]p17:
1261 // A member or a member template may be nested within many
1262 // enclosing class templates. In an explicit specialization for
1263 // such a member, the member declaration shall be preceded by a
1264 // template<> for each enclosing class template that is
1265 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001266 //
1267 // Following the existing practice of GNU and EDG, we allow a typedef of a
1268 // template specialization type.
1269 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1270 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001271
Mike Stump11289f42009-09-09 15:08:12 +00001272 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001273 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001274 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1275 if (!Template)
1276 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001277
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001278 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001279 ClassTemplateSpecializationDecl *SpecDecl
1280 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1281 // If the nested name specifier refers to an explicit specialization,
1282 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001283 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1284 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001285 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001286 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001287 }
Mike Stump11289f42009-09-09 15:08:12 +00001288
Douglas Gregord8d297c2009-07-21 23:53:31 +00001289 TemplateIdsInSpecifier.push_back(SpecType);
1290 }
1291 }
Mike Stump11289f42009-09-09 15:08:12 +00001292
Douglas Gregord8d297c2009-07-21 23:53:31 +00001293 // Reverse the list of template-ids in the scope specifier, so that we can
1294 // more easily match up the template-ids and the template parameter lists.
1295 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001296
Douglas Gregord8d297c2009-07-21 23:53:31 +00001297 SourceLocation FirstTemplateLoc = DeclStartLoc;
1298 if (NumParamLists)
1299 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001300
Douglas Gregord8d297c2009-07-21 23:53:31 +00001301 // Match the template-ids found in the specifier to the template parameter
1302 // lists.
1303 unsigned Idx = 0;
1304 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1305 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001306 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1307 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001308 if (Idx >= NumParamLists) {
1309 // We have a template-id without a corresponding template parameter
1310 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001311
1312 // ...which is fine if this is a friend declaration.
1313 if (IsFriend) {
1314 IsExplicitSpecialization = true;
1315 break;
1316 }
1317
Douglas Gregord8d297c2009-07-21 23:53:31 +00001318 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001319 // FIXME: the location information here isn't great.
1320 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001321 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001322 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001323 << SS.getRange();
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001324 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001325 } else {
1326 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1327 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001328 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001329 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001330 }
1331 return 0;
1332 }
Mike Stump11289f42009-09-09 15:08:12 +00001333
Douglas Gregord8d297c2009-07-21 23:53:31 +00001334 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001335 if (DependentTemplateId) {
John McCall2408e322010-04-27 00:57:59 +00001336 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00001337
John McCall2408e322010-04-27 00:57:59 +00001338 // Are there cases in (e.g.) friends where this won't match?
1339 if (const InjectedClassNameType *Injected
1340 = TemplateId->getAs<InjectedClassNameType>()) {
1341 CXXRecordDecl *Record = Injected->getDecl();
1342 if (ClassTemplatePartialSpecializationDecl *Partial =
1343 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1344 ExpectedTemplateParams = Partial->getTemplateParameters();
1345 else
1346 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1347 ->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001348 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001349
John McCall2408e322010-04-27 00:57:59 +00001350 if (ExpectedTemplateParams)
1351 TemplateParameterListsAreEqual(ParamLists[Idx],
1352 ExpectedTemplateParams,
1353 true, TPL_TemplateMatch);
1354
Douglas Gregored5731f2009-11-25 17:50:39 +00001355 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001356 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001357 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001358 diag::err_template_param_list_matches_nontemplate)
1359 << TemplateId
1360 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001361 else
1362 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001363 }
Mike Stump11289f42009-09-09 15:08:12 +00001364
Douglas Gregord8d297c2009-07-21 23:53:31 +00001365 // If there were at least as many template-ids as there were template
1366 // parameter lists, then there are no template parameter lists remaining for
1367 // the declaration itself.
Douglas Gregor5be1eb82010-08-20 03:26:10 +00001368 if (Idx >= NumParamLists)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001369 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001370
Douglas Gregord8d297c2009-07-21 23:53:31 +00001371 // If there were too many template parameter lists, complain about that now.
1372 if (Idx != NumParamLists - 1) {
1373 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001374 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001375 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001376 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1377 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001378 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1379 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001380
1381 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1382 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1383 diag::note_explicit_template_spec_does_not_need_header)
1384 << ExplicitSpecializationsInSpecifier.back();
1385 ExplicitSpecializationsInSpecifier.pop_back();
1386 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001387
1388 // We have a template parameter list with no corresponding scope, which
1389 // means that the resulting template declaration can't be instantiated
1390 // properly (we'll end up with dependent nodes when we shouldn't).
1391 if (!isExplicitSpecHeader)
1392 Invalid = true;
1393
Douglas Gregord8d297c2009-07-21 23:53:31 +00001394 ++Idx;
1395 }
1396 }
Mike Stump11289f42009-09-09 15:08:12 +00001397
Douglas Gregord8d297c2009-07-21 23:53:31 +00001398 // Return the last template parameter list, which corresponds to the
1399 // entity being declared.
1400 return ParamLists[NumParamLists - 1];
1401}
1402
Douglas Gregordc572a32009-03-30 22:58:21 +00001403QualType Sema::CheckTemplateIdType(TemplateName Name,
1404 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001405 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001406 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001407 if (!Template) {
1408 // The template name does not resolve to a template, so we just
1409 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001410 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001411 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001412
Douglas Gregorc40290e2009-03-09 23:48:35 +00001413 // Check that the template argument list is well-formed for this
1414 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001415 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001416 TemplateArgs.size());
1417 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001418 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001419 return QualType();
1420
Mike Stump11289f42009-09-09 15:08:12 +00001421 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001422 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001423 "Converted template argument list is too short!");
1424
1425 QualType CanonType;
1426
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001427 if (Name.isDependent() ||
1428 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001429 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001430 // This class template specialization is a dependent
1431 // type. Therefore, its canonical type is another class template
1432 // specialization type that contains all of the converted
1433 // arguments in canonical form. This ensures that, e.g., A<T> and
1434 // A<T, T> have identical types when A is declared as:
1435 //
1436 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001437 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001438 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001439 Converted.getFlatArguments(),
1440 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001441
Douglas Gregora8e02e72009-07-28 23:00:59 +00001442 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001443 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001444 // In the future, we need to teach getTemplateSpecializationType to only
1445 // build the canonical type and return that to us.
1446 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001447
1448 // This might work out to be a current instantiation, in which
1449 // case the canonical type needs to be the InjectedClassNameType.
1450 //
1451 // TODO: in theory this could be a simple hashtable lookup; most
1452 // changes to CurContext don't change the set of current
1453 // instantiations.
1454 if (isa<ClassTemplateDecl>(Template)) {
1455 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1456 // If we get out to a namespace, we're done.
1457 if (Ctx->isFileContext()) break;
1458
1459 // If this isn't a record, keep looking.
1460 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1461 if (!Record) continue;
1462
1463 // Look for one of the two cases with InjectedClassNameTypes
1464 // and check whether it's the same template.
1465 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1466 !Record->getDescribedClassTemplate())
1467 continue;
1468
1469 // Fetch the injected class name type and check whether its
1470 // injected type is equal to the type we just built.
1471 QualType ICNT = Context.getTypeDeclType(Record);
1472 QualType Injected = cast<InjectedClassNameType>(ICNT)
1473 ->getInjectedSpecializationType();
1474
1475 if (CanonType != Injected->getCanonicalTypeInternal())
1476 continue;
1477
1478 // If so, the canonical type of this TST is the injected
1479 // class name type of the record we just found.
1480 assert(ICNT.isCanonical());
1481 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00001482 break;
1483 }
1484 }
Mike Stump11289f42009-09-09 15:08:12 +00001485 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001486 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001487 // Find the class template specialization declaration that
1488 // corresponds to these arguments.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001489 void *InsertPos = 0;
1490 ClassTemplateSpecializationDecl *Decl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001491 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
1492 Converted.flatSize(), InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001493 if (!Decl) {
1494 // This is the first time we have referenced this class template
1495 // specialization. Create the canonical declaration and add it to
1496 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001497 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001498 ClassTemplate->getTemplatedDecl()->getTagKind(),
1499 ClassTemplate->getDeclContext(),
1500 ClassTemplate->getLocation(),
1501 ClassTemplate,
1502 Converted, 0);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001503 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001504 Decl->setLexicalDeclContext(CurContext);
1505 }
1506
1507 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001508 assert(isa<RecordType>(CanonType) &&
1509 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001510 }
Mike Stump11289f42009-09-09 15:08:12 +00001511
Douglas Gregorc40290e2009-03-09 23:48:35 +00001512 // Build the fully-sugared type for this class template
1513 // specialization, which refers back to the class template
1514 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00001515 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001516}
1517
Douglas Gregor67a65642009-02-17 23:15:12 +00001518Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001519Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001520 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001521 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001522 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001523 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001524
Douglas Gregorc40290e2009-03-09 23:48:35 +00001525 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001526 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001527 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001528
John McCall6b51f282009-11-23 01:53:49 +00001529 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001530 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001531
1532 if (Result.isNull())
1533 return true;
1534
John McCallbcd03502009-12-07 02:54:59 +00001535 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001536 TemplateSpecializationTypeLoc TL
1537 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1538 TL.setTemplateNameLoc(TemplateLoc);
1539 TL.setLAngleLoc(LAngleLoc);
1540 TL.setRAngleLoc(RAngleLoc);
1541 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1542 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1543
John McCallba7bf592010-08-24 05:47:05 +00001544 return CreateParsedType(Result, DI);
John McCalld8fe9af2009-09-08 17:47:29 +00001545}
John McCall06f6fe8d2009-09-04 01:14:41 +00001546
John McCalld8fe9af2009-09-08 17:47:29 +00001547Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1548 TagUseKind TUK,
1549 DeclSpec::TST TagSpec,
1550 SourceLocation TagLoc) {
1551 if (TypeResult.isInvalid())
1552 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001553
John McCall0ad16662009-10-29 08:12:44 +00001554 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001555 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001556 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001557
John McCalld8fe9af2009-09-08 17:47:29 +00001558 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001559 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001560
John McCalld8fe9af2009-09-08 17:47:29 +00001561 if (const RecordType *RT = Type->getAs<RecordType>()) {
1562 RecordDecl *D = RT->getDecl();
1563
1564 IdentifierInfo *Id = D->getIdentifier();
1565 assert(Id && "templated class must have an identifier");
1566
1567 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1568 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001569 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001570 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001571 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001572 }
1573 }
1574
Abramo Bagnara6150c882010-05-11 21:36:43 +00001575 ElaboratedTypeKeyword Keyword
1576 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1577 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001578
John McCallba7bf592010-08-24 05:47:05 +00001579 return ParsedType::make(ElabType);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001580}
1581
John McCalldadc5752010-08-24 06:29:42 +00001582ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001583 LookupResult &R,
1584 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001585 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001586 // FIXME: Can we do any checking at this point? I guess we could check the
1587 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001588 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001589 // though.
John McCalle66edc12009-11-24 19:00:30 +00001590
1591 // These should be filtered out by our callers.
1592 assert(!R.empty() && "empty lookup results when building templateid");
1593 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1594
1595 NestedNameSpecifier *Qualifier = 0;
1596 SourceRange QualifierRange;
1597 if (SS.isSet()) {
1598 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1599 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001600 }
John McCall58cc69d2010-01-27 01:50:18 +00001601
1602 // We don't want lookup warnings at this point.
1603 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001604
John McCalle66edc12009-11-24 19:00:30 +00001605 bool Dependent
1606 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1607 &TemplateArgs);
1608 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001609 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001610 Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001611 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001612 RequiresADL, TemplateArgs,
1613 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001614
1615 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001616}
1617
John McCalle66edc12009-11-24 19:00:30 +00001618// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00001619ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001620Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001621 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +00001622 const TemplateArgumentListInfo &TemplateArgs) {
1623 DeclContext *DC;
1624 if (!(DC = computeDeclContext(SS, false)) ||
1625 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001626 RequireCompleteDeclContext(SS, DC))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001627 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001628
Douglas Gregor786123d2010-05-21 23:18:07 +00001629 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001630 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00001631 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1632 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00001633
John McCalle66edc12009-11-24 19:00:30 +00001634 if (R.isAmbiguous())
1635 return ExprError();
1636
1637 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001638 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1639 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001640 return ExprError();
1641 }
1642
1643 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001644 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1645 << (NestedNameSpecifier*) SS.getScopeRep()
1646 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001647 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1648 return ExprError();
1649 }
1650
1651 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001652}
1653
Douglas Gregorb67535d2009-03-31 00:43:58 +00001654/// \brief Form a dependent template name.
1655///
1656/// This action forms a dependent template name given the template
1657/// name and its (presumably dependent) scope specifier. For
1658/// example, given "MetaFun::template apply", the scope specifier \p
1659/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1660/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregorbb119652010-06-16 23:00:59 +00001661TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1662 SourceLocation TemplateKWLoc,
1663 CXXScopeSpec &SS,
1664 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00001665 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00001666 bool EnteringContext,
1667 TemplateTy &Result) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00001668 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1669 !getLangOptions().CPlusPlus0x)
1670 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1671 << FixItHint::CreateRemoval(TemplateKWLoc);
1672
Douglas Gregor9abe2372010-01-19 16:01:07 +00001673 DeclContext *LookupCtx = 0;
1674 if (SS.isSet())
1675 LookupCtx = computeDeclContext(SS, EnteringContext);
1676 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00001677 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00001678 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001679 // C++0x [temp.names]p5:
1680 // If a name prefixed by the keyword template is not the name of
1681 // a template, the program is ill-formed. [Note: the keyword
1682 // template may not be applied to non-template members of class
1683 // templates. -end note ] [ Note: as is the case with the
1684 // typename prefix, the template prefix is allowed in cases
1685 // where it is not strictly necessary; i.e., when the
1686 // nested-name-specifier or the expression on the left of the ->
1687 // or . is not dependent on a template-parameter, or the use
1688 // does not appear in the scope of a template. -end note]
1689 //
1690 // Note: C++03 was more strict here, because it banned the use of
1691 // the "template" keyword prior to a template-name that was not a
1692 // dependent name. C++ DR468 relaxed this requirement (the
1693 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00001694 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00001695 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001696 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1697 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00001698 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001699 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1700 isa<CXXRecordDecl>(LookupCtx) &&
1701 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregorbb119652010-06-16 23:00:59 +00001702 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00001703 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001704 Diag(Name.getSourceRange().getBegin(),
1705 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001706 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001707 << Name.getSourceRange()
1708 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001709 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00001710 } else {
1711 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00001712 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001713 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001714 }
1715
Mike Stump11289f42009-09-09 15:08:12 +00001716 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001717 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001718
1719 switch (Name.getKind()) {
1720 case UnqualifiedId::IK_Identifier:
Douglas Gregorbb119652010-06-16 23:00:59 +00001721 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1722 Name.Identifier));
1723 return TNK_Dependent_template_name;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001724
Douglas Gregor71395fa2009-11-04 00:56:37 +00001725 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00001726 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00001727 Name.OperatorFunctionId.Operator));
Douglas Gregorbb119652010-06-16 23:00:59 +00001728 return TNK_Dependent_template_name;
Alexis Hunted0530f2009-11-28 08:58:14 +00001729
1730 case UnqualifiedId::IK_LiteralOperatorId:
1731 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1732
Douglas Gregor3cf81312009-11-03 23:16:33 +00001733 default:
1734 break;
1735 }
1736
1737 Diag(Name.getSourceRange().getBegin(),
1738 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001739 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001740 << Name.getSourceRange()
1741 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001742 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001743}
1744
Mike Stump11289f42009-09-09 15:08:12 +00001745bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001746 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001747 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001748 const TemplateArgument &Arg = AL.getArgument();
1749
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001750 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001751 switch(Arg.getKind()) {
1752 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001753 // C++ [temp.arg.type]p1:
1754 // A template-argument for a template-parameter which is a
1755 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001756 break;
1757 case TemplateArgument::Template: {
1758 // We have a template type parameter but the template argument
1759 // is a template without any arguments.
1760 SourceRange SR = AL.getSourceRange();
1761 TemplateName Name = Arg.getAsTemplate();
1762 Diag(SR.getBegin(), diag::err_template_missing_args)
1763 << Name << SR;
1764 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1765 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001766
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001767 return true;
1768 }
1769 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001770 // We have a template type parameter but the template argument
1771 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001772 SourceRange SR = AL.getSourceRange();
1773 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001774 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001775
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001776 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001777 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001778 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001779
John McCallbcd03502009-12-07 02:54:59 +00001780 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001781 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001782
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001783 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001784 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001785 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001786 return false;
1787}
1788
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001789/// \brief Substitute template arguments into the default template argument for
1790/// the given template type parameter.
1791///
1792/// \param SemaRef the semantic analysis object for which we are performing
1793/// the substitution.
1794///
1795/// \param Template the template that we are synthesizing template arguments
1796/// for.
1797///
1798/// \param TemplateLoc the location of the template name that started the
1799/// template-id we are checking.
1800///
1801/// \param RAngleLoc the location of the right angle bracket ('>') that
1802/// terminates the template-id.
1803///
1804/// \param Param the template template parameter whose default we are
1805/// substituting into.
1806///
1807/// \param Converted the list of template arguments provided for template
1808/// parameters that precede \p Param in the template parameter list.
1809///
1810/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001811static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001812SubstDefaultTemplateArgument(Sema &SemaRef,
1813 TemplateDecl *Template,
1814 SourceLocation TemplateLoc,
1815 SourceLocation RAngleLoc,
1816 TemplateTypeParmDecl *Param,
1817 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001818 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001819
1820 // If the argument type is dependent, instantiate it now based
1821 // on the previously-computed template arguments.
1822 if (ArgType->getType()->isDependentType()) {
1823 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1824 /*TakeArgs=*/false);
1825
1826 MultiLevelTemplateArgumentList AllTemplateArgs
1827 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1828
1829 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1830 Template, Converted.getFlatArguments(),
1831 Converted.flatSize(),
1832 SourceRange(TemplateLoc, RAngleLoc));
1833
1834 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1835 Param->getDefaultArgumentLoc(),
1836 Param->getDeclName());
1837 }
1838
1839 return ArgType;
1840}
1841
1842/// \brief Substitute template arguments into the default template argument for
1843/// the given non-type template parameter.
1844///
1845/// \param SemaRef the semantic analysis object for which we are performing
1846/// the substitution.
1847///
1848/// \param Template the template that we are synthesizing template arguments
1849/// for.
1850///
1851/// \param TemplateLoc the location of the template name that started the
1852/// template-id we are checking.
1853///
1854/// \param RAngleLoc the location of the right angle bracket ('>') that
1855/// terminates the template-id.
1856///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001857/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001858/// substituting into.
1859///
1860/// \param Converted the list of template arguments provided for template
1861/// parameters that precede \p Param in the template parameter list.
1862///
1863/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00001864static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001865SubstDefaultTemplateArgument(Sema &SemaRef,
1866 TemplateDecl *Template,
1867 SourceLocation TemplateLoc,
1868 SourceLocation RAngleLoc,
1869 NonTypeTemplateParmDecl *Param,
1870 TemplateArgumentListBuilder &Converted) {
1871 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1872 /*TakeArgs=*/false);
1873
1874 MultiLevelTemplateArgumentList AllTemplateArgs
1875 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1876
1877 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1878 Template, Converted.getFlatArguments(),
1879 Converted.flatSize(),
1880 SourceRange(TemplateLoc, RAngleLoc));
1881
1882 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1883}
1884
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001885/// \brief Substitute template arguments into the default template argument for
1886/// the given template template parameter.
1887///
1888/// \param SemaRef the semantic analysis object for which we are performing
1889/// the substitution.
1890///
1891/// \param Template the template that we are synthesizing template arguments
1892/// for.
1893///
1894/// \param TemplateLoc the location of the template name that started the
1895/// template-id we are checking.
1896///
1897/// \param RAngleLoc the location of the right angle bracket ('>') that
1898/// terminates the template-id.
1899///
1900/// \param Param the template template parameter whose default we are
1901/// substituting into.
1902///
1903/// \param Converted the list of template arguments provided for template
1904/// parameters that precede \p Param in the template parameter list.
1905///
1906/// \returns the substituted template argument, or NULL if an error occurred.
1907static TemplateName
1908SubstDefaultTemplateArgument(Sema &SemaRef,
1909 TemplateDecl *Template,
1910 SourceLocation TemplateLoc,
1911 SourceLocation RAngleLoc,
1912 TemplateTemplateParmDecl *Param,
1913 TemplateArgumentListBuilder &Converted) {
1914 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1915 /*TakeArgs=*/false);
1916
1917 MultiLevelTemplateArgumentList AllTemplateArgs
1918 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1919
1920 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1921 Template, Converted.getFlatArguments(),
1922 Converted.flatSize(),
1923 SourceRange(TemplateLoc, RAngleLoc));
1924
1925 return SemaRef.SubstTemplateName(
1926 Param->getDefaultArgument().getArgument().getAsTemplate(),
1927 Param->getDefaultArgument().getTemplateNameLoc(),
1928 AllTemplateArgs);
1929}
1930
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001931/// \brief If the given template parameter has a default template
1932/// argument, substitute into that default template argument and
1933/// return the corresponding template argument.
1934TemplateArgumentLoc
1935Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1936 SourceLocation TemplateLoc,
1937 SourceLocation RAngleLoc,
1938 Decl *Param,
1939 TemplateArgumentListBuilder &Converted) {
1940 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1941 if (!TypeParm->hasDefaultArgument())
1942 return TemplateArgumentLoc();
1943
John McCallbcd03502009-12-07 02:54:59 +00001944 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001945 TemplateLoc,
1946 RAngleLoc,
1947 TypeParm,
1948 Converted);
1949 if (DI)
1950 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1951
1952 return TemplateArgumentLoc();
1953 }
1954
1955 if (NonTypeTemplateParmDecl *NonTypeParm
1956 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1957 if (!NonTypeParm->hasDefaultArgument())
1958 return TemplateArgumentLoc();
1959
John McCalldadc5752010-08-24 06:29:42 +00001960 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001961 TemplateLoc,
1962 RAngleLoc,
1963 NonTypeParm,
1964 Converted);
1965 if (Arg.isInvalid())
1966 return TemplateArgumentLoc();
1967
1968 Expr *ArgE = Arg.takeAs<Expr>();
1969 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1970 }
1971
1972 TemplateTemplateParmDecl *TempTempParm
1973 = cast<TemplateTemplateParmDecl>(Param);
1974 if (!TempTempParm->hasDefaultArgument())
1975 return TemplateArgumentLoc();
1976
1977 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1978 TemplateLoc,
1979 RAngleLoc,
1980 TempTempParm,
1981 Converted);
1982 if (TName.isNull())
1983 return TemplateArgumentLoc();
1984
1985 return TemplateArgumentLoc(TemplateArgument(TName),
1986 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1987 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1988}
1989
Douglas Gregorda0fb532009-11-11 19:31:23 +00001990/// \brief Check that the given template argument corresponds to the given
1991/// template parameter.
1992bool Sema::CheckTemplateArgument(NamedDecl *Param,
1993 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001994 TemplateDecl *Template,
1995 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001996 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001997 TemplateArgumentListBuilder &Converted,
1998 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001999 // Check template type parameters.
2000 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002001 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002002
Douglas Gregoreebed722009-11-11 19:41:09 +00002003 // Check non-type template parameters.
2004 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00002005 // Do substitution on the type of the non-type template parameter
2006 // with the template arguments we've seen thus far.
2007 QualType NTTPType = NTTP->getType();
2008 if (NTTPType->isDependentType()) {
2009 // Do substitution on the type of the non-type template parameter.
2010 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2011 NTTP, Converted.getFlatArguments(),
2012 Converted.flatSize(),
2013 SourceRange(TemplateLoc, RAngleLoc));
2014
2015 TemplateArgumentList TemplateArgs(Context, Converted,
2016 /*TakeArgs=*/false);
2017 NTTPType = SubstType(NTTPType,
2018 MultiLevelTemplateArgumentList(TemplateArgs),
2019 NTTP->getLocation(),
2020 NTTP->getDeclName());
2021 // If that worked, check the non-type template parameter type
2022 // for validity.
2023 if (!NTTPType.isNull())
2024 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2025 NTTP->getLocation());
2026 if (NTTPType.isNull())
2027 return true;
2028 }
2029
2030 switch (Arg.getArgument().getKind()) {
2031 case TemplateArgument::Null:
2032 assert(false && "Should never see a NULL template argument here");
2033 return true;
2034
2035 case TemplateArgument::Expression: {
2036 Expr *E = Arg.getArgument().getAsExpr();
2037 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002038 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002039 return true;
2040
2041 Converted.Append(Result);
2042 break;
2043 }
2044
2045 case TemplateArgument::Declaration:
2046 case TemplateArgument::Integral:
2047 // We've already checked this template argument, so just copy
2048 // it to the list of converted arguments.
2049 Converted.Append(Arg.getArgument());
2050 break;
2051
2052 case TemplateArgument::Template:
2053 // We were given a template template argument. It may not be ill-formed;
2054 // see below.
2055 if (DependentTemplateName *DTN
2056 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2057 // We have a template argument such as \c T::template X, which we
2058 // parsed as a template template argument. However, since we now
2059 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002060 // template name into an expression.
2061
2062 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2063 Arg.getTemplateNameLoc());
2064
John McCalle66edc12009-11-24 19:00:30 +00002065 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2066 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002067 Arg.getTemplateQualifierRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002068 NameInfo);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002069
2070 TemplateArgument Result;
2071 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2072 return true;
2073
2074 Converted.Append(Result);
2075 break;
2076 }
2077
2078 // We have a template argument that actually does refer to a class
2079 // template, template alias, or template template parameter, and
2080 // therefore cannot be a non-type template argument.
2081 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2082 << Arg.getSourceRange();
2083
2084 Diag(Param->getLocation(), diag::note_template_param_here);
2085 return true;
2086
2087 case TemplateArgument::Type: {
2088 // We have a non-type template parameter but the template
2089 // argument is a type.
2090
2091 // C++ [temp.arg]p2:
2092 // In a template-argument, an ambiguity between a type-id and
2093 // an expression is resolved to a type-id, regardless of the
2094 // form of the corresponding template-parameter.
2095 //
2096 // We warn specifically about this case, since it can be rather
2097 // confusing for users.
2098 QualType T = Arg.getArgument().getAsType();
2099 SourceRange SR = Arg.getSourceRange();
2100 if (T->isFunctionType())
2101 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2102 else
2103 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2104 Diag(Param->getLocation(), diag::note_template_param_here);
2105 return true;
2106 }
2107
2108 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002109 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002110 break;
2111 }
2112
2113 return false;
2114 }
2115
2116
2117 // Check template template parameters.
2118 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2119
2120 // Substitute into the template parameter list of the template
2121 // template parameter, since previously-supplied template arguments
2122 // may appear within the template template parameter.
2123 {
2124 // Set up a template instantiation context.
2125 LocalInstantiationScope Scope(*this);
2126 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2127 TempParm, Converted.getFlatArguments(),
2128 Converted.flatSize(),
2129 SourceRange(TemplateLoc, RAngleLoc));
2130
2131 TemplateArgumentList TemplateArgs(Context, Converted,
2132 /*TakeArgs=*/false);
2133 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2134 SubstDecl(TempParm, CurContext,
2135 MultiLevelTemplateArgumentList(TemplateArgs)));
2136 if (!TempParm)
2137 return true;
2138
2139 // FIXME: TempParam is leaked.
2140 }
2141
2142 switch (Arg.getArgument().getKind()) {
2143 case TemplateArgument::Null:
2144 assert(false && "Should never see a NULL template argument here");
2145 return true;
2146
2147 case TemplateArgument::Template:
2148 if (CheckTemplateArgument(TempParm, Arg))
2149 return true;
2150
2151 Converted.Append(Arg.getArgument());
2152 break;
2153
2154 case TemplateArgument::Expression:
2155 case TemplateArgument::Type:
2156 // We have a template template parameter but the template
2157 // argument does not refer to a template.
2158 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2159 return true;
2160
2161 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002162 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002163 "Declaration argument with template template parameter");
2164 break;
2165 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002166 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002167 "Integral argument with template template parameter");
2168 break;
2169
2170 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002171 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002172 break;
2173 }
2174
2175 return false;
2176}
2177
Douglas Gregord32e0282009-02-09 23:23:08 +00002178/// \brief Check that the given template argument list is well-formed
2179/// for specializing the given template.
2180bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2181 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002182 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002183 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002184 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002185 TemplateParameterList *Params = Template->getTemplateParameters();
2186 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002187 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002188 bool Invalid = false;
2189
John McCall6b51f282009-11-23 01:53:49 +00002190 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2191
Mike Stump11289f42009-09-09 15:08:12 +00002192 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002193 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002194
Anders Carlsson15201f12009-06-13 02:08:00 +00002195 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002196 (NumArgs < Params->getMinRequiredArguments() &&
2197 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002198 // FIXME: point at either the first arg beyond what we can handle,
2199 // or the '>', depending on whether we have too many or too few
2200 // arguments.
2201 SourceRange Range;
2202 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002203 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002204 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2205 << (NumArgs > NumParams)
2206 << (isa<ClassTemplateDecl>(Template)? 0 :
2207 isa<FunctionTemplateDecl>(Template)? 1 :
2208 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2209 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002210 Diag(Template->getLocation(), diag::note_template_decl_here)
2211 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002212 Invalid = true;
2213 }
Mike Stump11289f42009-09-09 15:08:12 +00002214
2215 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002216 // [...] The type and form of each template-argument specified in
2217 // a template-id shall match the type and form specified for the
2218 // corresponding parameter declared by the template in its
2219 // template-parameter-list.
2220 unsigned ArgIdx = 0;
2221 for (TemplateParameterList::iterator Param = Params->begin(),
2222 ParamEnd = Params->end();
2223 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002224 if (ArgIdx > NumArgs && PartialTemplateArgs)
2225 break;
Mike Stump11289f42009-09-09 15:08:12 +00002226
Douglas Gregoreebed722009-11-11 19:41:09 +00002227 // If we have a template parameter pack, check every remaining template
2228 // argument against that template parameter pack.
2229 if ((*Param)->isTemplateParameterPack()) {
2230 Converted.BeginPack();
2231 for (; ArgIdx < NumArgs; ++ArgIdx) {
2232 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2233 TemplateLoc, RAngleLoc, Converted)) {
2234 Invalid = true;
2235 break;
2236 }
2237 }
2238 Converted.EndPack();
2239 continue;
2240 }
2241
Douglas Gregor84d49a22009-11-11 21:54:23 +00002242 if (ArgIdx < NumArgs) {
2243 // Check the template argument we were given.
2244 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2245 TemplateLoc, RAngleLoc, Converted))
2246 return true;
2247
2248 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002249 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002250
Douglas Gregor84d49a22009-11-11 21:54:23 +00002251 // We have a default template argument that we will use.
2252 TemplateArgumentLoc Arg;
2253
2254 // Retrieve the default template argument from the template
2255 // parameter. For each kind of template parameter, we substitute the
2256 // template arguments provided thus far and any "outer" template arguments
2257 // (when the template parameter was part of a nested template) into
2258 // the default argument.
2259 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2260 if (!TTP->hasDefaultArgument()) {
2261 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2262 break;
2263 }
2264
John McCallbcd03502009-12-07 02:54:59 +00002265 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002266 Template,
2267 TemplateLoc,
2268 RAngleLoc,
2269 TTP,
2270 Converted);
2271 if (!ArgType)
2272 return true;
2273
2274 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2275 ArgType);
2276 } else if (NonTypeTemplateParmDecl *NTTP
2277 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2278 if (!NTTP->hasDefaultArgument()) {
2279 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2280 break;
2281 }
2282
John McCalldadc5752010-08-24 06:29:42 +00002283 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002284 TemplateLoc,
2285 RAngleLoc,
2286 NTTP,
2287 Converted);
2288 if (E.isInvalid())
2289 return true;
2290
2291 Expr *Ex = E.takeAs<Expr>();
2292 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2293 } else {
2294 TemplateTemplateParmDecl *TempParm
2295 = cast<TemplateTemplateParmDecl>(*Param);
2296
2297 if (!TempParm->hasDefaultArgument()) {
2298 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2299 break;
2300 }
2301
2302 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2303 TemplateLoc,
2304 RAngleLoc,
2305 TempParm,
2306 Converted);
2307 if (Name.isNull())
2308 return true;
2309
2310 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2311 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2312 TempParm->getDefaultArgument().getTemplateNameLoc());
2313 }
2314
2315 // Introduce an instantiation record that describes where we are using
2316 // the default template argument.
2317 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2318 Converted.getFlatArguments(),
2319 Converted.flatSize(),
2320 SourceRange(TemplateLoc, RAngleLoc));
2321
2322 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002323 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002324 RAngleLoc, Converted))
2325 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002326 }
2327
2328 return Invalid;
2329}
2330
2331/// \brief Check a template argument against its corresponding
2332/// template type parameter.
2333///
2334/// This routine implements the semantics of C++ [temp.arg.type]. It
2335/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002336bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002337 TypeSourceInfo *ArgInfo) {
2338 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002339 QualType Arg = ArgInfo->getType();
2340
Douglas Gregord32e0282009-02-09 23:23:08 +00002341 // C++ [temp.arg.type]p2:
2342 // A local type, a type with no linkage, an unnamed type or a type
2343 // compounded from any of these types shall not be used as a
2344 // template-argument for a template type-parameter.
2345 //
Douglas Gregor959d5a02010-05-22 16:17:30 +00002346 // FIXME: Perform the unnamed type check.
2347 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002348 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002349 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002350 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002351 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002352 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002353 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002354 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall0ad16662009-10-29 08:12:44 +00002355 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2356 << QualType(Tag, 0) << SR;
2357 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002358 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002359 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002360 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2361 return true;
Douglas Gregor959d5a02010-05-22 16:17:30 +00002362 } else if (Arg->isVariablyModifiedType()) {
2363 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2364 << Arg;
2365 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002366 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002367 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002368 }
2369
2370 return false;
2371}
2372
Douglas Gregorccb07762009-02-11 19:52:55 +00002373/// \brief Checks whether the given template argument is the address
2374/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002375static bool
2376CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2377 NonTypeTemplateParmDecl *Param,
2378 QualType ParamType,
2379 Expr *ArgIn,
2380 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002381 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002382 Expr *Arg = ArgIn;
2383 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002384
2385 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002386 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002387 Arg = Cast->getSubExpr();
2388
2389 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002390 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002391 // A template-argument for a non-type, non-template
2392 // template-parameter shall be one of: [...]
2393 //
2394 // -- the address of an object or function with external
2395 // linkage, including function templates and function
2396 // template-ids but excluding non-static class members,
2397 // expressed as & id-expression where the & is optional if
2398 // the name refers to a function or array, or if the
2399 // corresponding template-parameter is a reference; or
2400 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002401
Douglas Gregorccb07762009-02-11 19:52:55 +00002402 // Ignore (and complain about) any excess parentheses.
2403 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2404 if (!Invalid) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002405 S.Diag(Arg->getSourceRange().getBegin(),
2406 diag::err_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002407 << Arg->getSourceRange();
2408 Invalid = true;
2409 }
2410
2411 Arg = Parens->getSubExpr();
2412 }
2413
Douglas Gregorb242683d2010-04-01 18:32:35 +00002414 bool AddressTaken = false;
2415 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002416 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002417 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002418 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002419 AddressTaken = true;
2420 AddrOpLoc = UnOp->getOperatorLoc();
2421 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002422 } else
2423 DRE = dyn_cast<DeclRefExpr>(Arg);
2424
Douglas Gregorb242683d2010-04-01 18:32:35 +00002425 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002426 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2427 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002428 S.Diag(Param->getLocation(), diag::note_template_param_here);
2429 return true;
2430 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002431
2432 // Stop checking the precise nature of the argument if it is value dependent,
2433 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002434 if (Arg->isValueDependent()) {
2435 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002436 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002437 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002438
Douglas Gregorb242683d2010-04-01 18:32:35 +00002439 if (!isa<ValueDecl>(DRE->getDecl())) {
2440 S.Diag(Arg->getSourceRange().getBegin(),
2441 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002442 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002443 S.Diag(Param->getLocation(), diag::note_template_param_here);
2444 return true;
2445 }
2446
2447 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002448
2449 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002450 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2451 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002452 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002453 S.Diag(Param->getLocation(), diag::note_template_param_here);
2454 return true;
2455 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002456
2457 // Cannot refer to non-static member functions
2458 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002459 if (!Method->isStatic()) {
2460 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002461 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002462 S.Diag(Param->getLocation(), diag::note_template_param_here);
2463 return true;
2464 }
Mike Stump11289f42009-09-09 15:08:12 +00002465
Douglas Gregorccb07762009-02-11 19:52:55 +00002466 // Functions must have external linkage.
2467 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002468 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002469 S.Diag(Arg->getSourceRange().getBegin(),
2470 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002471 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002472 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002473 << true;
2474 return true;
2475 }
2476
2477 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002478 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002479
Douglas Gregorb242683d2010-04-01 18:32:35 +00002480 // If the template parameter has pointer type, the function decays.
2481 if (ParamType->isPointerType() && !AddressTaken)
2482 ArgType = S.Context.getPointerType(Func->getType());
2483 else if (AddressTaken && ParamType->isReferenceType()) {
2484 // If we originally had an address-of operator, but the
2485 // parameter has reference type, complain and (if things look
2486 // like they will work) drop the address-of operator.
2487 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2488 ParamType.getNonReferenceType())) {
2489 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2490 << ParamType;
2491 S.Diag(Param->getLocation(), diag::note_template_param_here);
2492 return true;
2493 }
2494
2495 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2496 << ParamType
2497 << FixItHint::CreateRemoval(AddrOpLoc);
2498 S.Diag(Param->getLocation(), diag::note_template_param_here);
2499
2500 ArgType = Func->getType();
2501 }
2502 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002503 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002504 S.Diag(Arg->getSourceRange().getBegin(),
2505 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002506 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002507 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002508 << true;
2509 return true;
2510 }
2511
Douglas Gregorb242683d2010-04-01 18:32:35 +00002512 // A value of reference type is not an object.
2513 if (Var->getType()->isReferenceType()) {
2514 S.Diag(Arg->getSourceRange().getBegin(),
2515 diag::err_template_arg_reference_var)
2516 << Var->getType() << Arg->getSourceRange();
2517 S.Diag(Param->getLocation(), diag::note_template_param_here);
2518 return true;
2519 }
2520
Douglas Gregorccb07762009-02-11 19:52:55 +00002521 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002522 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002523
2524 // If the template parameter has pointer type, we must have taken
2525 // the address of this object.
2526 if (ParamType->isReferenceType()) {
2527 if (AddressTaken) {
2528 // If we originally had an address-of operator, but the
2529 // parameter has reference type, complain and (if things look
2530 // like they will work) drop the address-of operator.
2531 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2532 ParamType.getNonReferenceType())) {
2533 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2534 << ParamType;
2535 S.Diag(Param->getLocation(), diag::note_template_param_here);
2536 return true;
2537 }
2538
2539 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2540 << ParamType
2541 << FixItHint::CreateRemoval(AddrOpLoc);
2542 S.Diag(Param->getLocation(), diag::note_template_param_here);
2543
2544 ArgType = Var->getType();
2545 }
2546 } else if (!AddressTaken && ParamType->isPointerType()) {
2547 if (Var->getType()->isArrayType()) {
2548 // Array-to-pointer decay.
2549 ArgType = S.Context.getArrayDecayedType(Var->getType());
2550 } else {
2551 // If the template parameter has pointer type but the address of
2552 // this object was not taken, complain and (possibly) recover by
2553 // taking the address of the entity.
2554 ArgType = S.Context.getPointerType(Var->getType());
2555 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2556 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2557 << ParamType;
2558 S.Diag(Param->getLocation(), diag::note_template_param_here);
2559 return true;
2560 }
2561
2562 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2563 << ParamType
2564 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2565
2566 S.Diag(Param->getLocation(), diag::note_template_param_here);
2567 }
2568 }
2569 } else {
2570 // We found something else, but we don't know specifically what it is.
2571 S.Diag(Arg->getSourceRange().getBegin(),
2572 diag::err_template_arg_not_object_or_func)
2573 << Arg->getSourceRange();
2574 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2575 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002576 }
Mike Stump11289f42009-09-09 15:08:12 +00002577
Douglas Gregorb242683d2010-04-01 18:32:35 +00002578 if (ParamType->isPointerType() &&
2579 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2580 S.IsQualificationConversion(ArgType, ParamType)) {
2581 // For pointer-to-object types, qualification conversions are
2582 // permitted.
2583 } else {
2584 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2585 if (!ParamRef->getPointeeType()->isFunctionType()) {
2586 // C++ [temp.arg.nontype]p5b3:
2587 // For a non-type template-parameter of type reference to
2588 // object, no conversions apply. The type referred to by the
2589 // reference may be more cv-qualified than the (otherwise
2590 // identical) type of the template- argument. The
2591 // template-parameter is bound directly to the
2592 // template-argument, which shall be an lvalue.
2593
2594 // FIXME: Other qualifiers?
2595 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2596 unsigned ArgQuals = ArgType.getCVRQualifiers();
2597
2598 if ((ParamQuals | ArgQuals) != ParamQuals) {
2599 S.Diag(Arg->getSourceRange().getBegin(),
2600 diag::err_template_arg_ref_bind_ignores_quals)
2601 << ParamType << Arg->getType()
2602 << Arg->getSourceRange();
2603 S.Diag(Param->getLocation(), diag::note_template_param_here);
2604 return true;
2605 }
2606 }
2607 }
2608
2609 // At this point, the template argument refers to an object or
2610 // function with external linkage. We now need to check whether the
2611 // argument and parameter types are compatible.
2612 if (!S.Context.hasSameUnqualifiedType(ArgType,
2613 ParamType.getNonReferenceType())) {
2614 // We can't perform this conversion or binding.
2615 if (ParamType->isReferenceType())
2616 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2617 << ParamType << Arg->getType() << Arg->getSourceRange();
2618 else
2619 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2620 << Arg->getType() << ParamType << Arg->getSourceRange();
2621 S.Diag(Param->getLocation(), diag::note_template_param_here);
2622 return true;
2623 }
2624 }
2625
2626 // Create the template argument.
2627 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002628 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002629 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002630}
2631
2632/// \brief Checks whether the given template argument is a pointer to
2633/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002634bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2635 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002636 bool Invalid = false;
2637
2638 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002639 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002640 Arg = Cast->getSubExpr();
2641
2642 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002643 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002644 // A template-argument for a non-type, non-template
2645 // template-parameter shall be one of: [...]
2646 //
2647 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002648 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002649
2650 // Ignore (and complain about) any excess parentheses.
2651 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2652 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002653 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002654 diag::err_template_arg_extra_parens)
2655 << Arg->getSourceRange();
2656 Invalid = true;
2657 }
2658
2659 Arg = Parens->getSubExpr();
2660 }
2661
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002662 // A pointer-to-member constant written &Class::member.
2663 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002664 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2665 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2666 if (DRE && !DRE->getQualifier())
2667 DRE = 0;
2668 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002669 }
2670 // A constant of pointer-to-member type.
2671 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2672 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2673 if (VD->getType()->isMemberPointerType()) {
2674 if (isa<NonTypeTemplateParmDecl>(VD) ||
2675 (isa<VarDecl>(VD) &&
2676 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2677 if (Arg->isTypeDependent() || Arg->isValueDependent())
2678 Converted = TemplateArgument(Arg->Retain());
2679 else
2680 Converted = TemplateArgument(VD->getCanonicalDecl());
2681 return Invalid;
2682 }
2683 }
2684 }
2685
2686 DRE = 0;
2687 }
2688
Douglas Gregorccb07762009-02-11 19:52:55 +00002689 if (!DRE)
2690 return Diag(Arg->getSourceRange().getBegin(),
2691 diag::err_template_arg_not_pointer_to_member_form)
2692 << Arg->getSourceRange();
2693
2694 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2695 assert((isa<FieldDecl>(DRE->getDecl()) ||
2696 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2697 "Only non-static member pointers can make it here");
2698
2699 // Okay: this is the address of a non-static member, and therefore
2700 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002701 if (Arg->isTypeDependent() || Arg->isValueDependent())
2702 Converted = TemplateArgument(Arg->Retain());
2703 else
2704 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002705 return Invalid;
2706 }
2707
2708 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002709 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002710 diag::err_template_arg_not_pointer_to_member_form)
2711 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002712 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002713 diag::note_template_arg_refers_here);
2714 return true;
2715}
2716
Douglas Gregord32e0282009-02-09 23:23:08 +00002717/// \brief Check a template argument against its corresponding
2718/// non-type template parameter.
2719///
Douglas Gregor463421d2009-03-03 04:44:36 +00002720/// This routine implements the semantics of C++ [temp.arg.nontype].
2721/// It returns true if an error occurred, and false otherwise. \p
2722/// InstantiatedParamType is the type of the non-type template
2723/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002724///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002725/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002726bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002727 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002728 TemplateArgument &Converted,
2729 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002730 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2731
Douglas Gregor86560402009-02-10 23:36:10 +00002732 // If either the parameter has a dependent type or the argument is
2733 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002734 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2735 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002736 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002737 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002738 }
Douglas Gregor86560402009-02-10 23:36:10 +00002739
2740 // C++ [temp.arg.nontype]p5:
2741 // The following conversions are performed on each expression used
2742 // as a non-type template-argument. If a non-type
2743 // template-argument cannot be converted to the type of the
2744 // corresponding template-parameter then the program is
2745 // ill-formed.
2746 //
2747 // -- for a non-type template-parameter of integral or
2748 // enumeration type, integral promotions (4.5) and integral
2749 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002750 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002751 QualType ArgType = Arg->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +00002752 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002753 // C++ [temp.arg.nontype]p1:
2754 // A template-argument for a non-type, non-template
2755 // template-parameter shall be one of:
2756 //
2757 // -- an integral constant-expression of integral or enumeration
2758 // type; or
2759 // -- the name of a non-type template-parameter; or
2760 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002761 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00002762 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002763 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002764 diag::err_template_arg_not_integral_or_enumeral)
2765 << ArgType << Arg->getSourceRange();
2766 Diag(Param->getLocation(), diag::note_template_param_here);
2767 return true;
2768 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002769 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002770 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2771 << ArgType << Arg->getSourceRange();
2772 return true;
2773 }
2774
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002775 // From here on out, all we care about are the unqualified forms
2776 // of the parameter and argument types.
2777 ParamType = ParamType.getUnqualifiedType();
2778 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00002779
2780 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002781 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002782 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002783 } else if (CTAK == CTAK_Deduced) {
2784 // C++ [temp.deduct.type]p17:
2785 // If, in the declaration of a function template with a non-type
2786 // template-parameter, the non-type template- parameter is used
2787 // in an expression in the function parameter-list and, if the
2788 // corresponding template-argument is deduced, the
2789 // template-argument type shall match the type of the
2790 // template-parameter exactly, except that a template-argument
2791 // deduced from an array bound may be of any integral type.
2792 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2793 << ArgType << ParamType;
2794 Diag(Param->getLocation(), diag::note_template_param_here);
2795 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00002796 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2797 !ParamType->isEnumeralType()) {
2798 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002799 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002800 } else {
2801 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002802 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002803 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002804 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002805 Diag(Param->getLocation(), diag::note_template_param_here);
2806 return true;
2807 }
2808
Douglas Gregor52aba872009-03-14 00:20:21 +00002809 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002810 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002811 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002812
2813 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002814 llvm::APSInt OldValue = Value;
2815
2816 // Coerce the template argument's value to the value it will have
2817 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002818 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002819 if (Value.getBitWidth() != AllowedBits)
2820 Value.extOrTrunc(AllowedBits);
2821 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002822
2823 // Complain if an unsigned parameter received a negative value.
2824 if (IntegerType->isUnsignedIntegerType()
2825 && (OldValue.isSigned() && OldValue.isNegative())) {
2826 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2827 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2828 << Arg->getSourceRange();
2829 Diag(Param->getLocation(), diag::note_template_param_here);
2830 }
2831
2832 // Complain if we overflowed the template parameter's type.
2833 unsigned RequiredBits;
2834 if (IntegerType->isUnsignedIntegerType())
2835 RequiredBits = OldValue.getActiveBits();
2836 else if (OldValue.isUnsigned())
2837 RequiredBits = OldValue.getActiveBits() + 1;
2838 else
2839 RequiredBits = OldValue.getMinSignedBits();
2840 if (RequiredBits > AllowedBits) {
2841 Diag(Arg->getSourceRange().getBegin(),
2842 diag::warn_template_arg_too_large)
2843 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2844 << Arg->getSourceRange();
2845 Diag(Param->getLocation(), diag::note_template_param_here);
2846 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002847 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002848
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002849 // Add the value of this argument to the list of converted
2850 // arguments. We use the bitwidth and signedness of the template
2851 // parameter.
2852 if (Arg->isValueDependent()) {
2853 // The argument is value-dependent. Create a new
2854 // TemplateArgument with the converted expression.
2855 Converted = TemplateArgument(Arg);
2856 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002857 }
2858
John McCall0ad16662009-10-29 08:12:44 +00002859 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002860 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002861 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002862 return false;
2863 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002864
John McCall16df1e52010-03-30 21:47:33 +00002865 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2866
Douglas Gregorb242683d2010-04-01 18:32:35 +00002867 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2868 // from a template argument of type std::nullptr_t to a non-type
2869 // template parameter of type pointer to object, pointer to
2870 // function, or pointer-to-member, respectively.
2871 if (ArgType->isNullPtrType() &&
2872 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2873 Converted = TemplateArgument((NamedDecl *)0);
2874 return false;
2875 }
2876
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002877 // Handle pointer-to-function, reference-to-function, and
2878 // pointer-to-member-function all in (roughly) the same way.
2879 if (// -- For a non-type template-parameter of type pointer to
2880 // function, only the function-to-pointer conversion (4.3) is
2881 // applied. If the template-argument represents a set of
2882 // overloaded functions (or a pointer to such), the matching
2883 // function is selected from the set (13.4).
2884 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002885 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002886 // -- For a non-type template-parameter of type reference to
2887 // function, no conversions apply. If the template-argument
2888 // represents a set of overloaded functions, the matching
2889 // function is selected from the set (13.4).
2890 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002891 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002892 // -- For a non-type template-parameter of type pointer to
2893 // member function, no conversions apply. If the
2894 // template-argument represents a set of overloaded member
2895 // functions, the matching member function is selected from
2896 // the set (13.4).
2897 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002898 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002899 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002900
Douglas Gregor064fdb22010-04-14 23:11:21 +00002901 if (Arg->getType() == Context.OverloadTy) {
2902 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2903 true,
2904 FoundResult)) {
2905 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2906 return true;
2907
2908 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2909 ArgType = Arg->getType();
2910 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00002911 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002912 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002913
Douglas Gregorb242683d2010-04-01 18:32:35 +00002914 if (!ParamType->isMemberPointerType())
2915 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2916 ParamType,
2917 Arg, Converted);
2918
2919 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002920 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp, CastCategory(Arg));
Douglas Gregorb242683d2010-04-01 18:32:35 +00002921 } else if (!Context.hasSameUnqualifiedType(ArgType,
2922 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002923 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002924 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002925 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002926 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002927 Diag(Param->getLocation(), diag::note_template_param_here);
2928 return true;
2929 }
Mike Stump11289f42009-09-09 15:08:12 +00002930
Douglas Gregorb242683d2010-04-01 18:32:35 +00002931 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002932 }
2933
Chris Lattner696197c2009-02-20 21:37:53 +00002934 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002935 // -- for a non-type template-parameter of type pointer to
2936 // object, qualification conversions (4.4) and the
2937 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002938 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00002939 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002940 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002941
Douglas Gregorb242683d2010-04-01 18:32:35 +00002942 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2943 ParamType,
2944 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00002945 }
Mike Stump11289f42009-09-09 15:08:12 +00002946
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002947 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002948 // -- For a non-type template-parameter of type reference to
2949 // object, no conversions apply. The type referred to by the
2950 // reference may be more cv-qualified than the (otherwise
2951 // identical) type of the template-argument. The
2952 // template-parameter is bound directly to the
2953 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00002954 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002955 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002956
Douglas Gregor064fdb22010-04-14 23:11:21 +00002957 if (Arg->getType() == Context.OverloadTy) {
2958 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2959 ParamRefType->getPointeeType(),
2960 true,
2961 FoundResult)) {
2962 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2963 return true;
2964
2965 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2966 ArgType = Arg->getType();
2967 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00002968 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002969 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002970
Douglas Gregorb242683d2010-04-01 18:32:35 +00002971 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2972 ParamType,
2973 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002974 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002975
2976 // -- For a non-type template-parameter of type pointer to data
2977 // member, qualification conversions (4.4) are applied.
2978 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2979
Douglas Gregor1515f762009-02-11 18:22:40 +00002980 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002981 // Types match exactly: nothing more to do here.
2982 } else if (IsQualificationConversion(ArgType, ParamType)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002983 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp, CastCategory(Arg));
Douglas Gregor0e558532009-02-11 16:16:59 +00002984 } else {
2985 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002986 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002987 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002988 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002989 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002990 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002991 }
2992
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002993 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002994}
2995
2996/// \brief Check a template argument against its corresponding
2997/// template template parameter.
2998///
2999/// This routine implements the semantics of C++ [temp.arg.template].
3000/// It returns true if an error occurred, and false otherwise.
3001bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003002 const TemplateArgumentLoc &Arg) {
3003 TemplateName Name = Arg.getArgument().getAsTemplate();
3004 TemplateDecl *Template = Name.getAsTemplateDecl();
3005 if (!Template) {
3006 // Any dependent template name is fine.
3007 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3008 return false;
3009 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003010
3011 // C++ [temp.arg.template]p1:
3012 // A template-argument for a template template-parameter shall be
3013 // the name of a class template, expressed as id-expression. Only
3014 // primary class templates are considered when matching the
3015 // template template argument with the corresponding parameter;
3016 // partial specializations are not considered even if their
3017 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003018 //
3019 // Note that we also allow template template parameters here, which
3020 // will happen when we are dealing with, e.g., class template
3021 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003022 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003023 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003024 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003025 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003026 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003027 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003028 << Template;
3029 }
3030
3031 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3032 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003033 true,
3034 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003035 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003036}
3037
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003038/// \brief Given a non-type template argument that refers to a
3039/// declaration and the type of its corresponding non-type template
3040/// parameter, produce an expression that properly refers to that
3041/// declaration.
John McCalldadc5752010-08-24 06:29:42 +00003042ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003043Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3044 QualType ParamType,
3045 SourceLocation Loc) {
3046 assert(Arg.getKind() == TemplateArgument::Declaration &&
3047 "Only declaration template arguments permitted here");
3048 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3049
3050 if (VD->getDeclContext()->isRecord() &&
3051 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3052 // If the value is a class member, we might have a pointer-to-member.
3053 // Determine whether the non-type template template parameter is of
3054 // pointer-to-member type. If so, we need to build an appropriate
3055 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3056 // would refer to the member itself.
3057 if (ParamType->isMemberPointerType()) {
3058 QualType ClassType
3059 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3060 NestedNameSpecifier *Qualifier
John McCallb268a282010-08-23 23:25:46 +00003061 = NestedNameSpecifier::Create(Context, 0, false,
3062 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003063 CXXScopeSpec SS;
3064 SS.setScopeRep(Qualifier);
John McCalldadc5752010-08-24 06:29:42 +00003065 ExprResult RefExpr = BuildDeclRefExpr(VD,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003066 VD->getType().getNonReferenceType(),
3067 Loc,
3068 &SS);
3069 if (RefExpr.isInvalid())
3070 return ExprError();
3071
John McCallb268a282010-08-23 23:25:46 +00003072 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, RefExpr.get());
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003073
3074 // We might need to perform a trailing qualification conversion, since
3075 // the element type on the parameter could be more qualified than the
3076 // element type in the expression we constructed.
3077 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3078 ParamType.getUnqualifiedType())) {
3079 Expr *RefE = RefExpr.takeAs<Expr>();
3080 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(),
3081 CastExpr::CK_NoOp);
3082 RefExpr = Owned(RefE);
3083 }
3084
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003085 assert(!RefExpr.isInvalid() &&
3086 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003087 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003088 return move(RefExpr);
3089 }
3090 }
3091
3092 QualType T = VD->getType().getNonReferenceType();
3093 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003094 // When the non-type template parameter is a pointer, take the
3095 // address of the declaration.
John McCalldadc5752010-08-24 06:29:42 +00003096 ExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003097 if (RefExpr.isInvalid())
3098 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003099
3100 if (T->isFunctionType() || T->isArrayType()) {
3101 // Decay functions and arrays.
3102 Expr *RefE = (Expr *)RefExpr.get();
3103 DefaultFunctionArrayConversion(RefE);
3104 if (RefE != RefExpr.get()) {
3105 RefExpr.release();
3106 RefExpr = Owned(RefE);
3107 }
3108
3109 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003110 }
3111
Douglas Gregorb242683d2010-04-01 18:32:35 +00003112 // Take the address of everything else
John McCallb268a282010-08-23 23:25:46 +00003113 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003114 }
3115
3116 // If the non-type template parameter has reference type, qualify the
3117 // resulting declaration reference with the extra qualifiers on the
3118 // type that the reference refers to.
3119 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3120 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3121
3122 return BuildDeclRefExpr(VD, T, Loc);
3123}
3124
3125/// \brief Construct a new expression that refers to the given
3126/// integral template argument with the given source-location
3127/// information.
3128///
3129/// This routine takes care of the mapping from an integral template
3130/// argument (which may have any integral type) to the appropriate
3131/// literal value.
John McCalldadc5752010-08-24 06:29:42 +00003132ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003133Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3134 SourceLocation Loc) {
3135 assert(Arg.getKind() == TemplateArgument::Integral &&
3136 "Operation is only value for integral template arguments");
3137 QualType T = Arg.getIntegralType();
3138 if (T->isCharType() || T->isWideCharType())
3139 return Owned(new (Context) CharacterLiteral(
3140 Arg.getAsIntegral()->getZExtValue(),
3141 T->isWideCharType(),
3142 T,
3143 Loc));
3144 if (T->isBooleanType())
3145 return Owned(new (Context) CXXBoolLiteralExpr(
3146 Arg.getAsIntegral()->getBoolValue(),
3147 T,
3148 Loc));
3149
3150 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3151}
3152
3153
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003154/// \brief Determine whether the given template parameter lists are
3155/// equivalent.
3156///
Mike Stump11289f42009-09-09 15:08:12 +00003157/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003158/// source code as part of a new template declaration.
3159///
3160/// \param Old The old template parameter list, typically found via
3161/// name lookup of the template declared with this template parameter
3162/// list.
3163///
3164/// \param Complain If true, this routine will produce a diagnostic if
3165/// the template parameter lists are not equivalent.
3166///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003167/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003168///
3169/// \param TemplateArgLoc If this source location is valid, then we
3170/// are actually checking the template parameter list of a template
3171/// argument (New) against the template parameter list of its
3172/// corresponding template template parameter (Old). We produce
3173/// slightly different diagnostics in this scenario.
3174///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003175/// \returns True if the template parameter lists are equal, false
3176/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003177bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003178Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3179 TemplateParameterList *Old,
3180 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003181 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003182 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003183 if (Old->size() != New->size()) {
3184 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003185 unsigned NextDiag = diag::err_template_param_list_different_arity;
3186 if (TemplateArgLoc.isValid()) {
3187 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3188 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003189 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003190 Diag(New->getTemplateLoc(), NextDiag)
3191 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003192 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003193 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003194 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003195 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003196 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3197 }
3198
3199 return false;
3200 }
3201
3202 for (TemplateParameterList::iterator OldParm = Old->begin(),
3203 OldParmEnd = Old->end(), NewParm = New->begin();
3204 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3205 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003206 if (Complain) {
3207 unsigned NextDiag = diag::err_template_param_different_kind;
3208 if (TemplateArgLoc.isValid()) {
3209 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3210 NextDiag = diag::note_template_param_different_kind;
3211 }
3212 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003213 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003214 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003215 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003216 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003217 return false;
3218 }
3219
Douglas Gregor2e87ca22010-06-04 08:34:32 +00003220 if (TemplateTypeParmDecl *OldTTP
3221 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3222 // Template type parameters are equivalent if either both are template
3223 // type parameter packs or neither are (since we know we're at the same
3224 // index).
3225 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3226 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3227 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3228 // allow one to match a template parameter pack in the template
3229 // parameter list of a template template parameter to one or more
3230 // template parameters in the template parameter list of the
3231 // corresponding template template argument.
3232 if (Complain) {
3233 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3234 if (TemplateArgLoc.isValid()) {
3235 Diag(TemplateArgLoc,
3236 diag::err_template_arg_template_params_mismatch);
3237 NextDiag = diag::note_template_parameter_pack_non_pack;
3238 }
3239 Diag(NewTTP->getLocation(), NextDiag)
3240 << 0 << NewTTP->isParameterPack();
3241 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3242 << 0 << OldTTP->isParameterPack();
3243 }
3244 return false;
3245 }
Mike Stump11289f42009-09-09 15:08:12 +00003246 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003247 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3248 // The types of non-type template parameters must agree.
3249 NonTypeTemplateParmDecl *NewNTTP
3250 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003251
3252 // If we are matching a template template argument to a template
3253 // template parameter and one of the non-type template parameter types
3254 // is dependent, then we must wait until template instantiation time
3255 // to actually compare the arguments.
3256 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3257 (OldNTTP->getType()->isDependentType() ||
3258 NewNTTP->getType()->isDependentType()))
3259 continue;
3260
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003261 if (Context.getCanonicalType(OldNTTP->getType()) !=
3262 Context.getCanonicalType(NewNTTP->getType())) {
3263 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003264 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3265 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003266 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003267 diag::err_template_arg_template_params_mismatch);
3268 NextDiag = diag::note_template_nontype_parm_different_type;
3269 }
3270 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003271 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003272 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003273 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003274 diag::note_template_nontype_parm_prev_declaration)
3275 << OldNTTP->getType();
3276 }
3277 return false;
3278 }
3279 } else {
3280 // The template parameter lists of template template
3281 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003282 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003283 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003284 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003285 = cast<TemplateTemplateParmDecl>(*OldParm);
3286 TemplateTemplateParmDecl *NewTTP
3287 = cast<TemplateTemplateParmDecl>(*NewParm);
3288 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3289 OldTTP->getTemplateParameters(),
3290 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003291 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003292 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003293 return false;
3294 }
3295 }
3296
3297 return true;
3298}
3299
3300/// \brief Check whether a template can be declared within this scope.
3301///
3302/// If the template declaration is valid in this scope, returns
3303/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003304bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003305Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003306 // Find the nearest enclosing declaration scope.
3307 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3308 (S->getFlags() & Scope::TemplateParamScope) != 0)
3309 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003310
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003311 // C++ [temp]p2:
3312 // A template-declaration can appear only as a namespace scope or
3313 // class scope declaration.
3314 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003315 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3316 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003317 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003318 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003319
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003320 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003321 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003322
3323 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3324 return false;
3325
Mike Stump11289f42009-09-09 15:08:12 +00003326 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003327 diag::err_template_outside_namespace_or_class_scope)
3328 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003329}
Douglas Gregor67a65642009-02-17 23:15:12 +00003330
Douglas Gregor54888652009-10-07 00:13:32 +00003331/// \brief Determine what kind of template specialization the given declaration
3332/// is.
3333static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3334 if (!D)
3335 return TSK_Undeclared;
3336
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003337 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3338 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003339 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3340 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003341 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3342 return Var->getTemplateSpecializationKind();
3343
Douglas Gregor54888652009-10-07 00:13:32 +00003344 return TSK_Undeclared;
3345}
3346
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003347/// \brief Check whether a specialization is well-formed in the current
3348/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003349///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003350/// This routine determines whether a template specialization can be declared
3351/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003352///
3353/// \param S the semantic analysis object for which this check is being
3354/// performed.
3355///
3356/// \param Specialized the entity being specialized or instantiated, which
3357/// may be a kind of template (class template, function template, etc.) or
3358/// a member of a class template (member function, static data member,
3359/// member class).
3360///
3361/// \param PrevDecl the previous declaration of this entity, if any.
3362///
3363/// \param Loc the location of the explicit specialization or instantiation of
3364/// this entity.
3365///
3366/// \param IsPartialSpecialization whether this is a partial specialization of
3367/// a class template.
3368///
Douglas Gregor54888652009-10-07 00:13:32 +00003369/// \returns true if there was an error that we cannot recover from, false
3370/// otherwise.
3371static bool CheckTemplateSpecializationScope(Sema &S,
3372 NamedDecl *Specialized,
3373 NamedDecl *PrevDecl,
3374 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003375 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003376 // Keep these "kind" numbers in sync with the %select statements in the
3377 // various diagnostics emitted by this routine.
3378 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003379 bool isTemplateSpecialization = false;
3380 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003381 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003382 isTemplateSpecialization = true;
3383 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003384 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003385 isTemplateSpecialization = true;
3386 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003387 EntityKind = 3;
3388 else if (isa<VarDecl>(Specialized))
3389 EntityKind = 4;
3390 else if (isa<RecordDecl>(Specialized))
3391 EntityKind = 5;
3392 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003393 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3394 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003395 return true;
3396 }
3397
Douglas Gregorf47b9112009-02-25 22:02:03 +00003398 // C++ [temp.expl.spec]p2:
3399 // An explicit specialization shall be declared in the namespace
3400 // of which the template is a member, or, for member templates, in
3401 // the namespace of which the enclosing class or enclosing class
3402 // template is a member. An explicit specialization of a member
3403 // function, member class or static data member of a class
3404 // template shall be declared in the namespace of which the class
3405 // template is a member. Such a declaration may also be a
3406 // definition. If the declaration is not a definition, the
3407 // specialization may be defined later in the name- space in which
3408 // the explicit specialization was declared, or in a namespace
3409 // that encloses the one in which the explicit specialization was
3410 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003411 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3412 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003413 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003414 return true;
3415 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003416
Douglas Gregor40fb7442009-10-07 17:30:37 +00003417 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3418 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003419 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003420 return true;
3421 }
3422
Douglas Gregore4b05162009-10-07 17:21:34 +00003423 // C++ [temp.class.spec]p6:
3424 // A class template partial specialization may be declared or redeclared
3425 // in any namespace scope in which its definition may be defined (14.5.1
3426 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003427 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003428 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003429 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003430 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003431 if ((!PrevDecl ||
3432 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3433 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3434 // There is no prior declaration of this entity, so this
3435 // specialization must be in the same context as the template
3436 // itself.
3437 if (!DC->Equals(SpecializedContext)) {
3438 if (isa<TranslationUnitDecl>(SpecializedContext))
3439 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3440 << EntityKind << Specialized;
3441 else if (isa<NamespaceDecl>(SpecializedContext))
3442 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3443 << EntityKind << Specialized
3444 << cast<NamedDecl>(SpecializedContext);
3445
3446 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3447 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003448 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003449 }
Douglas Gregor54888652009-10-07 00:13:32 +00003450
3451 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003452 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003453 // Note that HandleDeclarator() performs this check for explicit
3454 // specializations of function templates, static data members, and member
3455 // functions, so we skip the check here for those kinds of entities.
3456 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003457 // Should we refactor that check, so that it occurs later?
3458 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003459 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3460 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003461 if (isa<TranslationUnitDecl>(SpecializedContext))
3462 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3463 << EntityKind << Specialized;
3464 else if (isa<NamespaceDecl>(SpecializedContext))
3465 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3466 << EntityKind << Specialized
3467 << cast<NamedDecl>(SpecializedContext);
3468
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003469 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003470 }
Douglas Gregor54888652009-10-07 00:13:32 +00003471
3472 // FIXME: check for specialization-after-instantiation errors and such.
3473
Douglas Gregorf47b9112009-02-25 22:02:03 +00003474 return false;
3475}
Douglas Gregor54888652009-10-07 00:13:32 +00003476
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003477/// \brief Check the non-type template arguments of a class template
3478/// partial specialization according to C++ [temp.class.spec]p9.
3479///
Douglas Gregor09a30232009-06-12 22:08:06 +00003480/// \param TemplateParams the template parameters of the primary class
3481/// template.
3482///
3483/// \param TemplateArg the template arguments of the class template
3484/// partial specialization.
3485///
3486/// \param MirrorsPrimaryTemplate will be set true if the class
3487/// template partial specialization arguments are identical to the
3488/// implicit template arguments of the primary template. This is not
3489/// necessarily an error (C++0x), and it is left to the caller to diagnose
3490/// this condition when it is an error.
3491///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003492/// \returns true if there was an error, false otherwise.
3493bool Sema::CheckClassTemplatePartialSpecializationArgs(
3494 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003495 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003496 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003497 // FIXME: the interface to this function will have to change to
3498 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003499 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003500
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003501 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003502
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003503 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003504 // Determine whether the template argument list of the partial
3505 // specialization is identical to the implicit argument list of
3506 // the primary template. The caller may need to diagnostic this as
3507 // an error per C++ [temp.class.spec]p9b3.
3508 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003509 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003510 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3511 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003512 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003513 MirrorsPrimaryTemplate = false;
3514 } else if (TemplateTemplateParmDecl *TTP
3515 = dyn_cast<TemplateTemplateParmDecl>(
3516 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003517 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003518 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003519 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003520 if (!ArgDecl ||
3521 ArgDecl->getIndex() != TTP->getIndex() ||
3522 ArgDecl->getDepth() != TTP->getDepth())
3523 MirrorsPrimaryTemplate = false;
3524 }
3525 }
3526
Mike Stump11289f42009-09-09 15:08:12 +00003527 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003528 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003529 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003530 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003531 }
3532
Anders Carlsson40c1d492009-06-13 18:20:51 +00003533 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003534 if (!ArgExpr) {
3535 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003536 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003537 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003538
3539 // C++ [temp.class.spec]p8:
3540 // A non-type argument is non-specialized if it is the name of a
3541 // non-type parameter. All other non-type arguments are
3542 // specialized.
3543 //
3544 // Below, we check the two conditions that only apply to
3545 // specialized non-type arguments, so skip any non-specialized
3546 // arguments.
3547 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003548 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003549 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003550 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003551 (Param->getIndex() != NTTP->getIndex() ||
3552 Param->getDepth() != NTTP->getDepth()))
3553 MirrorsPrimaryTemplate = false;
3554
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003555 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003556 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003557
3558 // C++ [temp.class.spec]p9:
3559 // Within the argument list of a class template partial
3560 // specialization, the following restrictions apply:
3561 // -- A partially specialized non-type argument expression
3562 // shall not involve a template parameter of the partial
3563 // specialization except when the argument expression is a
3564 // simple identifier.
3565 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003566 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003567 diag::err_dependent_non_type_arg_in_partial_spec)
3568 << ArgExpr->getSourceRange();
3569 return true;
3570 }
3571
3572 // -- The type of a template parameter corresponding to a
3573 // specialized non-type argument shall not be dependent on a
3574 // parameter of the specialization.
3575 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003576 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003577 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3578 << Param->getType()
3579 << ArgExpr->getSourceRange();
3580 Diag(Param->getLocation(), diag::note_template_param_here);
3581 return true;
3582 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003583
3584 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003585 }
3586
3587 return false;
3588}
3589
Douglas Gregorc854c662010-02-26 06:03:23 +00003590/// \brief Retrieve the previous declaration of the given declaration.
3591static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3592 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3593 return VD->getPreviousDeclaration();
3594 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3595 return FD->getPreviousDeclaration();
3596 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3597 return TD->getPreviousDeclaration();
3598 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3599 return TD->getPreviousDeclaration();
3600 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3601 return FTD->getPreviousDeclaration();
3602 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3603 return CTD->getPreviousDeclaration();
3604 return 0;
3605}
3606
John McCall48871652010-08-21 09:40:31 +00003607DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003608Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3609 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003610 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003611 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003612 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003613 SourceLocation TemplateNameLoc,
3614 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003615 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003616 SourceLocation RAngleLoc,
3617 AttributeList *Attr,
3618 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003619 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003620
Douglas Gregor67a65642009-02-17 23:15:12 +00003621 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003622 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003623 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003624 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3625
3626 if (!ClassTemplate) {
3627 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3628 << (Name.getAsTemplateDecl() &&
3629 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3630 return true;
3631 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003632
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003633 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003634 bool isPartialSpecialization = false;
3635
Douglas Gregorf47b9112009-02-25 22:02:03 +00003636 // Check the validity of the template headers that introduce this
3637 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003638 // FIXME: We probably shouldn't complain about these headers for
3639 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003640 bool Invalid = false;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003641 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003642 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3643 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003644 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003645 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003646 isExplicitSpecialization,
3647 Invalid);
3648 if (Invalid)
3649 return true;
3650
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003651 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3652 if (TemplateParams)
3653 --NumMatchedTemplateParamLists;
3654
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003655 if (TemplateParams && TemplateParams->size() > 0) {
3656 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003657
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003658 // C++ [temp.class.spec]p10:
3659 // The template parameter list of a specialization shall not
3660 // contain default template argument values.
3661 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3662 Decl *Param = TemplateParams->getParam(I);
3663 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3664 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003665 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003666 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003667 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003668 }
3669 } else if (NonTypeTemplateParmDecl *NTTP
3670 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3671 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003672 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003673 diag::err_default_arg_in_partial_spec)
3674 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003675 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003676 }
3677 } else {
3678 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003679 if (TTP->hasDefaultArgument()) {
3680 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003681 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003682 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003683 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00003684 }
3685 }
3686 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003687 } else if (TemplateParams) {
3688 if (TUK == TUK_Friend)
3689 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003690 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003691 SourceRange(TemplateParams->getTemplateLoc(),
3692 TemplateParams->getRAngleLoc()))
3693 << SourceRange(LAngleLoc, RAngleLoc);
3694 else
3695 isExplicitSpecialization = true;
3696 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003697 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003698 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003699 isExplicitSpecialization = true;
3700 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003701
Douglas Gregor67a65642009-02-17 23:15:12 +00003702 // Check that the specialization uses the same tag kind as the
3703 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003704 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3705 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00003706 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003707 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003708 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003709 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003710 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003711 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003712 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003713 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003714 diag::note_previous_use);
3715 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3716 }
3717
Douglas Gregorc40290e2009-03-09 23:48:35 +00003718 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003719 TemplateArgumentListInfo TemplateArgs;
3720 TemplateArgs.setLAngleLoc(LAngleLoc);
3721 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003722 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003723
Douglas Gregor67a65642009-02-17 23:15:12 +00003724 // Check that the template argument list is well-formed for this
3725 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003726 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3727 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003728 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3729 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003730 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003731
Mike Stump11289f42009-09-09 15:08:12 +00003732 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003733 ClassTemplate->getTemplateParameters()->size()) &&
3734 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003735
Douglas Gregor2373c592009-05-31 09:31:02 +00003736 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003737 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00003738 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003739 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003740 if (CheckClassTemplatePartialSpecializationArgs(
3741 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003742 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003743 return true;
3744
Douglas Gregor09a30232009-06-12 22:08:06 +00003745 if (MirrorsPrimaryTemplate) {
3746 // C++ [temp.class.spec]p9b3:
3747 //
Mike Stump11289f42009-09-09 15:08:12 +00003748 // -- The argument list of the specialization shall not be identical
3749 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003750 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003751 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003752 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003753 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003754 ClassTemplate->getIdentifier(),
3755 TemplateNameLoc,
3756 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003757 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003758 AS_none);
3759 }
3760
Douglas Gregor2208a292009-09-26 20:57:03 +00003761 // FIXME: Diagnose friend partial specializations
3762
Douglas Gregor92354b62010-02-09 00:37:32 +00003763 if (!Name.isDependent() &&
3764 !TemplateSpecializationType::anyDependentTemplateArguments(
3765 TemplateArgs.getArgumentArray(),
3766 TemplateArgs.size())) {
3767 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3768 << ClassTemplate->getDeclName();
3769 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00003770 }
3771 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003772
Douglas Gregor67a65642009-02-17 23:15:12 +00003773 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003774 ClassTemplateSpecializationDecl *PrevDecl = 0;
3775
3776 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003777 // FIXME: Template parameter list matters, too
Douglas Gregor2373c592009-05-31 09:31:02 +00003778 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003779 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
3780 Converted.flatSize(),
3781 InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00003782 else
3783 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003784 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
3785 Converted.flatSize(), InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003786
3787 ClassTemplateSpecializationDecl *Specialization = 0;
3788
Douglas Gregorf47b9112009-02-25 22:02:03 +00003789 // Check whether we can declare a class template specialization in
3790 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003791 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003792 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003793 TemplateNameLoc,
3794 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003795 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003796
Douglas Gregor15301382009-07-30 17:40:51 +00003797 // The canonical type
3798 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003799 if (PrevDecl &&
3800 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003801 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003802 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003803 // arguments was referenced but not declared, or we're only
3804 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003805 // declaration node as our own, updating its source location to
3806 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003807 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003808 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003809 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003810 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003811 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003812 // Build the canonical type that describes the converted template
3813 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003814 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3815 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003816 Converted.getFlatArguments(),
3817 Converted.flatSize());
3818
Douglas Gregor2373c592009-05-31 09:31:02 +00003819 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003820 ClassTemplatePartialSpecializationDecl *PrevPartial
3821 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00003822 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003823 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump11289f42009-09-09 15:08:12 +00003824 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00003825 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00003826 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003827 TemplateNameLoc,
3828 TemplateParams,
3829 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003830 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003831 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003832 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00003833 PrevPartial,
3834 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00003835 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00003836 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003837 Partial->setTemplateParameterListsInfo(Context,
3838 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003839 (TemplateParameterList**) TemplateParameterLists.release());
3840 }
Douglas Gregor2373c592009-05-31 09:31:02 +00003841
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003842 if (!PrevPartial)
3843 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00003844 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003845
Douglas Gregor21610382009-10-29 00:04:11 +00003846 // If we are providing an explicit specialization of a member class
3847 // template specialization, make a note of that.
3848 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3849 PrevPartial->setMemberSpecialization();
3850
Douglas Gregor91772d12009-06-13 00:26:55 +00003851 // Check that all of the template parameters of the class template
3852 // partial specialization are deducible from the template
3853 // arguments. If not, this class template partial specialization
3854 // will never be used.
3855 llvm::SmallVector<bool, 8> DeducibleParams;
3856 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003857 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003858 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003859 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003860 unsigned NumNonDeducible = 0;
3861 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3862 if (!DeducibleParams[I])
3863 ++NumNonDeducible;
3864
3865 if (NumNonDeducible) {
3866 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3867 << (NumNonDeducible > 1)
3868 << SourceRange(TemplateNameLoc, RAngleLoc);
3869 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3870 if (!DeducibleParams[I]) {
3871 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3872 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003873 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003874 diag::note_partial_spec_unused_parameter)
3875 << Param->getDeclName();
3876 else
Mike Stump11289f42009-09-09 15:08:12 +00003877 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003878 diag::note_partial_spec_unused_parameter)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003879 << "<anonymous>";
Douglas Gregor91772d12009-06-13 00:26:55 +00003880 }
3881 }
3882 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003883 } else {
3884 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003885 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003886 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00003887 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00003888 ClassTemplate->getDeclContext(),
3889 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003890 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003891 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003892 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00003893 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00003894 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003895 Specialization->setTemplateParameterListsInfo(Context,
3896 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003897 (TemplateParameterList**) TemplateParameterLists.release());
3898 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003899
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003900 if (!PrevDecl)
3901 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00003902
3903 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003904 }
3905
Douglas Gregor06db9f52009-10-12 20:18:28 +00003906 // C++ [temp.expl.spec]p6:
3907 // If a template, a member template or the member of a class template is
3908 // explicitly specialized then that specialization shall be declared
3909 // before the first use of that specialization that would cause an implicit
3910 // instantiation to take place, in every translation unit in which such a
3911 // use occurs; no diagnostic is required.
3912 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003913 bool Okay = false;
3914 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3915 // Is there any previous explicit specialization declaration?
3916 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3917 Okay = true;
3918 break;
3919 }
3920 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003921
Douglas Gregorc854c662010-02-26 06:03:23 +00003922 if (!Okay) {
3923 SourceRange Range(TemplateNameLoc, RAngleLoc);
3924 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3925 << Context.getTypeDeclType(Specialization) << Range;
3926
3927 Diag(PrevDecl->getPointOfInstantiation(),
3928 diag::note_instantiation_required_here)
3929 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003930 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003931 return true;
3932 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003933 }
3934
Douglas Gregor2208a292009-09-26 20:57:03 +00003935 // If this is not a friend, note that this is an explicit specialization.
3936 if (TUK != TUK_Friend)
3937 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003938
3939 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003940 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003941 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003942 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003943 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003944 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003945 Diag(Def->getLocation(), diag::note_previous_definition);
3946 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003947 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003948 }
3949 }
3950
Douglas Gregord56a91e2009-02-26 22:19:44 +00003951 // Build the fully-sugared type for this class template
3952 // specialization as the user wrote in the specialization
3953 // itself. This means that we'll pretty-print the type retrieved
3954 // from the specialization's declaration the way that the user
3955 // actually wrote the specialization, rather than formatting the
3956 // name based on the "canonical" representation used to store the
3957 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003958 TypeSourceInfo *WrittenTy
3959 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3960 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00003961 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003962 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregord890b732010-07-06 18:33:12 +00003963 if (TemplateParams)
3964 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnara8075c852010-06-12 07:44:57 +00003965 }
Douglas Gregorc40290e2009-03-09 23:48:35 +00003966 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003967
Douglas Gregor1e249f82009-02-25 22:18:32 +00003968 // C++ [temp.expl.spec]p9:
3969 // A template explicit specialization is in the scope of the
3970 // namespace in which the template was defined.
3971 //
3972 // We actually implement this paragraph where we set the semantic
3973 // context (in the creation of the ClassTemplateSpecializationDecl),
3974 // but we also maintain the lexical context where the actual
3975 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003976 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003977
Douglas Gregor67a65642009-02-17 23:15:12 +00003978 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003979 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003980 Specialization->startDefinition();
3981
Douglas Gregor2208a292009-09-26 20:57:03 +00003982 if (TUK == TUK_Friend) {
3983 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3984 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00003985 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00003986 /*FIXME:*/KWLoc);
3987 Friend->setAccess(AS_public);
3988 CurContext->addDecl(Friend);
3989 } else {
3990 // Add the specialization into its lexical context, so that it can
3991 // be seen when iterating through the list of declarations in that
3992 // context. However, specializations are not found by name lookup.
3993 CurContext->addDecl(Specialization);
3994 }
John McCall48871652010-08-21 09:40:31 +00003995 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00003996}
Douglas Gregor333489b2009-03-27 23:10:48 +00003997
John McCall48871652010-08-21 09:40:31 +00003998Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003999 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004000 Declarator &D) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004001 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4002}
4003
John McCall48871652010-08-21 09:40:31 +00004004Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004005 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004006 Declarator &D) {
Douglas Gregor17a7c122009-06-24 00:54:41 +00004007 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4008 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4009 "Not a function declarator!");
4010 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00004011
Douglas Gregor17a7c122009-06-24 00:54:41 +00004012 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004013 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004014 }
Mike Stump11289f42009-09-09 15:08:12 +00004015
Douglas Gregor17a7c122009-06-24 00:54:41 +00004016 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004017
John McCall48871652010-08-21 09:40:31 +00004018 Decl *DP = HandleDeclarator(ParentScope, D,
4019 move(TemplateParameterLists),
4020 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004021 if (FunctionTemplateDecl *FunctionTemplate
John McCall48871652010-08-21 09:40:31 +00004022 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump11289f42009-09-09 15:08:12 +00004023 return ActOnStartOfFunctionDef(FnBodyScope,
John McCall48871652010-08-21 09:40:31 +00004024 FunctionTemplate->getTemplatedDecl());
4025 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4026 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4027 return 0;
Douglas Gregor17a7c122009-06-24 00:54:41 +00004028}
4029
John McCall4f7ced62010-02-11 01:33:53 +00004030/// \brief Strips various properties off an implicit instantiation
4031/// that has just been explicitly specialized.
4032static void StripImplicitInstantiation(NamedDecl *D) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004033 D->dropAttrs();
John McCall4f7ced62010-02-11 01:33:53 +00004034
4035 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4036 FD->setInlineSpecified(false);
4037 }
4038}
4039
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004040/// \brief Diagnose cases where we have an explicit template specialization
4041/// before/after an explicit template instantiation, producing diagnostics
4042/// for those cases where they are required and determining whether the
4043/// new specialization/instantiation will have any effect.
4044///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004045/// \param NewLoc the location of the new explicit specialization or
4046/// instantiation.
4047///
4048/// \param NewTSK the kind of the new explicit specialization or instantiation.
4049///
4050/// \param PrevDecl the previous declaration of the entity.
4051///
4052/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4053///
4054/// \param PrevPointOfInstantiation if valid, indicates where the previus
4055/// declaration was instantiated (either implicitly or explicitly).
4056///
Abramo Bagnara8075c852010-06-12 07:44:57 +00004057/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004058/// specialization or instantiation has no effect and should be ignored.
4059///
4060/// \returns true if there was an error that should prevent the introduction of
4061/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004062bool
4063Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4064 TemplateSpecializationKind NewTSK,
4065 NamedDecl *PrevDecl,
4066 TemplateSpecializationKind PrevTSK,
4067 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004068 bool &HasNoEffect) {
4069 HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004070
4071 switch (NewTSK) {
4072 case TSK_Undeclared:
4073 case TSK_ImplicitInstantiation:
4074 assert(false && "Don't check implicit instantiations here");
4075 return false;
4076
4077 case TSK_ExplicitSpecialization:
4078 switch (PrevTSK) {
4079 case TSK_Undeclared:
4080 case TSK_ExplicitSpecialization:
4081 // Okay, we're just specializing something that is either already
4082 // explicitly specialized or has merely been mentioned without any
4083 // instantiation.
4084 return false;
4085
4086 case TSK_ImplicitInstantiation:
4087 if (PrevPointOfInstantiation.isInvalid()) {
4088 // The declaration itself has not actually been instantiated, so it is
4089 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004090 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004091 return false;
4092 }
4093 // Fall through
4094
4095 case TSK_ExplicitInstantiationDeclaration:
4096 case TSK_ExplicitInstantiationDefinition:
4097 assert((PrevTSK == TSK_ImplicitInstantiation ||
4098 PrevPointOfInstantiation.isValid()) &&
4099 "Explicit instantiation without point of instantiation?");
4100
4101 // C++ [temp.expl.spec]p6:
4102 // If a template, a member template or the member of a class template
4103 // is explicitly specialized then that specialization shall be declared
4104 // before the first use of that specialization that would cause an
4105 // implicit instantiation to take place, in every translation unit in
4106 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004107 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4108 // Is there any previous explicit specialization declaration?
4109 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4110 return false;
4111 }
4112
Douglas Gregor1d957a32009-10-27 18:42:08 +00004113 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004114 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004115 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004116 << (PrevTSK != TSK_ImplicitInstantiation);
4117
4118 return true;
4119 }
4120 break;
4121
4122 case TSK_ExplicitInstantiationDeclaration:
4123 switch (PrevTSK) {
4124 case TSK_ExplicitInstantiationDeclaration:
4125 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00004126 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004127 return false;
4128
4129 case TSK_Undeclared:
4130 case TSK_ImplicitInstantiation:
4131 // We're explicitly instantiating something that may have already been
4132 // implicitly instantiated; that's fine.
4133 return false;
4134
4135 case TSK_ExplicitSpecialization:
4136 // C++0x [temp.explicit]p4:
4137 // For a given set of template parameters, if an explicit instantiation
4138 // of a template appears after a declaration of an explicit
4139 // specialization for that template, the explicit instantiation has no
4140 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00004141 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004142 return false;
4143
4144 case TSK_ExplicitInstantiationDefinition:
4145 // C++0x [temp.explicit]p10:
4146 // If an entity is the subject of both an explicit instantiation
4147 // declaration and an explicit instantiation definition in the same
4148 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004149 Diag(NewLoc,
4150 diag::err_explicit_instantiation_declaration_after_definition);
4151 Diag(PrevPointOfInstantiation,
4152 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004153 assert(PrevPointOfInstantiation.isValid() &&
4154 "Explicit instantiation without point of instantiation?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00004155 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004156 return false;
4157 }
4158 break;
4159
4160 case TSK_ExplicitInstantiationDefinition:
4161 switch (PrevTSK) {
4162 case TSK_Undeclared:
4163 case TSK_ImplicitInstantiation:
4164 // We're explicitly instantiating something that may have already been
4165 // implicitly instantiated; that's fine.
4166 return false;
4167
4168 case TSK_ExplicitSpecialization:
4169 // C++ DR 259, C++0x [temp.explicit]p4:
4170 // For a given set of template parameters, if an explicit
4171 // instantiation of a template appears after a declaration of
4172 // an explicit specialization for that template, the explicit
4173 // instantiation has no effect.
4174 //
4175 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004176 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004177 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004178 if (!getLangOptions().CPlusPlus0x) {
4179 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004180 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004181 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004182 diag::note_previous_template_specialization);
4183 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004184 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004185 return false;
4186
4187 case TSK_ExplicitInstantiationDeclaration:
4188 // We're explicity instantiating a definition for something for which we
4189 // were previously asked to suppress instantiations. That's fine.
4190 return false;
4191
4192 case TSK_ExplicitInstantiationDefinition:
4193 // C++0x [temp.spec]p5:
4194 // For a given template and a given set of template-arguments,
4195 // - an explicit instantiation definition shall appear at most once
4196 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004197 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004198 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004199 Diag(PrevPointOfInstantiation,
4200 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004201 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004202 return false;
4203 }
4204 break;
4205 }
4206
4207 assert(false && "Missing specialization/instantiation case?");
4208
4209 return false;
4210}
4211
John McCallb9c78482010-04-08 09:05:18 +00004212/// \brief Perform semantic analysis for the given dependent function
4213/// template specialization. The only possible way to get a dependent
4214/// function template specialization is with a friend declaration,
4215/// like so:
4216///
4217/// template <class T> void foo(T);
4218/// template <class T> class A {
4219/// friend void foo<>(T);
4220/// };
4221///
4222/// There really isn't any useful analysis we can do here, so we
4223/// just store the information.
4224bool
4225Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4226 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4227 LookupResult &Previous) {
4228 // Remove anything from Previous that isn't a function template in
4229 // the correct context.
4230 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4231 LookupResult::Filter F = Previous.makeFilter();
4232 while (F.hasNext()) {
4233 NamedDecl *D = F.next()->getUnderlyingDecl();
4234 if (!isa<FunctionTemplateDecl>(D) ||
4235 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4236 F.erase();
4237 }
4238 F.done();
4239
4240 // Should this be diagnosed here?
4241 if (Previous.empty()) return true;
4242
4243 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4244 ExplicitTemplateArgs);
4245 return false;
4246}
4247
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004248/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004249/// specialization.
4250///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004251/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004252/// explicit function template specialization. On successful completion,
4253/// the function declaration \p FD will become a function template
4254/// specialization.
4255///
4256/// \param FD the function declaration, which will be updated to become a
4257/// function template specialization.
4258///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004259/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4260/// if any. Note that this may be valid info even when 0 arguments are
4261/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4262/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004263///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004264/// \param PrevDecl the set of declarations that may be specialized by
4265/// this function specialization.
4266bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004267Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004268 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004269 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004270 // The set of function template specializations that could match this
4271 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004272 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004273
4274 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00004275 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4276 I != E; ++I) {
4277 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4278 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004279 // Only consider templates found within the same semantic lookup scope as
4280 // FD.
4281 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4282 continue;
4283
4284 // C++ [temp.expl.spec]p11:
4285 // A trailing template-argument can be left unspecified in the
4286 // template-id naming an explicit function template specialization
4287 // provided it can be deduced from the function argument type.
4288 // Perform template argument deduction to determine whether we may be
4289 // specializing this template.
4290 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004291 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004292 FunctionDecl *Specialization = 0;
4293 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004294 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004295 FD->getType(),
4296 Specialization,
4297 Info)) {
4298 // FIXME: Template argument deduction failed; record why it failed, so
4299 // that we can provide nifty diagnostics.
4300 (void)TDK;
4301 continue;
4302 }
4303
4304 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004305 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004306 }
4307 }
4308
Douglas Gregor5de279c2009-09-26 03:41:46 +00004309 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004310 UnresolvedSetIterator Result
4311 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4312 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004313 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004314 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004315 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004316 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004317 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004318 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004319 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004320
4321 // Ignore access information; it doesn't figure into redeclaration checking.
4322 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004323 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004324
4325 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004326 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004327
4328 // If this is a friend declaration, then we're not really declaring
4329 // an explicit specialization.
4330 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004331
Douglas Gregor54888652009-10-07 00:13:32 +00004332 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004333 if (!isFriend &&
4334 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004335 Specialization->getPrimaryTemplate(),
4336 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004337 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004338 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004339
4340 // C++ [temp.expl.spec]p6:
4341 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004342 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004343 // before the first use of that specialization that would cause an implicit
4344 // instantiation to take place, in every translation unit in which such a
4345 // use occurs; no diagnostic is required.
4346 FunctionTemplateSpecializationInfo *SpecInfo
4347 = Specialization->getTemplateSpecializationInfo();
4348 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004349
Abramo Bagnara8075c852010-06-12 07:44:57 +00004350 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00004351 if (!isFriend &&
4352 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004353 TSK_ExplicitSpecialization,
4354 Specialization,
4355 SpecInfo->getTemplateSpecializationKind(),
4356 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004357 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004358 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004359
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004360 // Mark the prior declaration as an explicit specialization, so that later
4361 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004362 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00004363 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004364 MarkUnusedFileScopedDecl(Specialization);
4365 }
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004366
4367 // Turn the given function declaration into a function template
4368 // specialization, with the template arguments from the previous
4369 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004370 // Take copies of (semantic and syntactic) template argument lists.
4371 const TemplateArgumentList* TemplArgs = new (Context)
4372 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4373 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4374 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004375 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004376 TemplArgs, /*InsertPos=*/0,
4377 SpecInfo->getTemplateSpecializationKind(),
4378 TemplArgsAsWritten);
4379
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004380 // The "previous declaration" for this function template specialization is
4381 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004382 Previous.clear();
4383 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004384 return false;
4385}
4386
Douglas Gregor86d142a2009-10-08 07:24:58 +00004387/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004388/// specialization.
4389///
4390/// This routine performs all of the semantic analysis required for an
4391/// explicit member function specialization. On successful completion,
4392/// the function declaration \p FD will become a member function
4393/// specialization.
4394///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004395/// \param Member the member declaration, which will be updated to become a
4396/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004397///
John McCall1f82f242009-11-18 22:49:29 +00004398/// \param Previous the set of declarations, one of which may be specialized
4399/// by this function specialization; the set will be modified to contain the
4400/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004401bool
John McCall1f82f242009-11-18 22:49:29 +00004402Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004403 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004404
Douglas Gregor86d142a2009-10-08 07:24:58 +00004405 // Try to find the member we are instantiating.
4406 NamedDecl *Instantiation = 0;
4407 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004408 MemberSpecializationInfo *MSInfo = 0;
4409
John McCall1f82f242009-11-18 22:49:29 +00004410 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004411 // Nowhere to look anyway.
4412 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004413 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4414 I != E; ++I) {
4415 NamedDecl *D = (*I)->getUnderlyingDecl();
4416 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004417 if (Context.hasSameType(Function->getType(), Method->getType())) {
4418 Instantiation = Method;
4419 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004420 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004421 break;
4422 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004423 }
4424 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004425 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004426 VarDecl *PrevVar;
4427 if (Previous.isSingleResult() &&
4428 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004429 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004430 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004431 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004432 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004433 }
4434 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004435 CXXRecordDecl *PrevRecord;
4436 if (Previous.isSingleResult() &&
4437 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4438 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004439 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004440 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004441 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004442 }
4443
4444 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004445 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004446 // specializations are always out-of-line, the caller will complain about
4447 // this mismatch later.
4448 return false;
4449 }
John McCalle820e5e2010-04-13 20:37:33 +00004450
4451 // If this is a friend, just bail out here before we start turning
4452 // things into explicit specializations.
4453 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4454 // Preserve instantiation information.
4455 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4456 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4457 cast<CXXMethodDecl>(InstantiatedFrom),
4458 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4459 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4460 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4461 cast<CXXRecordDecl>(InstantiatedFrom),
4462 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4463 }
4464
4465 Previous.clear();
4466 Previous.addDecl(Instantiation);
4467 return false;
4468 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004469
Douglas Gregor86d142a2009-10-08 07:24:58 +00004470 // Make sure that this is a specialization of a member.
4471 if (!InstantiatedFrom) {
4472 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4473 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004474 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4475 return true;
4476 }
4477
Douglas Gregor06db9f52009-10-12 20:18:28 +00004478 // C++ [temp.expl.spec]p6:
4479 // If a template, a member template or the member of a class template is
4480 // explicitly specialized then that spe- cialization shall be declared
4481 // before the first use of that specialization that would cause an implicit
4482 // instantiation to take place, in every translation unit in which such a
4483 // use occurs; no diagnostic is required.
4484 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004485
Abramo Bagnara8075c852010-06-12 07:44:57 +00004486 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00004487 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4488 TSK_ExplicitSpecialization,
4489 Instantiation,
4490 MSInfo->getTemplateSpecializationKind(),
4491 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004492 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004493 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004494
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004495 // Check the scope of this explicit specialization.
4496 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004497 InstantiatedFrom,
4498 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004499 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004500 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004501
Douglas Gregor86d142a2009-10-08 07:24:58 +00004502 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004503 // the original declaration to note that it is an explicit specialization
4504 // (if it was previously an implicit instantiation). This latter step
4505 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004506 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004507 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4508 if (InstantiationFunction->getTemplateSpecializationKind() ==
4509 TSK_ImplicitInstantiation) {
4510 InstantiationFunction->setTemplateSpecializationKind(
4511 TSK_ExplicitSpecialization);
4512 InstantiationFunction->setLocation(Member->getLocation());
4513 }
4514
Douglas Gregor86d142a2009-10-08 07:24:58 +00004515 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4516 cast<CXXMethodDecl>(InstantiatedFrom),
4517 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004518 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004519 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004520 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4521 if (InstantiationVar->getTemplateSpecializationKind() ==
4522 TSK_ImplicitInstantiation) {
4523 InstantiationVar->setTemplateSpecializationKind(
4524 TSK_ExplicitSpecialization);
4525 InstantiationVar->setLocation(Member->getLocation());
4526 }
4527
Douglas Gregor86d142a2009-10-08 07:24:58 +00004528 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4529 cast<VarDecl>(InstantiatedFrom),
4530 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004531 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004532 } else {
4533 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004534 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4535 if (InstantiationClass->getTemplateSpecializationKind() ==
4536 TSK_ImplicitInstantiation) {
4537 InstantiationClass->setTemplateSpecializationKind(
4538 TSK_ExplicitSpecialization);
4539 InstantiationClass->setLocation(Member->getLocation());
4540 }
4541
Douglas Gregor86d142a2009-10-08 07:24:58 +00004542 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004543 cast<CXXRecordDecl>(InstantiatedFrom),
4544 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004545 }
4546
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004547 // Save the caller the trouble of having to figure out which declaration
4548 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004549 Previous.clear();
4550 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004551 return false;
4552}
4553
Douglas Gregore47f5a72009-10-14 23:41:34 +00004554/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004555///
4556/// \returns true if a serious error occurs, false otherwise.
4557static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00004558 SourceLocation InstLoc,
4559 bool WasQualifiedName) {
4560 DeclContext *ExpectedContext
4561 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4562 DeclContext *CurContext = S.CurContext->getLookupContext();
4563
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004564 if (CurContext->isRecord()) {
4565 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4566 << D;
4567 return true;
4568 }
4569
Douglas Gregore47f5a72009-10-14 23:41:34 +00004570 // C++0x [temp.explicit]p2:
4571 // An explicit instantiation shall appear in an enclosing namespace of its
4572 // template.
4573 //
4574 // This is DR275, which we do not retroactively apply to C++98/03.
4575 if (S.getLangOptions().CPlusPlus0x &&
4576 !CurContext->Encloses(ExpectedContext)) {
4577 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004578 S.Diag(InstLoc,
4579 S.getLangOptions().CPlusPlus0x?
4580 diag::err_explicit_instantiation_out_of_scope
4581 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004582 << D << NS;
4583 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004584 S.Diag(InstLoc,
4585 S.getLangOptions().CPlusPlus0x?
4586 diag::err_explicit_instantiation_must_be_global
4587 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004588 << D;
4589 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004590 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004591 }
4592
4593 // C++0x [temp.explicit]p2:
4594 // If the name declared in the explicit instantiation is an unqualified
4595 // name, the explicit instantiation shall appear in the namespace where
4596 // its template is declared or, if that namespace is inline (7.3.1), any
4597 // namespace from its enclosing namespace set.
4598 if (WasQualifiedName)
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004599 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004600
4601 if (CurContext->Equals(ExpectedContext))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004602 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004603
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004604 S.Diag(InstLoc,
4605 S.getLangOptions().CPlusPlus0x?
4606 diag::err_explicit_instantiation_unqualified_wrong_namespace
4607 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004608 << D << ExpectedContext;
4609 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004610 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004611}
4612
4613/// \brief Determine whether the given scope specifier has a template-id in it.
4614static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4615 if (!SS.isSet())
4616 return false;
4617
4618 // C++0x [temp.explicit]p2:
4619 // If the explicit instantiation is for a member function, a member class
4620 // or a static data member of a class template specialization, the name of
4621 // the class template specialization in the qualified-id for the member
4622 // name shall be a simple-template-id.
4623 //
4624 // C++98 has the same restriction, just worded differently.
4625 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4626 NNS; NNS = NNS->getPrefix())
4627 if (Type *T = NNS->getAsType())
4628 if (isa<TemplateSpecializationType>(T))
4629 return true;
4630
4631 return false;
4632}
4633
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004634// Explicit instantiation of a class template specialization
Douglas Gregora1f49972009-05-13 00:25:59 +00004635Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004636Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004637 SourceLocation ExternLoc,
4638 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004639 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004640 SourceLocation KWLoc,
4641 const CXXScopeSpec &SS,
4642 TemplateTy TemplateD,
4643 SourceLocation TemplateNameLoc,
4644 SourceLocation LAngleLoc,
4645 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004646 SourceLocation RAngleLoc,
4647 AttributeList *Attr) {
4648 // Find the class template we're specializing
4649 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004650 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004651 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4652
4653 // Check that the specialization uses the same tag kind as the
4654 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004655 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4656 assert(Kind != TTK_Enum &&
4657 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004658 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004659 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004660 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004661 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004662 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004663 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004664 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004665 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004666 diag::note_previous_use);
4667 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4668 }
4669
Douglas Gregore47f5a72009-10-14 23:41:34 +00004670 // C++0x [temp.explicit]p2:
4671 // There are two forms of explicit instantiation: an explicit instantiation
4672 // definition and an explicit instantiation declaration. An explicit
4673 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004674 TemplateSpecializationKind TSK
4675 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4676 : TSK_ExplicitInstantiationDeclaration;
4677
Douglas Gregora1f49972009-05-13 00:25:59 +00004678 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004679 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004680 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004681
4682 // Check that the template argument list is well-formed for this
4683 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004684 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4685 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004686 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4687 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004688 return true;
4689
Mike Stump11289f42009-09-09 15:08:12 +00004690 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004691 ClassTemplate->getTemplateParameters()->size()) &&
4692 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004693
Douglas Gregora1f49972009-05-13 00:25:59 +00004694 // Find the class template specialization declaration that
4695 // corresponds to these arguments.
Douglas Gregora1f49972009-05-13 00:25:59 +00004696 void *InsertPos = 0;
4697 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004698 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4699 Converted.flatSize(), InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004700
Abramo Bagnara8075c852010-06-12 07:44:57 +00004701 TemplateSpecializationKind PrevDecl_TSK
4702 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4703
Douglas Gregor54888652009-10-07 00:13:32 +00004704 // C++0x [temp.explicit]p2:
4705 // [...] An explicit instantiation shall appear in an enclosing
4706 // namespace of its template. [...]
4707 //
4708 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004709 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4710 SS.isSet()))
4711 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004712
Douglas Gregora1f49972009-05-13 00:25:59 +00004713 ClassTemplateSpecializationDecl *Specialization = 0;
4714
Douglas Gregor0681a352009-11-25 06:01:46 +00004715 bool ReusedDecl = false;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004716 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004717 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00004718 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004719 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004720 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004721 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00004722 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00004723
Abramo Bagnara8075c852010-06-12 07:44:57 +00004724 // Even though HasNoEffect == true means that this explicit instantiation
4725 // has no effect on semantics, we go on to put its syntax in the AST.
4726
4727 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4728 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004729 // Since the only prior class template specialization with these
4730 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00004731 // declaration node as our own, updating the source location
4732 // for the template name to reflect our new declaration.
4733 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004734 Specialization = PrevDecl;
4735 Specialization->setLocation(TemplateNameLoc);
4736 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004737 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004738 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004739 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004740
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004741 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004742 // Create a new class template specialization declaration node for
4743 // this explicit specialization.
4744 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004745 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00004746 ClassTemplate->getDeclContext(),
4747 TemplateNameLoc,
4748 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004749 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004750 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004751
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004752 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00004753 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004754 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004755 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004756 }
4757
4758 // Build the fully-sugared type for this explicit instantiation as
4759 // the user wrote in the explicit instantiation itself. This means
4760 // that we'll pretty-print the type retrieved from the
4761 // specialization's declaration the way that the user actually wrote
4762 // the explicit instantiation, rather than formatting the name based
4763 // on the "canonical" representation used to store the template
4764 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004765 TypeSourceInfo *WrittenTy
4766 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4767 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004768 Context.getTypeDeclType(Specialization));
4769 Specialization->setTypeAsWritten(WrittenTy);
4770 TemplateArgsIn.release();
4771
Abramo Bagnara8075c852010-06-12 07:44:57 +00004772 // Set source locations for keywords.
4773 Specialization->setExternLoc(ExternLoc);
4774 Specialization->setTemplateKeywordLoc(TemplateLoc);
4775
4776 // Add the explicit instantiation into its lexical context. However,
4777 // since explicit instantiations are never found by name lookup, we
4778 // just put it into the declaration context directly.
4779 Specialization->setLexicalDeclContext(CurContext);
4780 CurContext->addDecl(Specialization);
4781
4782 // Syntax is now OK, so return if it has no other effect on semantics.
4783 if (HasNoEffect) {
4784 // Set the template specialization kind.
4785 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00004786 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00004787 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004788
4789 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004790 // A definition of a class template or class member template
4791 // shall be in scope at the point of the explicit instantiation of
4792 // the class template or class member template.
4793 //
4794 // This check comes when we actually try to perform the
4795 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004796 ClassTemplateSpecializationDecl *Def
4797 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004798 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004799 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004800 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004801 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00004802 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004803 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
4804 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004805
Douglas Gregor1d957a32009-10-27 18:42:08 +00004806 // Instantiate the members of this class template specialization.
4807 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004808 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004809 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004810 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4811
4812 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4813 // TSK_ExplicitInstantiationDefinition
4814 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4815 TSK == TSK_ExplicitInstantiationDefinition)
4816 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004817
Douglas Gregor12e49d32009-10-15 22:53:21 +00004818 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004819 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004820
Abramo Bagnara8075c852010-06-12 07:44:57 +00004821 // Set the template specialization kind.
4822 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00004823 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00004824}
4825
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004826// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00004827DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004828Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004829 SourceLocation ExternLoc,
4830 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004831 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004832 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004833 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004834 IdentifierInfo *Name,
4835 SourceLocation NameLoc,
4836 AttributeList *Attr) {
4837
Douglas Gregord6ab8742009-05-28 23:31:59 +00004838 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004839 bool IsDependent = false;
John McCall48871652010-08-21 09:40:31 +00004840 Decl *TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
4841 KWLoc, SS, Name, NameLoc, Attr, AS_none,
4842 MultiTemplateParamsArg(*this, 0, 0),
4843 Owned, IsDependent);
John McCall7f41d982009-09-11 04:59:25 +00004844 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4845
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004846 if (!TagD)
4847 return true;
4848
John McCall48871652010-08-21 09:40:31 +00004849 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004850 if (Tag->isEnum()) {
4851 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4852 << Context.getTypeDeclType(Tag);
4853 return true;
4854 }
4855
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004856 if (Tag->isInvalidDecl())
4857 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004858
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004859 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4860 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4861 if (!Pattern) {
4862 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4863 << Context.getTypeDeclType(Record);
4864 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4865 return true;
4866 }
4867
Douglas Gregore47f5a72009-10-14 23:41:34 +00004868 // C++0x [temp.explicit]p2:
4869 // If the explicit instantiation is for a class or member class, the
4870 // elaborated-type-specifier in the declaration shall include a
4871 // simple-template-id.
4872 //
4873 // C++98 has the same restriction, just worded differently.
4874 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00004875 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004876 << Record << SS.getRange();
4877
4878 // C++0x [temp.explicit]p2:
4879 // There are two forms of explicit instantiation: an explicit instantiation
4880 // definition and an explicit instantiation declaration. An explicit
4881 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004882 TemplateSpecializationKind TSK
4883 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4884 : TSK_ExplicitInstantiationDeclaration;
4885
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004886 // C++0x [temp.explicit]p2:
4887 // [...] An explicit instantiation shall appear in an enclosing
4888 // namespace of its template. [...]
4889 //
4890 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004891 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004892
4893 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004894 CXXRecordDecl *PrevDecl
4895 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004896 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004897 PrevDecl = Record;
4898 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004899 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00004900 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004901 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004902 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004903 PrevDecl,
4904 MSInfo->getTemplateSpecializationKind(),
4905 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004906 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004907 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004908 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004909 return TagD;
4910 }
4911
Douglas Gregor12e49d32009-10-15 22:53:21 +00004912 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004913 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004914 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004915 // C++ [temp.explicit]p3:
4916 // A definition of a member class of a class template shall be in scope
4917 // at the point of an explicit instantiation of the member class.
4918 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004919 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004920 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004921 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4922 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004923 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4924 << Pattern;
4925 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004926 } else {
4927 if (InstantiateClass(NameLoc, Record, Def,
4928 getTemplateInstantiationArgs(Record),
4929 TSK))
4930 return true;
4931
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004932 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004933 if (!RecordDef)
4934 return true;
4935 }
4936 }
4937
4938 // Instantiate all of the members of the class.
4939 InstantiateClassMembers(NameLoc, RecordDef,
4940 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004941
Douglas Gregor88d292c2010-05-13 16:44:06 +00004942 if (TSK == TSK_ExplicitInstantiationDefinition)
4943 MarkVTableUsed(NameLoc, RecordDef, true);
4944
Mike Stump87c57ac2009-05-16 07:39:55 +00004945 // FIXME: We don't have any representation for explicit instantiations of
4946 // member classes. Such a representation is not needed for compilation, but it
4947 // should be available for clients that want to see all of the declarations in
4948 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004949 return TagD;
4950}
4951
Douglas Gregor450f00842009-09-25 18:43:00 +00004952Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4953 SourceLocation ExternLoc,
4954 SourceLocation TemplateLoc,
4955 Declarator &D) {
4956 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004957 // TODO: check if/when DNInfo should replace Name.
4958 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4959 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00004960 if (!Name) {
4961 if (!D.isInvalidType())
4962 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4963 diag::err_explicit_instantiation_requires_name)
4964 << D.getDeclSpec().getSourceRange()
4965 << D.getSourceRange();
4966
4967 return true;
4968 }
4969
4970 // The scope passed in may not be a decl scope. Zip up the scope tree until
4971 // we find one that is.
4972 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4973 (S->getFlags() & Scope::TemplateParamScope) != 0)
4974 S = S->getParent();
4975
4976 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00004977 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
4978 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00004979 if (R.isNull())
4980 return true;
4981
4982 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4983 // Cannot explicitly instantiate a typedef.
4984 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4985 << Name;
4986 return true;
4987 }
4988
Douglas Gregor3c74d412009-10-14 20:14:33 +00004989 // C++0x [temp.explicit]p1:
4990 // [...] An explicit instantiation of a function template shall not use the
4991 // inline or constexpr specifiers.
4992 // Presumably, this also applies to member functions of class templates as
4993 // well.
4994 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4995 Diag(D.getDeclSpec().getInlineSpecLoc(),
4996 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00004997 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004998
4999 // FIXME: check for constexpr specifier.
5000
Douglas Gregore47f5a72009-10-14 23:41:34 +00005001 // C++0x [temp.explicit]p2:
5002 // There are two forms of explicit instantiation: an explicit instantiation
5003 // definition and an explicit instantiation declaration. An explicit
5004 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00005005 TemplateSpecializationKind TSK
5006 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5007 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005008
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005009 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005010 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00005011
5012 if (!R->isFunctionType()) {
5013 // C++ [temp.explicit]p1:
5014 // A [...] static data member of a class template can be explicitly
5015 // instantiated from the member definition associated with its class
5016 // template.
John McCall27b18f82009-11-17 02:14:36 +00005017 if (Previous.isAmbiguous())
5018 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00005019
John McCall67c00872009-12-02 08:25:40 +00005020 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005021 if (!Prev || !Prev->isStaticDataMember()) {
5022 // We expect to see a data data member here.
5023 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5024 << Name;
5025 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5026 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005027 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005028 return true;
5029 }
5030
5031 if (!Prev->getInstantiatedFromStaticDataMember()) {
5032 // FIXME: Check for explicit specialization?
5033 Diag(D.getIdentifierLoc(),
5034 diag::err_explicit_instantiation_data_member_not_instantiated)
5035 << Prev;
5036 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5037 // FIXME: Can we provide a note showing where this was declared?
5038 return true;
5039 }
5040
Douglas Gregore47f5a72009-10-14 23:41:34 +00005041 // C++0x [temp.explicit]p2:
5042 // If the explicit instantiation is for a member function, a member class
5043 // or a static data member of a class template specialization, the name of
5044 // the class template specialization in the qualified-id for the member
5045 // name shall be a simple-template-id.
5046 //
5047 // C++98 has the same restriction, just worded differently.
5048 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5049 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005050 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005051 << Prev << D.getCXXScopeSpec().getRange();
5052
5053 // Check the scope of this explicit instantiation.
5054 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5055
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005056 // Verify that it is okay to explicitly instantiate here.
5057 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5058 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00005059 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005060 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005061 MSInfo->getTemplateSpecializationKind(),
5062 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005063 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005064 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005065 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005066 return (Decl*) 0;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005067
Douglas Gregor450f00842009-09-25 18:43:00 +00005068 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005069 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005070 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00005071 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
5072 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00005073
5074 // FIXME: Create an ExplicitInstantiation node?
John McCall48871652010-08-21 09:40:31 +00005075 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005076 }
5077
Douglas Gregor0e876e02009-09-25 23:53:26 +00005078 // If the declarator is a template-id, translate the parser's template
5079 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005080 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005081 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005082 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5083 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005084 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5085 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005086 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5087 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005088 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005089 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005090 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005091 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005092 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005093
Douglas Gregor450f00842009-09-25 18:43:00 +00005094 // C++ [temp.explicit]p1:
5095 // A [...] function [...] can be explicitly instantiated from its template.
5096 // A member function [...] of a class template can be explicitly
5097 // instantiated from the member definition associated with its class
5098 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005099 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005100 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5101 P != PEnd; ++P) {
5102 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005103 if (!HasExplicitTemplateArgs) {
5104 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5105 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5106 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005107
John McCall58cc69d2010-01-27 01:50:18 +00005108 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005109 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5110 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005111 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005112 }
5113 }
5114
5115 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5116 if (!FunTmpl)
5117 continue;
5118
John McCallbc077cf2010-02-08 23:07:23 +00005119 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005120 FunctionDecl *Specialization = 0;
5121 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005122 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005123 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005124 R, Specialization, Info)) {
5125 // FIXME: Keep track of almost-matches?
5126 (void)TDK;
5127 continue;
5128 }
5129
John McCall58cc69d2010-01-27 01:50:18 +00005130 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005131 }
5132
5133 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005134 UnresolvedSetIterator Result
5135 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005136 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005137 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5138 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5139 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005140
John McCall58cc69d2010-01-27 01:50:18 +00005141 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005142 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005143
5144 // Ignore access control bits, we don't need them for redeclaration checking.
5145 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005146
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005147 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005148 Diag(D.getIdentifierLoc(),
5149 diag::err_explicit_instantiation_member_function_not_instantiated)
5150 << Specialization
5151 << (Specialization->getTemplateSpecializationKind() ==
5152 TSK_ExplicitSpecialization);
5153 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5154 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005155 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005156
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005157 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005158 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5159 PrevDecl = Specialization;
5160
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005161 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005162 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005163 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005164 PrevDecl,
5165 PrevDecl->getTemplateSpecializationKind(),
5166 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005167 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005168 return true;
5169
5170 // FIXME: We may still want to build some representation of this
5171 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00005172 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005173 return (Decl*) 0;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005174 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005175
5176 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005177
5178 if (TSK == TSK_ExplicitInstantiationDefinition)
5179 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5180 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005181
Douglas Gregore47f5a72009-10-14 23:41:34 +00005182 // C++0x [temp.explicit]p2:
5183 // If the explicit instantiation is for a member function, a member class
5184 // or a static data member of a class template specialization, the name of
5185 // the class template specialization in the qualified-id for the member
5186 // name shall be a simple-template-id.
5187 //
5188 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005189 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005190 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005191 D.getCXXScopeSpec().isSet() &&
5192 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5193 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005194 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005195 << Specialization << D.getCXXScopeSpec().getRange();
5196
5197 CheckExplicitInstantiationScope(*this,
5198 FunTmpl? (NamedDecl *)FunTmpl
5199 : Specialization->getInstantiatedFromMemberFunction(),
5200 D.getIdentifierLoc(),
5201 D.getCXXScopeSpec().isSet());
5202
Douglas Gregor450f00842009-09-25 18:43:00 +00005203 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCall48871652010-08-21 09:40:31 +00005204 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005205}
5206
Douglas Gregor333489b2009-03-27 23:10:48 +00005207Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005208Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5209 const CXXScopeSpec &SS, IdentifierInfo *Name,
5210 SourceLocation TagLoc, SourceLocation NameLoc) {
5211 // This has to hold, because SS is expected to be defined.
5212 assert(Name && "Expected a name in a dependent tag");
5213
5214 NestedNameSpecifier *NNS
5215 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5216 if (!NNS)
5217 return true;
5218
Abramo Bagnara6150c882010-05-11 21:36:43 +00005219 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005220
Douglas Gregorba41d012010-04-24 16:38:41 +00005221 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5222 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005223 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005224 return true;
5225 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005226
5227 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallba7bf592010-08-24 05:47:05 +00005228 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCall7f41d982009-09-11 04:59:25 +00005229}
5230
5231Sema::TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005232Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5233 const CXXScopeSpec &SS, const IdentifierInfo &II,
5234 SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005235 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005236 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5237 if (!NNS)
5238 return true;
5239
Douglas Gregorf7d77712010-06-16 22:31:08 +00005240 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5241 !getLangOptions().CPlusPlus0x)
5242 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5243 << FixItHint::CreateRemoval(TypenameLoc);
5244
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005245 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005246 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005247 if (T.isNull())
5248 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005249
5250 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5251 if (isa<DependentNameType>(T)) {
5252 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005253 TL.setKeywordLoc(TypenameLoc);
5254 TL.setQualifierRange(SS.getRange());
5255 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005256 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005257 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005258 TL.setKeywordLoc(TypenameLoc);
5259 TL.setQualifierRange(SS.getRange());
5260 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005261 }
5262
John McCallba7bf592010-08-24 05:47:05 +00005263 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00005264}
5265
Douglas Gregordce2b622009-04-01 00:28:59 +00005266Sema::TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005267Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5268 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallba7bf592010-08-24 05:47:05 +00005269 ParsedType Ty) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00005270 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5271 !getLangOptions().CPlusPlus0x)
5272 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5273 << FixItHint::CreateRemoval(TypenameLoc);
5274
John McCallf7bcc812010-05-28 23:32:21 +00005275 TypeSourceInfo *InnerTSI = 0;
5276 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCallf7bcc812010-05-28 23:32:21 +00005277
5278 assert(isa<TemplateSpecializationType>(T) &&
5279 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005280
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005281 if (computeDeclContext(SS, false)) {
5282 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005283 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005284 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005285
5286 // Push the inner type, preserving its source locations if possible.
5287 TypeLocBuilder Builder;
5288 if (InnerTSI)
5289 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5290 else
5291 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5292
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005293 /* Note: NNS already embedded in template specialization type T. */
5294 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCallf7bcc812010-05-28 23:32:21 +00005295 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5296 TL.setKeywordLoc(TypenameLoc);
5297 TL.setQualifierRange(SS.getRange());
5298
5299 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallba7bf592010-08-24 05:47:05 +00005300 return CreateParsedType(T, TSI);
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005301 }
Mike Stump11289f42009-09-09 15:08:12 +00005302
John McCallc392f372010-06-11 00:33:02 +00005303 // TODO: it's really silly that we make a template specialization
5304 // type earlier only to drop it again here.
5305 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5306 DependentTemplateName *DTN =
5307 TST->getTemplateName().getAsDependentTemplateName();
5308 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005309 assert(DTN->getQualifier()
5310 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5311 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5312 DTN->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00005313 DTN->getIdentifier(),
5314 TST->getNumArgs(),
5315 TST->getArgs());
John McCall99b2fe52010-04-29 23:50:39 +00005316 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCallc392f372010-06-11 00:33:02 +00005317 DependentTemplateSpecializationTypeLoc TL =
5318 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5319 if (InnerTSI) {
5320 TemplateSpecializationTypeLoc TSTL =
5321 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5322 TL.setLAngleLoc(TSTL.getLAngleLoc());
5323 TL.setRAngleLoc(TSTL.getRAngleLoc());
5324 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5325 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5326 } else {
5327 TL.initializeLocal(SourceLocation());
5328 }
John McCallf7bcc812010-05-28 23:32:21 +00005329 TL.setKeywordLoc(TypenameLoc);
5330 TL.setQualifierRange(SS.getRange());
John McCallba7bf592010-08-24 05:47:05 +00005331 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00005332}
5333
Douglas Gregor333489b2009-03-27 23:10:48 +00005334/// \brief Build the type that describes a C++ typename specifier,
5335/// e.g., "typename T::type".
5336QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005337Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5338 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005339 SourceLocation KeywordLoc, SourceRange NNSRange,
5340 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005341 CXXScopeSpec SS;
5342 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005343 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005344
John McCall0b66eb32010-05-01 00:40:08 +00005345 DeclContext *Ctx = computeDeclContext(SS);
5346 if (!Ctx) {
5347 // If the nested-name-specifier is dependent and couldn't be
5348 // resolved to a type, build a typename type.
5349 assert(NNS->isDependent());
5350 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005351 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005352
John McCall0b66eb32010-05-01 00:40:08 +00005353 // If the nested-name-specifier refers to the current instantiation,
5354 // the "typename" keyword itself is superfluous. In C++03, the
5355 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5356 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00005357 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005358
John McCall0b66eb32010-05-01 00:40:08 +00005359 if (RequireCompleteDeclContext(SS, Ctx))
5360 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005361
5362 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005363 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005364 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005365 unsigned DiagID = 0;
5366 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005367 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005368 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005369 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005370 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005371
5372 case LookupResult::NotFoundInCurrentInstantiation:
5373 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005374 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005375
5376 case LookupResult::Found:
Douglas Gregorf7d77712010-06-16 22:31:08 +00005377 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005378 // We found a type. Build an ElaboratedType, since the
5379 // typename-specifier was just sugar.
5380 return Context.getElaboratedType(ETK_Typename, NNS,
5381 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005382 }
5383
5384 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005385 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005386 break;
5387
John McCalle61f2ba2009-11-18 02:36:19 +00005388 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005389 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005390 return QualType();
5391
Douglas Gregor333489b2009-03-27 23:10:48 +00005392 case LookupResult::FoundOverloaded:
5393 DiagID = diag::err_typename_nested_not_type;
5394 Referenced = *Result.begin();
5395 break;
5396
John McCall6538c932009-10-10 05:48:19 +00005397 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005398 return QualType();
5399 }
5400
5401 // If we get here, it's because name lookup did not find a
5402 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005403 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5404 IILoc);
5405 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005406 if (Referenced)
5407 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5408 << Name;
5409 return QualType();
5410}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005411
5412namespace {
5413 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005414 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005415 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005416 SourceLocation Loc;
5417 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005418
Douglas Gregor15acfb92009-08-06 16:20:37 +00005419 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005420 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5421
Mike Stump11289f42009-09-09 15:08:12 +00005422 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005423 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005424 DeclarationName Entity)
5425 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005426 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005427
5428 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005429 /// transformed.
5430 ///
5431 /// For the purposes of type reconstruction, a type has already been
5432 /// transformed if it is NULL or if it is not dependent.
5433 bool AlreadyTransformed(QualType T) {
5434 return T.isNull() || !T->isDependentType();
5435 }
Mike Stump11289f42009-09-09 15:08:12 +00005436
5437 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005438 /// rebuilt.
5439 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005440
Douglas Gregor15acfb92009-08-06 16:20:37 +00005441 /// \brief Returns the name of the entity whose type is being rebuilt.
5442 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005443
Douglas Gregoref6ab412009-10-27 06:26:26 +00005444 /// \brief Sets the "base" location and entity when that
5445 /// information is known based on another transformation.
5446 void setBase(SourceLocation Loc, DeclarationName Entity) {
5447 this->Loc = Loc;
5448 this->Entity = Entity;
5449 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00005450 };
5451}
5452
Douglas Gregor15acfb92009-08-06 16:20:37 +00005453/// \brief Rebuilds a type within the context of the current instantiation.
5454///
Mike Stump11289f42009-09-09 15:08:12 +00005455/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005456/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005457/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005458/// partial specialization thereof). This routine will rebuild that type now
5459/// that we have entered the declarator's scope, which may produce different
5460/// canonical types, e.g.,
5461///
5462/// \code
5463/// template<typename T>
5464/// struct X {
5465/// typedef T* pointer;
5466/// pointer data();
5467/// };
5468///
5469/// template<typename T>
5470/// typename X<T>::pointer X<T>::data() { ... }
5471/// \endcode
5472///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005473/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005474/// since we do not know that we can look into X<T> when we parsed the type.
5475/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005476/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005477/// as the canonical type of T*, allowing the return types of the out-of-line
5478/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005479TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5480 SourceLocation Loc,
5481 DeclarationName Name) {
5482 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005483 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005484
Douglas Gregor15acfb92009-08-06 16:20:37 +00005485 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5486 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005487}
Douglas Gregorbe999392009-09-15 16:23:51 +00005488
John McCalldadc5752010-08-24 06:29:42 +00005489ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00005490 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5491 DeclarationName());
5492 return Rebuilder.TransformExpr(E);
5493}
5494
John McCall99b2fe52010-04-29 23:50:39 +00005495bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5496 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005497
5498 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5499 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5500 DeclarationName());
5501 NestedNameSpecifier *Rebuilt =
5502 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005503 if (!Rebuilt) return true;
5504
5505 SS.setScopeRep(Rebuilt);
5506 return false;
John McCall2408e322010-04-27 00:57:59 +00005507}
5508
Douglas Gregorbe999392009-09-15 16:23:51 +00005509/// \brief Produces a formatted string that describes the binding of
5510/// template parameters to template arguments.
5511std::string
5512Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5513 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005514 // FIXME: For variadic templates, we'll need to get the structured list.
5515 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5516 Args.flat_size());
5517}
5518
5519std::string
5520Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5521 const TemplateArgument *Args,
5522 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005523 std::string Result;
5524
Douglas Gregore62e6a02009-11-11 19:13:48 +00005525 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005526 return Result;
5527
5528 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005529 if (I >= NumArgs)
5530 break;
5531
Douglas Gregorbe999392009-09-15 16:23:51 +00005532 if (I == 0)
5533 Result += "[with ";
5534 else
5535 Result += ", ";
5536
5537 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5538 Result += Id->getName();
5539 } else {
5540 Result += '$';
5541 Result += llvm::utostr(I);
5542 }
5543
5544 Result += " = ";
5545
5546 switch (Args[I].getKind()) {
5547 case TemplateArgument::Null:
5548 Result += "<no value>";
5549 break;
5550
5551 case TemplateArgument::Type: {
5552 std::string TypeStr;
5553 Args[I].getAsType().getAsStringInternal(TypeStr,
5554 Context.PrintingPolicy);
5555 Result += TypeStr;
5556 break;
5557 }
5558
5559 case TemplateArgument::Declaration: {
5560 bool Unnamed = true;
5561 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5562 if (ND->getDeclName()) {
5563 Unnamed = false;
5564 Result += ND->getNameAsString();
5565 }
5566 }
5567
5568 if (Unnamed) {
5569 Result += "<anonymous>";
5570 }
5571 break;
5572 }
5573
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005574 case TemplateArgument::Template: {
5575 std::string Str;
5576 llvm::raw_string_ostream OS(Str);
5577 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5578 Result += OS.str();
5579 break;
5580 }
5581
Douglas Gregorbe999392009-09-15 16:23:51 +00005582 case TemplateArgument::Integral: {
5583 Result += Args[I].getAsIntegral()->toString(10);
5584 break;
5585 }
5586
5587 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005588 // FIXME: This is non-optimal, since we're regurgitating the
5589 // expression we were given.
5590 std::string Str;
5591 {
5592 llvm::raw_string_ostream OS(Str);
5593 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5594 Context.PrintingPolicy);
5595 }
5596 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005597 break;
5598 }
5599
5600 case TemplateArgument::Pack:
5601 // FIXME: Format template argument packs
5602 Result += "<template argument pack>";
5603 break;
5604 }
5605 }
5606
5607 Result += ']';
5608 return Result;
5609}