blob: 0c75cda57e651870b6a785bd903c9ed5853e8890 [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000018#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000020#include "clang/Parse/DeclSpec.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000021#include "clang/Parse/Template.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregorb7bfe792009-09-02 22:59:36 +000027/// \brief Determine whether the declaration found is acceptable as the name
28/// of a template and, if so, return that template declaration. Otherwise,
29/// returns NULL.
30static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
31 if (!D)
32 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000033
Douglas Gregorb7bfe792009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
35 return D;
Mike Stump11289f42009-09-09 15:08:12 +000036
Douglas Gregorb7bfe792009-09-02 22:59:36 +000037 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
38 // C++ [temp.local]p1:
39 // Like normal (non-template) classes, class templates have an
40 // injected-class-name (Clause 9). The injected-class-name
41 // can be used with or without a template-argument-list. When
42 // it is used without a template-argument-list, it is
43 // equivalent to the injected-class-name followed by the
44 // template-parameters of the class template enclosed in
45 // <>. When it is used with a template-argument-list, it
46 // refers to the specified class template specialization,
47 // which could be the current specialization or another
48 // specialization.
49 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000051 if (Record->getDescribedClassTemplate())
52 return Record->getDescribedClassTemplate();
53
54 if (ClassTemplateSpecializationDecl *Spec
55 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
56 return Spec->getSpecializedTemplate();
57 }
Mike Stump11289f42009-09-09 15:08:12 +000058
Douglas Gregorb7bfe792009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump11289f42009-09-09 15:08:12 +000061
Douglas Gregorb7bfe792009-09-02 22:59:36 +000062 return 0;
63}
64
John McCalle66edc12009-11-24 19:00:30 +000065static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor41f90302010-04-12 20:54:26 +000066 // The set of class templates we've already seen.
67 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000068 LookupResult::Filter filter = R.makeFilter();
69 while (filter.hasNext()) {
70 NamedDecl *Orig = filter.next();
71 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
72 if (!Repl)
73 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +000074 else if (Repl != Orig) {
75
76 // C++ [temp.local]p3:
77 // A lookup that finds an injected-class-name (10.2) can result in an
78 // ambiguity in certain cases (for example, if it is found in more than
79 // one base class). If all of the injected-class-names that are found
80 // refer to specializations of the same class template, and if the name
81 // is followed by a template-argument-list, the reference refers to the
82 // class template itself and not a specialization thereof, and is not
83 // ambiguous.
84 //
85 // FIXME: Will we eventually have to do the same for alias templates?
86 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
87 if (!ClassTemplates.insert(ClassTmpl)) {
88 filter.erase();
89 continue;
90 }
91
John McCalle66edc12009-11-24 19:00:30 +000092 filter.replace(Repl);
Douglas Gregor41f90302010-04-12 20:54:26 +000093 }
John McCalle66edc12009-11-24 19:00:30 +000094 }
95 filter.done();
96}
97
Douglas Gregorb7bfe792009-09-02 22:59:36 +000098TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +000099 CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000100 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000101 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000102 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000103 TemplateTy &TemplateResult,
104 bool &MemberOfUnknownSpecialization) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000105 assert(getLangOptions().CPlusPlus && "No template names in C!");
106
Douglas Gregor3cf81312009-11-03 23:16:33 +0000107 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000108 MemberOfUnknownSpecialization = false;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000109
110 switch (Name.getKind()) {
111 case UnqualifiedId::IK_Identifier:
112 TName = DeclarationName(Name.Identifier);
113 break;
114
115 case UnqualifiedId::IK_OperatorFunctionId:
116 TName = Context.DeclarationNames.getCXXOperatorName(
117 Name.OperatorFunctionId.Operator);
118 break;
119
Alexis Hunted0530f2009-11-28 08:58:14 +0000120 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000121 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
122 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000123
Douglas Gregor3cf81312009-11-03 23:16:33 +0000124 default:
125 return TNK_Non_template;
126 }
Mike Stump11289f42009-09-09 15:08:12 +0000127
John McCalle66edc12009-11-24 19:00:30 +0000128 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump11289f42009-09-09 15:08:12 +0000129
Douglas Gregorff18cc12009-12-31 08:11:17 +0000130 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
131 LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +0000132 R.suppressDiagnostics();
Douglas Gregor786123d2010-05-21 23:18:07 +0000133 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
134 MemberOfUnknownSpecialization);
Douglas Gregor41f90302010-04-12 20:54:26 +0000135 if (R.empty() || R.isAmbiguous())
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000136 return TNK_Non_template;
137
John McCalld28ae272009-12-02 08:04:21 +0000138 TemplateName Template;
139 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000140
John McCalld28ae272009-12-02 08:04:21 +0000141 unsigned ResultCount = R.end() - R.begin();
142 if (ResultCount > 1) {
143 // We assume that we'll preserve the qualifier from a function
144 // template name in other ways.
145 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
146 TemplateKind = TNK_Function_template;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000147 } else {
John McCalld28ae272009-12-02 08:04:21 +0000148 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
149
150 if (SS.isSet() && !SS.isInvalid()) {
151 NestedNameSpecifier *Qualifier
152 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
153 Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
154 } else {
155 Template = TemplateName(TD);
156 }
157
158 if (isa<FunctionTemplateDecl>(TD))
159 TemplateKind = TNK_Function_template;
160 else {
161 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
162 TemplateKind = TNK_Type_template;
163 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000164 }
Mike Stump11289f42009-09-09 15:08:12 +0000165
John McCalld28ae272009-12-02 08:04:21 +0000166 TemplateResult = TemplateTy::make(Template);
167 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000168}
169
Douglas Gregor18473f32010-01-12 21:28:44 +0000170bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
171 SourceLocation IILoc,
172 Scope *S,
173 const CXXScopeSpec *SS,
174 TemplateTy &SuggestedTemplate,
175 TemplateNameKind &SuggestedKind) {
176 // We can't recover unless there's a dependent scope specifier preceding the
177 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000178 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000179 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
180 computeDeclContext(*SS))
181 return false;
182
183 // The code is missing a 'template' keyword prior to the dependent template
184 // name.
185 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
186 Diag(IILoc, diag::err_template_kw_missing)
187 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000188 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor18473f32010-01-12 21:28:44 +0000189 SuggestedTemplate
190 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
191 SuggestedKind = TNK_Dependent_template_name;
192 return true;
193}
194
John McCalle66edc12009-11-24 19:00:30 +0000195void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000196 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000197 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000198 bool EnteringContext,
199 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000200 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000201 MemberOfUnknownSpecialization = false;
John McCalle66edc12009-11-24 19:00:30 +0000202 DeclContext *LookupCtx = 0;
203 bool isDependent = false;
204 if (!ObjectType.isNull()) {
205 // This nested-name-specifier occurs in a member access expression, e.g.,
206 // x->B::f, and we are looking into the type of the object.
207 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
208 LookupCtx = computeDeclContext(ObjectType);
209 isDependent = ObjectType->isDependentType();
210 assert((isDependent || !ObjectType->isIncompleteType()) &&
211 "Caller should have completed object type");
212 } else if (SS.isSet()) {
213 // This nested-name-specifier occurs after another nested-name-specifier,
214 // so long into the context associated with the prior nested-name-specifier.
215 LookupCtx = computeDeclContext(SS, EnteringContext);
216 isDependent = isDependentScopeSpecifier(SS);
217
218 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000219 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000220 return;
221 }
222
223 bool ObjectTypeSearchedInScope = false;
224 if (LookupCtx) {
225 // Perform "qualified" name lookup into the declaration context we
226 // computed, which is either the type of the base of a member access
227 // expression or the declaration context associated with a prior
228 // nested-name-specifier.
229 LookupQualifiedName(Found, LookupCtx);
230
231 if (!ObjectType.isNull() && Found.empty()) {
232 // C++ [basic.lookup.classref]p1:
233 // In a class member access expression (5.2.5), if the . or -> token is
234 // immediately followed by an identifier followed by a <, the
235 // identifier must be looked up to determine whether the < is the
236 // beginning of a template argument list (14.2) or a less-than operator.
237 // The identifier is first looked up in the class of the object
238 // expression. If the identifier is not found, it is then looked up in
239 // the context of the entire postfix-expression and shall name a class
240 // or function template.
241 //
242 // FIXME: When we're instantiating a template, do we actually have to
243 // look in the scope of the template? Seems fishy...
244 if (S) LookupName(Found, S);
245 ObjectTypeSearchedInScope = true;
246 }
247 } else if (isDependent) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000248 // We cannot look into a dependent object type or nested nme
249 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000250 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000251 return;
252 } else {
253 // Perform unqualified name lookup in the current scope.
254 LookupName(Found, S);
255 }
256
Douglas Gregorc119dd52010-01-12 17:06:20 +0000257 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000258 // If we did not find any names, attempt to correct any typos.
259 DeclarationName Name = Found.getLookupName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000260 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
261 false, CTC_CXXCasts)) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000262 FilterAcceptableTemplateNames(Context, Found);
263 if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
264 if (LookupCtx)
265 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
266 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000267 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000268 Found.getLookupName().getAsString());
269 else
270 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
271 << Name << Found.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +0000272 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000273 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000274 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
275 Diag(Template->getLocation(), diag::note_previous_decl)
276 << Template->getDeclName();
Douglas Gregorff18cc12009-12-31 08:11:17 +0000277 } else
278 Found.clear();
279 } else {
280 Found.clear();
281 }
282 }
283
John McCalle66edc12009-11-24 19:00:30 +0000284 FilterAcceptableTemplateNames(Context, Found);
285 if (Found.empty())
286 return;
287
288 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
289 // C++ [basic.lookup.classref]p1:
290 // [...] If the lookup in the class of the object expression finds a
291 // template, the name is also looked up in the context of the entire
292 // postfix-expression and [...]
293 //
294 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
295 LookupOrdinaryName);
296 LookupName(FoundOuter, S);
297 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor41f90302010-04-12 20:54:26 +0000298
John McCalle66edc12009-11-24 19:00:30 +0000299 if (FoundOuter.empty()) {
300 // - if the name is not found, the name found in the class of the
301 // object expression is used, otherwise
302 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
303 // - if the name is found in the context of the entire
304 // postfix-expression and does not name a class template, the name
305 // found in the class of the object expression is used, otherwise
306 } else {
307 // - if the name found is a class template, it must refer to the same
308 // entity as the one found in the class of the object expression,
309 // otherwise the program is ill-formed.
310 if (!Found.isSingleResult() ||
311 Found.getFoundDecl()->getCanonicalDecl()
312 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
313 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000314 diag::ext_nested_name_member_ref_lookup_ambiguous)
315 << Found.getLookupName()
316 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000317 Diag(Found.getRepresentativeDecl()->getLocation(),
318 diag::note_ambig_member_ref_object_type)
319 << ObjectType;
320 Diag(FoundOuter.getFoundDecl()->getLocation(),
321 diag::note_ambig_member_ref_scope);
322
323 // Recover by taking the template that we found in the object
324 // expression's type.
325 }
326 }
327 }
328}
329
John McCallcd4b4772009-12-02 03:53:29 +0000330/// ActOnDependentIdExpression - Handle a dependent id-expression that
331/// was just parsed. This is only possible with an explicit scope
332/// specifier naming a dependent type.
John McCalle66edc12009-11-24 19:00:30 +0000333Sema::OwningExprResult
334Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
335 DeclarationName Name,
336 SourceLocation NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +0000337 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000338 const TemplateArgumentListInfo *TemplateArgs) {
339 NestedNameSpecifier *Qualifier
340 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall87fe5d52010-05-20 01:18:31 +0000341
342 DeclContext *DC = getFunctionLevelDeclContext();
John McCalle66edc12009-11-24 19:00:30 +0000343
John McCallcd4b4772009-12-02 03:53:29 +0000344 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000345 isa<CXXMethodDecl>(DC) &&
346 cast<CXXMethodDecl>(DC)->isInstance()) {
347 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCallcd4b4772009-12-02 03:53:29 +0000348
John McCalle66edc12009-11-24 19:00:30 +0000349 // Since the 'this' expression is synthesized, we don't need to
350 // perform the double-lookup check.
351 NamedDecl *FirstQualifierInScope = 0;
352
John McCall2d74de92009-12-01 22:10:20 +0000353 return Owned(CXXDependentScopeMemberExpr::Create(Context,
354 /*This*/ 0, ThisType,
355 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000356 /*Op*/ SourceLocation(),
357 Qualifier, SS.getRange(),
358 FirstQualifierInScope,
359 Name, NameLoc,
360 TemplateArgs));
361 }
362
363 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
364}
365
366Sema::OwningExprResult
367Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
368 DeclarationName Name,
369 SourceLocation NameLoc,
370 const TemplateArgumentListInfo *TemplateArgs) {
371 return Owned(DependentScopeDeclRefExpr::Create(Context,
372 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
373 SS.getRange(),
374 Name, NameLoc,
375 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000376}
377
Douglas Gregor5101c242008-12-05 18:15:24 +0000378/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
379/// that the template parameter 'PrevDecl' is being shadowed by a new
380/// declaration at location Loc. Returns true to indicate that this is
381/// an error, and false otherwise.
382bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000383 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000384
385 // Microsoft Visual C++ permits template parameters to be shadowed.
386 if (getLangOptions().Microsoft)
387 return false;
388
389 // C++ [temp.local]p4:
390 // A template-parameter shall not be redeclared within its
391 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000392 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000393 << cast<NamedDecl>(PrevDecl)->getDeclName();
394 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
395 return true;
396}
397
Douglas Gregor463421d2009-03-03 04:44:36 +0000398/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000399/// the parameter D to reference the templated declaration and return a pointer
400/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000401TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000402 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000403 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000404 return Temp;
405 }
406 return 0;
407}
408
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000409static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
410 const ParsedTemplateArgument &Arg) {
411
412 switch (Arg.getKind()) {
413 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000414 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000415 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
416 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000417 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000418 return TemplateArgumentLoc(TemplateArgument(T), DI);
419 }
420
421 case ParsedTemplateArgument::NonType: {
422 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
423 return TemplateArgumentLoc(TemplateArgument(E), E);
424 }
425
426 case ParsedTemplateArgument::Template: {
427 TemplateName Template
428 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
429 return TemplateArgumentLoc(TemplateArgument(Template),
430 Arg.getScopeSpec().getRange(),
431 Arg.getLocation());
432 }
433 }
434
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000435 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000436 return TemplateArgumentLoc();
437}
438
439/// \brief Translates template arguments as provided by the parser
440/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000441void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
442 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000443 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000444 TemplateArgs.addArgument(translateTemplateArgument(*this,
445 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000446}
447
Douglas Gregor5101c242008-12-05 18:15:24 +0000448/// ActOnTypeParameter - Called when a C++ template type parameter
449/// (e.g., "typename T") has been parsed. Typename specifies whether
450/// the keyword "typename" was used to declare the type parameter
451/// (otherwise, "class" was used), and KeyLoc is the location of the
452/// "class" or "typename" keyword. ParamName is the name of the
453/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000454/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000455/// If the type parameter has a default argument, it will be added
456/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000457Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000458 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000459 SourceLocation KeyLoc,
460 IdentifierInfo *ParamName,
461 SourceLocation ParamNameLoc,
462 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000463 assert(S->isTemplateParamScope() &&
464 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000465 bool Invalid = false;
466
467 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000468 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000469 LookupOrdinaryName,
470 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000471 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000472 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000473 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000474 }
475
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000476 SourceLocation Loc = ParamNameLoc;
477 if (!ParamName)
478 Loc = KeyLoc;
479
Douglas Gregor5101c242008-12-05 18:15:24 +0000480 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000481 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
482 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000483 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000484 if (Invalid)
485 Param->setInvalidDecl();
486
487 if (ParamName) {
488 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000489 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000490 IdResolver.AddDecl(Param);
491 }
492
Chris Lattner83f095c2009-03-28 19:18:32 +0000493 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000494}
495
Douglas Gregordba32632009-02-10 19:49:53 +0000496/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000497/// Default) to the given template type parameter (TypeParam).
498void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000499 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000500 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000501 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000502 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000503 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000504
John McCallbcd03502009-12-07 02:54:59 +0000505 TypeSourceInfo *DefaultTInfo;
506 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall0ad16662009-10-29 08:12:44 +0000507
John McCallbcd03502009-12-07 02:54:59 +0000508 assert(DefaultTInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000509
Anders Carlssond3824352009-06-12 22:30:13 +0000510 // C++0x [temp.param]p9:
511 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000512 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000513 if (Parm->isParameterPack()) {
514 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000515 return;
516 }
Mike Stump11289f42009-09-09 15:08:12 +0000517
Douglas Gregordba32632009-02-10 19:49:53 +0000518 // C++ [temp.param]p14:
519 // A template-parameter shall not be used in its own default argument.
520 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000521
Douglas Gregordba32632009-02-10 19:49:53 +0000522 // Check the template argument itself.
John McCallbcd03502009-12-07 02:54:59 +0000523 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000524 Parm->setInvalidDecl();
525 return;
526 }
527
John McCallbcd03502009-12-07 02:54:59 +0000528 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000529}
530
Douglas Gregor463421d2009-03-03 04:44:36 +0000531/// \brief Check that the type of a non-type template parameter is
532/// well-formed.
533///
534/// \returns the (possibly-promoted) parameter type if valid;
535/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000536QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000537Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000538 // We don't allow variably-modified types as the type of non-type template
539 // parameters.
540 if (T->isVariablyModifiedType()) {
541 Diag(Loc, diag::err_variably_modified_nontype_template_param)
542 << T;
543 return QualType();
544 }
545
Douglas Gregor463421d2009-03-03 04:44:36 +0000546 // C++ [temp.param]p4:
547 //
548 // A non-type template-parameter shall have one of the following
549 // (optionally cv-qualified) types:
550 //
551 // -- integral or enumeration type,
552 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000553 // -- pointer to object or pointer to function,
554 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000555 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
556 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000557 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000558 T->isReferenceType() ||
559 // -- pointer to member.
560 T->isMemberPointerType() ||
561 // If T is a dependent type, we can't do the check now, so we
562 // assume that it is well-formed.
563 T->isDependentType())
564 return T;
565 // C++ [temp.param]p8:
566 //
567 // A non-type template-parameter of type "array of T" or
568 // "function returning T" is adjusted to be of type "pointer to
569 // T" or "pointer to function returning T", respectively.
570 else if (T->isArrayType())
571 // FIXME: Keep the type prior to promotion?
572 return Context.getArrayDecayedType(T);
573 else if (T->isFunctionType())
574 // FIXME: Keep the type prior to promotion?
575 return Context.getPointerType(T);
Douglas Gregor959d5a02010-05-22 16:17:30 +0000576
Douglas Gregor463421d2009-03-03 04:44:36 +0000577 Diag(Loc, diag::err_template_nontype_parm_bad_type)
578 << T;
579
580 return QualType();
581}
582
Douglas Gregor5101c242008-12-05 18:15:24 +0000583/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
584/// template parameter (e.g., "int Size" in "template<int Size>
585/// class Array") has been parsed. S is the current scope and D is
586/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000587Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000588 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000589 unsigned Position) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000590 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
591 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000592
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000593 assert(S->isTemplateParamScope() &&
594 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000595 bool Invalid = false;
596
597 IdentifierInfo *ParamName = D.getIdentifier();
598 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000599 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000600 LookupOrdinaryName,
601 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000602 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000603 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000604 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000605 }
606
Douglas Gregor463421d2009-03-03 04:44:36 +0000607 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000608 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000609 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000610 Invalid = true;
611 }
Douglas Gregor81338792009-02-10 17:43:50 +0000612
Douglas Gregor5101c242008-12-05 18:15:24 +0000613 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000614 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
615 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000616 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000617 if (Invalid)
618 Param->setInvalidDecl();
619
620 if (D.getIdentifier()) {
621 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000622 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000623 IdResolver.AddDecl(Param);
624 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000625 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000626}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000627
Douglas Gregordba32632009-02-10 19:49:53 +0000628/// \brief Adds a default argument to the given non-type template
629/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000630void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000631 SourceLocation EqualLoc,
632 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000633 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000634 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000635 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000636
Douglas Gregordba32632009-02-10 19:49:53 +0000637 // C++ [temp.param]p14:
638 // A template-parameter shall not be used in its own default argument.
639 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000640
Douglas Gregordba32632009-02-10 19:49:53 +0000641 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000642 TemplateArgument Converted;
643 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
644 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000645 TemplateParm->setInvalidDecl();
646 return;
647 }
648
Abramo Bagnara656e3002010-06-09 09:26:05 +0000649 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>(), false);
Douglas Gregordba32632009-02-10 19:49:53 +0000650}
651
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000652
653/// ActOnTemplateTemplateParameter - Called when a C++ template template
654/// parameter (e.g. T in template <template <typename> class T> class array)
655/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000656Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
657 SourceLocation TmpLoc,
658 TemplateParamsTy *Params,
659 IdentifierInfo *Name,
660 SourceLocation NameLoc,
661 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000662 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000663 assert(S->isTemplateParamScope() &&
664 "Template template parameter not in template parameter scope!");
665
666 // Construct the parameter object.
667 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000668 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
669 TmpLoc, Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000670 (TemplateParameterList*)Params);
671
672 // Make sure the parameter is valid.
673 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
674 // do anything yet. However, if the template parameter list or (eventual)
675 // default value is ever invalidated, that will propagate here.
676 bool Invalid = false;
677 if (Invalid) {
678 Param->setInvalidDecl();
679 }
680
681 // If the tt-param has a name, then link the identifier into the scope
682 // and lookup mechanisms.
683 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000684 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000685 IdResolver.AddDecl(Param);
686 }
687
Chris Lattner83f095c2009-03-28 19:18:32 +0000688 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000689}
690
Douglas Gregordba32632009-02-10 19:49:53 +0000691/// \brief Adds a default argument to the given template template
692/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000693void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000694 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000695 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000696 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000697 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000698
Douglas Gregordba32632009-02-10 19:49:53 +0000699 // C++ [temp.param]p14:
700 // A template-parameter shall not be used in its own default argument.
701 // FIXME: Implement this check! Needs a recursive walk over the types.
702
Douglas Gregore62e6a02009-11-11 19:13:48 +0000703 // Check only that we have a template template argument. We don't want to
704 // try to check well-formedness now, because our template template parameter
705 // might have dependent types in its template parameters, which we wouldn't
706 // be able to match now.
707 //
708 // If none of the template template parameter's template arguments mention
709 // other template parameters, we could actually perform more checking here.
710 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000711 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000712 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
713 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
714 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000715 return;
716 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000717
Abramo Bagnara656e3002010-06-09 09:26:05 +0000718 TemplateParm->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000719}
720
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000721/// ActOnTemplateParameterList - Builds a TemplateParameterList that
722/// contains the template parameters in Params/NumParams.
723Sema::TemplateParamsTy *
724Sema::ActOnTemplateParameterList(unsigned Depth,
725 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000726 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000727 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000728 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000729 SourceLocation RAngleLoc) {
730 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000731 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000732
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000733 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000734 (NamedDecl**)Params, NumParams,
735 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000736}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000737
John McCall3e11ebe2010-03-15 10:12:16 +0000738static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
739 if (SS.isSet())
740 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
741 SS.getRange());
742}
743
Douglas Gregorc08f4892009-03-25 00:13:59 +0000744Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000745Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000746 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000747 IdentifierInfo *Name, SourceLocation NameLoc,
748 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000749 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000750 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000751 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000752 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000753 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000754 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000755
756 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000757 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000758 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000759
Abramo Bagnara6150c882010-05-11 21:36:43 +0000760 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
761 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000762
763 // There is no such thing as an unnamed class template.
764 if (!Name) {
765 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000766 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000767 }
768
769 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000770 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000771 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000772 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000773 if (SS.isNotEmpty() && !SS.isInvalid()) {
774 SemanticContext = computeDeclContext(SS, true);
775 if (!SemanticContext) {
776 // FIXME: Produce a reasonable diagnostic here
777 return true;
778 }
Mike Stump11289f42009-09-09 15:08:12 +0000779
John McCall0b66eb32010-05-01 00:40:08 +0000780 if (RequireCompleteDeclContext(SS, SemanticContext))
781 return true;
782
John McCall27b18f82009-11-17 02:14:36 +0000783 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000784 } else {
785 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000786 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000787 }
Mike Stump11289f42009-09-09 15:08:12 +0000788
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000789 if (Previous.isAmbiguous())
790 return true;
791
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000792 NamedDecl *PrevDecl = 0;
793 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000794 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000795
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000796 // If there is a previous declaration with the same name, check
797 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000798 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000799 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000800
801 // We may have found the injected-class-name of a class template,
802 // class template partial specialization, or class template specialization.
803 // In these cases, grab the template that is being defined or specialized.
804 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
805 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
806 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
807 PrevClassTemplate
808 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
809 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
810 PrevClassTemplate
811 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
812 ->getSpecializedTemplate();
813 }
814 }
815
John McCalld43784f2009-12-18 11:25:59 +0000816 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000817 // C++ [namespace.memdef]p3:
818 // [...] When looking for a prior declaration of a class or a function
819 // declared as a friend, and when the name of the friend class or
820 // function is neither a qualified name nor a template-id, scopes outside
821 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000822 if (!SS.isSet()) {
823 DeclContext *OutermostContext = CurContext;
824 while (!OutermostContext->isFileContext())
825 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000826
Douglas Gregorb74b1032010-04-18 17:37:40 +0000827 if (PrevDecl &&
828 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
829 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
830 SemanticContext = PrevDecl->getDeclContext();
831 } else {
832 // Declarations in outer scopes don't matter. However, the outermost
833 // context we computed is the semantic context for our new
834 // declaration.
835 PrevDecl = PrevClassTemplate = 0;
836 SemanticContext = OutermostContext;
837 }
John McCall90d3bb92009-12-17 23:21:11 +0000838 }
Douglas Gregorb74b1032010-04-18 17:37:40 +0000839
John McCall90d3bb92009-12-17 23:21:11 +0000840 if (CurContext->isDependentContext()) {
841 // If this is a dependent context, we don't want to link the friend
842 // class template to the template in scope, because that would perform
843 // checking of the template parameter lists that can't be performed
844 // until the outer context is instantiated.
845 PrevDecl = PrevClassTemplate = 0;
846 }
847 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
848 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000849
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000850 if (PrevClassTemplate) {
851 // Ensure that the template parameter lists are compatible.
852 if (!TemplateParameterListsAreEqual(TemplateParams,
853 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000854 /*Complain=*/true,
855 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000856 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000857
858 // C++ [temp.class]p4:
859 // In a redeclaration, partial specialization, explicit
860 // specialization or explicit instantiation of a class template,
861 // the class-key shall agree in kind with the original class
862 // template declaration (7.1.5.3).
863 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000864 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000865 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000866 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000867 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000868 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000869 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000870 }
871
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000872 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000873 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000874 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000875 Diag(NameLoc, diag::err_redefinition) << Name;
876 Diag(Def->getLocation(), diag::note_previous_definition);
877 // FIXME: Would it make sense to try to "forget" the previous
878 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000879 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000880 }
881 }
882 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
883 // Maybe we will complain about the shadowed template parameter.
884 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
885 // Just pretend that we didn't see the previous declaration.
886 PrevDecl = 0;
887 } else if (PrevDecl) {
888 // C++ [temp]p5:
889 // A class template shall not have the same name as any other
890 // template, class, function, object, enumeration, enumerator,
891 // namespace, or type in the same scope (3.3), except as specified
892 // in (14.5.4).
893 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
894 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000895 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000896 }
897
Douglas Gregordba32632009-02-10 19:49:53 +0000898 // Check the template parameter list of this declaration, possibly
899 // merging in the template parameter list from the previous class
900 // template declaration.
901 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000902 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
903 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000904 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000905
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000906 if (SS.isSet()) {
907 // If the name of the template was qualified, we must be defining the
908 // template out-of-line.
909 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
910 !(TUK == TUK_Friend && CurContext->isDependentContext()))
911 Diag(NameLoc, diag::err_member_def_does_not_match)
912 << Name << SemanticContext << SS.getRange();
913 }
914
Mike Stump11289f42009-09-09 15:08:12 +0000915 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000916 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000917 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000918 PrevClassTemplate->getTemplatedDecl() : 0,
919 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000920 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000921
922 ClassTemplateDecl *NewTemplate
923 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
924 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000925 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000926 NewClass->setDescribedClassTemplate(NewTemplate);
927
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000928 // Build the type for the class template declaration now.
John McCalle78aac42010-03-10 03:28:59 +0000929 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
930 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000931 assert(T->isDependentType() && "Class template type is not dependent?");
932 (void)T;
933
Douglas Gregorcf915552009-10-13 16:30:37 +0000934 // If we are providing an explicit specialization of a member that is a
935 // class template, make a note of that.
936 if (PrevClassTemplate &&
937 PrevClassTemplate->getInstantiatedFromMemberTemplate())
938 PrevClassTemplate->setMemberSpecialization();
939
Anders Carlsson137108d2009-03-26 01:24:28 +0000940 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000941 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000942 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000943
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000944 // Set the lexical context of these templates
945 NewClass->setLexicalDeclContext(CurContext);
946 NewTemplate->setLexicalDeclContext(CurContext);
947
John McCall9bb74a52009-07-31 02:45:11 +0000948 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000949 NewClass->startDefinition();
950
951 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000952 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000953
John McCall27b5c252009-09-14 21:59:20 +0000954 if (TUK != TUK_Friend)
955 PushOnScopeChains(NewTemplate, S);
956 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000957 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000958 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000959 NewClass->setAccess(PrevClassTemplate->getAccess());
960 }
John McCall27b5c252009-09-14 21:59:20 +0000961
Douglas Gregor3dad8422009-09-26 06:47:28 +0000962 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
963 PrevClassTemplate != NULL);
964
John McCall27b5c252009-09-14 21:59:20 +0000965 // Friend templates are visible in fairly strange ways.
966 if (!CurContext->isDependentContext()) {
967 DeclContext *DC = SemanticContext->getLookupContext();
968 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
969 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
970 PushOnScopeChains(NewTemplate, EnclosingScope,
971 /* AddToContext = */ false);
972 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000973
974 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
975 NewClass->getLocation(),
976 NewTemplate,
977 /*FIXME:*/NewClass->getLocation());
978 Friend->setAccess(AS_public);
979 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000980 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000981
Douglas Gregordba32632009-02-10 19:49:53 +0000982 if (Invalid) {
983 NewTemplate->setInvalidDecl();
984 NewClass->setInvalidDecl();
985 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000986 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000987}
988
Douglas Gregored5731f2009-11-25 17:50:39 +0000989/// \brief Diagnose the presence of a default template argument on a
990/// template parameter, which is ill-formed in certain contexts.
991///
992/// \returns true if the default template argument should be dropped.
993static bool DiagnoseDefaultTemplateArgument(Sema &S,
994 Sema::TemplateParamListContext TPC,
995 SourceLocation ParamLoc,
996 SourceRange DefArgRange) {
997 switch (TPC) {
998 case Sema::TPC_ClassTemplate:
999 return false;
1000
1001 case Sema::TPC_FunctionTemplate:
1002 // C++ [temp.param]p9:
1003 // A default template-argument shall not be specified in a
1004 // function template declaration or a function template
1005 // definition [...]
1006 // (This sentence is not in C++0x, per DR226).
1007 if (!S.getLangOptions().CPlusPlus0x)
1008 S.Diag(ParamLoc,
1009 diag::err_template_parameter_default_in_function_template)
1010 << DefArgRange;
1011 return false;
1012
1013 case Sema::TPC_ClassTemplateMember:
1014 // C++0x [temp.param]p9:
1015 // A default template-argument shall not be specified in the
1016 // template-parameter-lists of the definition of a member of a
1017 // class template that appears outside of the member's class.
1018 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1019 << DefArgRange;
1020 return true;
1021
1022 case Sema::TPC_FriendFunctionTemplate:
1023 // C++ [temp.param]p9:
1024 // A default template-argument shall not be specified in a
1025 // friend template declaration.
1026 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1027 << DefArgRange;
1028 return true;
1029
1030 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1031 // for friend function templates if there is only a single
1032 // declaration (and it is a definition). Strange!
1033 }
1034
1035 return false;
1036}
1037
Douglas Gregordba32632009-02-10 19:49:53 +00001038/// \brief Checks the validity of a template parameter list, possibly
1039/// considering the template parameter list from a previous
1040/// declaration.
1041///
1042/// If an "old" template parameter list is provided, it must be
1043/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1044/// template parameter list.
1045///
1046/// \param NewParams Template parameter list for a new template
1047/// declaration. This template parameter list will be updated with any
1048/// default arguments that are carried through from the previous
1049/// template parameter list.
1050///
1051/// \param OldParams If provided, template parameter list from a
1052/// previous declaration of the same template. Default template
1053/// arguments will be merged from the old template parameter list to
1054/// the new template parameter list.
1055///
Douglas Gregored5731f2009-11-25 17:50:39 +00001056/// \param TPC Describes the context in which we are checking the given
1057/// template parameter list.
1058///
Douglas Gregordba32632009-02-10 19:49:53 +00001059/// \returns true if an error occurred, false otherwise.
1060bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001061 TemplateParameterList *OldParams,
1062 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001063 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001064
Douglas Gregordba32632009-02-10 19:49:53 +00001065 // C++ [temp.param]p10:
1066 // The set of default template-arguments available for use with a
1067 // template declaration or definition is obtained by merging the
1068 // default arguments from the definition (if in scope) and all
1069 // declarations in scope in the same way default function
1070 // arguments are (8.3.6).
1071 bool SawDefaultArgument = false;
1072 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001073
Anders Carlsson327865d2009-06-12 23:20:15 +00001074 bool SawParameterPack = false;
1075 SourceLocation ParameterPackLoc;
1076
Mike Stumpc89c8e32009-02-11 23:03:27 +00001077 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001078 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001079 if (OldParams)
1080 OldParam = OldParams->begin();
1081
1082 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1083 NewParamEnd = NewParams->end();
1084 NewParam != NewParamEnd; ++NewParam) {
1085 // Variables used to diagnose redundant default arguments
1086 bool RedundantDefaultArg = false;
1087 SourceLocation OldDefaultLoc;
1088 SourceLocation NewDefaultLoc;
1089
1090 // Variables used to diagnose missing default arguments
1091 bool MissingDefaultArg = false;
1092
Anders Carlsson327865d2009-06-12 23:20:15 +00001093 // C++0x [temp.param]p11:
1094 // If a template parameter of a class template is a template parameter pack,
1095 // it must be the last template parameter.
1096 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001097 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001098 diag::err_template_param_pack_must_be_last_template_parameter);
1099 Invalid = true;
1100 }
1101
Douglas Gregordba32632009-02-10 19:49:53 +00001102 if (TemplateTypeParmDecl *NewTypeParm
1103 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001104 // Check the presence of a default argument here.
1105 if (NewTypeParm->hasDefaultArgument() &&
1106 DiagnoseDefaultTemplateArgument(*this, TPC,
1107 NewTypeParm->getLocation(),
1108 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001109 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001110 NewTypeParm->removeDefaultArgument();
1111
1112 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001113 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001114 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001115
Anders Carlsson327865d2009-06-12 23:20:15 +00001116 if (NewTypeParm->isParameterPack()) {
1117 assert(!NewTypeParm->hasDefaultArgument() &&
1118 "Parameter packs can't have a default argument!");
1119 SawParameterPack = true;
1120 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001121 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001122 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001123 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1124 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1125 SawDefaultArgument = true;
1126 RedundantDefaultArg = true;
1127 PreviousDefaultArgLoc = NewDefaultLoc;
1128 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1129 // Merge the default argument from the old declaration to the
1130 // new declaration.
1131 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001132 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001133 true);
1134 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1135 } else if (NewTypeParm->hasDefaultArgument()) {
1136 SawDefaultArgument = true;
1137 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1138 } else if (SawDefaultArgument)
1139 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001140 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001141 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001142 // Check the presence of a default argument here.
1143 if (NewNonTypeParm->hasDefaultArgument() &&
1144 DiagnoseDefaultTemplateArgument(*this, TPC,
1145 NewNonTypeParm->getLocation(),
1146 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1147 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
Abramo Bagnara656e3002010-06-09 09:26:05 +00001148 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001149 }
1150
Mike Stump12b8ce12009-08-04 21:02:39 +00001151 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001152 NonTypeTemplateParmDecl *OldNonTypeParm
1153 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001154 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001155 NewNonTypeParm->hasDefaultArgument()) {
1156 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1157 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1158 SawDefaultArgument = true;
1159 RedundantDefaultArg = true;
1160 PreviousDefaultArgLoc = NewDefaultLoc;
1161 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1162 // Merge the default argument from the old declaration to the
1163 // new declaration.
1164 SawDefaultArgument = true;
1165 // FIXME: We need to create a new kind of "default argument"
1166 // expression that points to a previous template template
1167 // parameter.
1168 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001169 OldNonTypeParm->getDefaultArgument(),
1170 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001171 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1172 } else if (NewNonTypeParm->hasDefaultArgument()) {
1173 SawDefaultArgument = true;
1174 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1175 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001176 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001177 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001178 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001179 TemplateTemplateParmDecl *NewTemplateParm
1180 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001181 if (NewTemplateParm->hasDefaultArgument() &&
1182 DiagnoseDefaultTemplateArgument(*this, TPC,
1183 NewTemplateParm->getLocation(),
1184 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001185 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001186
1187 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001188 TemplateTemplateParmDecl *OldTemplateParm
1189 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001190 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001191 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001192 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1193 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001194 SawDefaultArgument = true;
1195 RedundantDefaultArg = true;
1196 PreviousDefaultArgLoc = NewDefaultLoc;
1197 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1198 // Merge the default argument from the old declaration to the
1199 // new declaration.
1200 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001201 // FIXME: We need to create a new kind of "default argument" expression
1202 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001203 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001204 OldTemplateParm->getDefaultArgument(),
1205 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001206 PreviousDefaultArgLoc
1207 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001208 } else if (NewTemplateParm->hasDefaultArgument()) {
1209 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001210 PreviousDefaultArgLoc
1211 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001212 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001213 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001214 }
1215
1216 if (RedundantDefaultArg) {
1217 // C++ [temp.param]p12:
1218 // A template-parameter shall not be given default arguments
1219 // by two different declarations in the same scope.
1220 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1221 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1222 Invalid = true;
1223 } else if (MissingDefaultArg) {
1224 // C++ [temp.param]p11:
1225 // If a template-parameter has a default template-argument,
1226 // all subsequent template-parameters shall have a default
1227 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001228 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001229 diag::err_template_param_default_arg_missing);
1230 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1231 Invalid = true;
1232 }
1233
1234 // If we have an old template parameter list that we're merging
1235 // in, move on to the next parameter.
1236 if (OldParams)
1237 ++OldParam;
1238 }
1239
1240 return Invalid;
1241}
Douglas Gregord32e0282009-02-09 23:23:08 +00001242
Mike Stump11289f42009-09-09 15:08:12 +00001243/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001244/// specifier, returning the template parameter list that applies to the
1245/// name.
1246///
1247/// \param DeclStartLoc the start of the declaration that has a scope
1248/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001249///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001250/// \param SS the scope specifier that will be matched to the given template
1251/// parameter lists. This scope specifier precedes a qualified name that is
1252/// being declared.
1253///
1254/// \param ParamLists the template parameter lists, from the outermost to the
1255/// innermost template parameter lists.
1256///
1257/// \param NumParamLists the number of template parameter lists in ParamLists.
1258///
John McCalle820e5e2010-04-13 20:37:33 +00001259/// \param IsFriend Whether to apply the slightly different rules for
1260/// matching template parameters to scope specifiers in friend
1261/// declarations.
1262///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001263/// \param IsExplicitSpecialization will be set true if the entity being
1264/// declared is an explicit specialization, false otherwise.
1265///
Mike Stump11289f42009-09-09 15:08:12 +00001266/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001267/// name that is preceded by the scope specifier @p SS. This template
1268/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001269/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001270/// template specialization), or may be NULL (if we were's declaring isn't
1271/// itself a template).
1272TemplateParameterList *
1273Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1274 const CXXScopeSpec &SS,
1275 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001276 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001277 bool IsFriend,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001278 bool &IsExplicitSpecialization) {
1279 IsExplicitSpecialization = false;
1280
Douglas Gregord8d297c2009-07-21 23:53:31 +00001281 // Find the template-ids that occur within the nested-name-specifier. These
1282 // template-ids will match up with the template parameter lists.
1283 llvm::SmallVector<const TemplateSpecializationType *, 4>
1284 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001285 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1286 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001287 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1288 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001289 const Type *T = NNS->getAsType();
1290 if (!T) break;
1291
1292 // C++0x [temp.expl.spec]p17:
1293 // A member or a member template may be nested within many
1294 // enclosing class templates. In an explicit specialization for
1295 // such a member, the member declaration shall be preceded by a
1296 // template<> for each enclosing class template that is
1297 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001298 //
1299 // Following the existing practice of GNU and EDG, we allow a typedef of a
1300 // template specialization type.
1301 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1302 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001303
Mike Stump11289f42009-09-09 15:08:12 +00001304 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001305 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001306 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1307 if (!Template)
1308 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001309
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001310 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001311 ClassTemplateSpecializationDecl *SpecDecl
1312 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1313 // If the nested name specifier refers to an explicit specialization,
1314 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001315 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1316 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001317 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001318 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001319 }
Mike Stump11289f42009-09-09 15:08:12 +00001320
Douglas Gregord8d297c2009-07-21 23:53:31 +00001321 TemplateIdsInSpecifier.push_back(SpecType);
1322 }
1323 }
Mike Stump11289f42009-09-09 15:08:12 +00001324
Douglas Gregord8d297c2009-07-21 23:53:31 +00001325 // Reverse the list of template-ids in the scope specifier, so that we can
1326 // more easily match up the template-ids and the template parameter lists.
1327 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001328
Douglas Gregord8d297c2009-07-21 23:53:31 +00001329 SourceLocation FirstTemplateLoc = DeclStartLoc;
1330 if (NumParamLists)
1331 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001332
Douglas Gregord8d297c2009-07-21 23:53:31 +00001333 // Match the template-ids found in the specifier to the template parameter
1334 // lists.
1335 unsigned Idx = 0;
1336 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1337 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001338 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1339 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001340 if (Idx >= NumParamLists) {
1341 // We have a template-id without a corresponding template parameter
1342 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001343
1344 // ...which is fine if this is a friend declaration.
1345 if (IsFriend) {
1346 IsExplicitSpecialization = true;
1347 break;
1348 }
1349
Douglas Gregord8d297c2009-07-21 23:53:31 +00001350 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001351 // FIXME: the location information here isn't great.
1352 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001353 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001354 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001355 << SS.getRange();
1356 } else {
1357 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1358 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001359 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001360 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001361 }
1362 return 0;
1363 }
Mike Stump11289f42009-09-09 15:08:12 +00001364
Douglas Gregord8d297c2009-07-21 23:53:31 +00001365 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001366 if (DependentTemplateId) {
John McCall2408e322010-04-27 00:57:59 +00001367 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00001368
John McCall2408e322010-04-27 00:57:59 +00001369 // Are there cases in (e.g.) friends where this won't match?
1370 if (const InjectedClassNameType *Injected
1371 = TemplateId->getAs<InjectedClassNameType>()) {
1372 CXXRecordDecl *Record = Injected->getDecl();
1373 if (ClassTemplatePartialSpecializationDecl *Partial =
1374 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1375 ExpectedTemplateParams = Partial->getTemplateParameters();
1376 else
1377 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1378 ->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001379 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001380
John McCall2408e322010-04-27 00:57:59 +00001381 if (ExpectedTemplateParams)
1382 TemplateParameterListsAreEqual(ParamLists[Idx],
1383 ExpectedTemplateParams,
1384 true, TPL_TemplateMatch);
1385
Douglas Gregored5731f2009-11-25 17:50:39 +00001386 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001387 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001388 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001389 diag::err_template_param_list_matches_nontemplate)
1390 << TemplateId
1391 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001392 else
1393 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001394 }
Mike Stump11289f42009-09-09 15:08:12 +00001395
Douglas Gregord8d297c2009-07-21 23:53:31 +00001396 // If there were at least as many template-ids as there were template
1397 // parameter lists, then there are no template parameter lists remaining for
1398 // the declaration itself.
1399 if (Idx >= NumParamLists)
1400 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001401
Douglas Gregord8d297c2009-07-21 23:53:31 +00001402 // If there were too many template parameter lists, complain about that now.
1403 if (Idx != NumParamLists - 1) {
1404 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001405 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001406 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001407 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1408 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001409 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1410 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001411
1412 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1413 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1414 diag::note_explicit_template_spec_does_not_need_header)
1415 << ExplicitSpecializationsInSpecifier.back();
1416 ExplicitSpecializationsInSpecifier.pop_back();
1417 }
1418
Douglas Gregord8d297c2009-07-21 23:53:31 +00001419 ++Idx;
1420 }
1421 }
Mike Stump11289f42009-09-09 15:08:12 +00001422
Douglas Gregord8d297c2009-07-21 23:53:31 +00001423 // Return the last template parameter list, which corresponds to the
1424 // entity being declared.
1425 return ParamLists[NumParamLists - 1];
1426}
1427
Douglas Gregordc572a32009-03-30 22:58:21 +00001428QualType Sema::CheckTemplateIdType(TemplateName Name,
1429 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001430 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001431 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001432 if (!Template) {
1433 // The template name does not resolve to a template, so we just
1434 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001435 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001436 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001437
Douglas Gregorc40290e2009-03-09 23:48:35 +00001438 // Check that the template argument list is well-formed for this
1439 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001440 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001441 TemplateArgs.size());
1442 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001443 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001444 return QualType();
1445
Mike Stump11289f42009-09-09 15:08:12 +00001446 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001447 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001448 "Converted template argument list is too short!");
1449
1450 QualType CanonType;
1451
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001452 if (Name.isDependent() ||
1453 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001454 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001455 // This class template specialization is a dependent
1456 // type. Therefore, its canonical type is another class template
1457 // specialization type that contains all of the converted
1458 // arguments in canonical form. This ensures that, e.g., A<T> and
1459 // A<T, T> have identical types when A is declared as:
1460 //
1461 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001462 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001463 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001464 Converted.getFlatArguments(),
1465 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001466
Douglas Gregora8e02e72009-07-28 23:00:59 +00001467 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001468 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001469 // In the future, we need to teach getTemplateSpecializationType to only
1470 // build the canonical type and return that to us.
1471 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001472
1473 // This might work out to be a current instantiation, in which
1474 // case the canonical type needs to be the InjectedClassNameType.
1475 //
1476 // TODO: in theory this could be a simple hashtable lookup; most
1477 // changes to CurContext don't change the set of current
1478 // instantiations.
1479 if (isa<ClassTemplateDecl>(Template)) {
1480 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1481 // If we get out to a namespace, we're done.
1482 if (Ctx->isFileContext()) break;
1483
1484 // If this isn't a record, keep looking.
1485 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1486 if (!Record) continue;
1487
1488 // Look for one of the two cases with InjectedClassNameTypes
1489 // and check whether it's the same template.
1490 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1491 !Record->getDescribedClassTemplate())
1492 continue;
1493
1494 // Fetch the injected class name type and check whether its
1495 // injected type is equal to the type we just built.
1496 QualType ICNT = Context.getTypeDeclType(Record);
1497 QualType Injected = cast<InjectedClassNameType>(ICNT)
1498 ->getInjectedSpecializationType();
1499
1500 if (CanonType != Injected->getCanonicalTypeInternal())
1501 continue;
1502
1503 // If so, the canonical type of this TST is the injected
1504 // class name type of the record we just found.
1505 assert(ICNT.isCanonical());
1506 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00001507 break;
1508 }
1509 }
Mike Stump11289f42009-09-09 15:08:12 +00001510 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001511 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001512 // Find the class template specialization declaration that
1513 // corresponds to these arguments.
1514 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001515 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001516 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001517 Converted.flatSize(),
1518 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001519 void *InsertPos = 0;
1520 ClassTemplateSpecializationDecl *Decl
1521 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1522 if (!Decl) {
1523 // This is the first time we have referenced this class template
1524 // specialization. Create the canonical declaration and add it to
1525 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001526 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001527 ClassTemplate->getTemplatedDecl()->getTagKind(),
1528 ClassTemplate->getDeclContext(),
1529 ClassTemplate->getLocation(),
1530 ClassTemplate,
1531 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001532 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1533 Decl->setLexicalDeclContext(CurContext);
1534 }
1535
1536 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001537 assert(isa<RecordType>(CanonType) &&
1538 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001539 }
Mike Stump11289f42009-09-09 15:08:12 +00001540
Douglas Gregorc40290e2009-03-09 23:48:35 +00001541 // Build the fully-sugared type for this class template
1542 // specialization, which refers back to the class template
1543 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00001544 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001545}
1546
Douglas Gregor67a65642009-02-17 23:15:12 +00001547Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001548Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001549 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001550 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001551 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001552 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001553
Douglas Gregorc40290e2009-03-09 23:48:35 +00001554 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001555 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001556 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001557
John McCall6b51f282009-11-23 01:53:49 +00001558 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001559 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001560
1561 if (Result.isNull())
1562 return true;
1563
John McCallbcd03502009-12-07 02:54:59 +00001564 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001565 TemplateSpecializationTypeLoc TL
1566 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1567 TL.setTemplateNameLoc(TemplateLoc);
1568 TL.setLAngleLoc(LAngleLoc);
1569 TL.setRAngleLoc(RAngleLoc);
1570 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1571 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1572
1573 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001574}
John McCall06f6fe8d2009-09-04 01:14:41 +00001575
John McCalld8fe9af2009-09-08 17:47:29 +00001576Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1577 TagUseKind TUK,
1578 DeclSpec::TST TagSpec,
1579 SourceLocation TagLoc) {
1580 if (TypeResult.isInvalid())
1581 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001582
John McCall0ad16662009-10-29 08:12:44 +00001583 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001584 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001585 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001586
John McCalld8fe9af2009-09-08 17:47:29 +00001587 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001588 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001589
John McCalld8fe9af2009-09-08 17:47:29 +00001590 if (const RecordType *RT = Type->getAs<RecordType>()) {
1591 RecordDecl *D = RT->getDecl();
1592
1593 IdentifierInfo *Id = D->getIdentifier();
1594 assert(Id && "templated class must have an identifier");
1595
1596 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1597 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001598 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001599 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001600 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001601 }
1602 }
1603
Abramo Bagnara6150c882010-05-11 21:36:43 +00001604 ElaboratedTypeKeyword Keyword
1605 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1606 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001607
1608 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001609}
1610
John McCalle66edc12009-11-24 19:00:30 +00001611Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1612 LookupResult &R,
1613 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001614 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001615 // FIXME: Can we do any checking at this point? I guess we could check the
1616 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001617 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001618 // though.
John McCalle66edc12009-11-24 19:00:30 +00001619
1620 // These should be filtered out by our callers.
1621 assert(!R.empty() && "empty lookup results when building templateid");
1622 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1623
1624 NestedNameSpecifier *Qualifier = 0;
1625 SourceRange QualifierRange;
1626 if (SS.isSet()) {
1627 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1628 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001629 }
John McCall58cc69d2010-01-27 01:50:18 +00001630
1631 // We don't want lookup warnings at this point.
1632 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001633
John McCalle66edc12009-11-24 19:00:30 +00001634 bool Dependent
1635 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1636 &TemplateArgs);
1637 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001638 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001639 Qualifier, QualifierRange,
1640 R.getLookupName(), R.getNameLoc(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001641 RequiresADL, TemplateArgs,
1642 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001643
1644 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001645}
1646
John McCalle66edc12009-11-24 19:00:30 +00001647// We actually only call this from template instantiation.
1648Sema::OwningExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001649Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001650 DeclarationName Name,
1651 SourceLocation NameLoc,
1652 const TemplateArgumentListInfo &TemplateArgs) {
1653 DeclContext *DC;
1654 if (!(DC = computeDeclContext(SS, false)) ||
1655 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001656 RequireCompleteDeclContext(SS, DC))
John McCalle66edc12009-11-24 19:00:30 +00001657 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001658
Douglas Gregor786123d2010-05-21 23:18:07 +00001659 bool MemberOfUnknownSpecialization;
John McCalle66edc12009-11-24 19:00:30 +00001660 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00001661 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1662 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00001663
John McCalle66edc12009-11-24 19:00:30 +00001664 if (R.isAmbiguous())
1665 return ExprError();
1666
1667 if (R.empty()) {
1668 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1669 << Name << SS.getRange();
1670 return ExprError();
1671 }
1672
1673 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1674 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1675 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1676 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1677 return ExprError();
1678 }
1679
1680 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001681}
1682
Douglas Gregorb67535d2009-03-31 00:43:58 +00001683/// \brief Form a dependent template name.
1684///
1685/// This action forms a dependent template name given the template
1686/// name and its (presumably dependent) scope specifier. For
1687/// example, given "MetaFun::template apply", the scope specifier \p
1688/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1689/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001690Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001691Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001692 CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001693 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001694 TypeTy *ObjectType,
1695 bool EnteringContext) {
Douglas Gregor9abe2372010-01-19 16:01:07 +00001696 DeclContext *LookupCtx = 0;
1697 if (SS.isSet())
1698 LookupCtx = computeDeclContext(SS, EnteringContext);
1699 if (!LookupCtx && ObjectType)
1700 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1701 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001702 // C++0x [temp.names]p5:
1703 // If a name prefixed by the keyword template is not the name of
1704 // a template, the program is ill-formed. [Note: the keyword
1705 // template may not be applied to non-template members of class
1706 // templates. -end note ] [ Note: as is the case with the
1707 // typename prefix, the template prefix is allowed in cases
1708 // where it is not strictly necessary; i.e., when the
1709 // nested-name-specifier or the expression on the left of the ->
1710 // or . is not dependent on a template-parameter, or the use
1711 // does not appear in the scope of a template. -end note]
1712 //
1713 // Note: C++03 was more strict here, because it banned the use of
1714 // the "template" keyword prior to a template-name that was not a
1715 // dependent name. C++ DR468 relaxed this requirement (the
1716 // "template" keyword is now permitted). We follow the C++0x
1717 // rules, even in C++03 mode, retroactively applying the DR.
1718 TemplateTy Template;
Douglas Gregor786123d2010-05-21 23:18:07 +00001719 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001720 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00001721 EnteringContext, Template,
1722 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001723 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1724 isa<CXXRecordDecl>(LookupCtx) &&
1725 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00001726 // This is a dependent template.
1727 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001728 Diag(Name.getSourceRange().getBegin(),
1729 diag::err_template_kw_refers_to_non_template)
1730 << GetNameFromUnqualifiedId(Name)
Douglas Gregorb22ee882010-05-05 05:58:24 +00001731 << Name.getSourceRange()
1732 << TemplateKWLoc;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001733 return TemplateTy();
Douglas Gregord2e6a452010-01-14 17:47:39 +00001734 } else {
1735 // We found something; return it.
1736 return Template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001737 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001738 }
1739
Mike Stump11289f42009-09-09 15:08:12 +00001740 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001741 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001742
1743 switch (Name.getKind()) {
1744 case UnqualifiedId::IK_Identifier:
1745 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1746 Name.Identifier));
1747
Douglas Gregor71395fa2009-11-04 00:56:37 +00001748 case UnqualifiedId::IK_OperatorFunctionId:
1749 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1750 Name.OperatorFunctionId.Operator));
Alexis Hunted0530f2009-11-28 08:58:14 +00001751
1752 case UnqualifiedId::IK_LiteralOperatorId:
1753 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1754
Douglas Gregor3cf81312009-11-03 23:16:33 +00001755 default:
1756 break;
1757 }
1758
1759 Diag(Name.getSourceRange().getBegin(),
1760 diag::err_template_kw_refers_to_non_template)
1761 << GetNameFromUnqualifiedId(Name)
Douglas Gregorb22ee882010-05-05 05:58:24 +00001762 << Name.getSourceRange()
1763 << TemplateKWLoc;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001764 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001765}
1766
Mike Stump11289f42009-09-09 15:08:12 +00001767bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001768 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001769 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001770 const TemplateArgument &Arg = AL.getArgument();
1771
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001772 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001773 switch(Arg.getKind()) {
1774 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001775 // C++ [temp.arg.type]p1:
1776 // A template-argument for a template-parameter which is a
1777 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001778 break;
1779 case TemplateArgument::Template: {
1780 // We have a template type parameter but the template argument
1781 // is a template without any arguments.
1782 SourceRange SR = AL.getSourceRange();
1783 TemplateName Name = Arg.getAsTemplate();
1784 Diag(SR.getBegin(), diag::err_template_missing_args)
1785 << Name << SR;
1786 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1787 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001788
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001789 return true;
1790 }
1791 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001792 // We have a template type parameter but the template argument
1793 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001794 SourceRange SR = AL.getSourceRange();
1795 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001796 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001797
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001798 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001799 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001800 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001801
John McCallbcd03502009-12-07 02:54:59 +00001802 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001803 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001804
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001805 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001806 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001807 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001808 return false;
1809}
1810
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001811/// \brief Substitute template arguments into the default template argument for
1812/// the given template type parameter.
1813///
1814/// \param SemaRef the semantic analysis object for which we are performing
1815/// the substitution.
1816///
1817/// \param Template the template that we are synthesizing template arguments
1818/// for.
1819///
1820/// \param TemplateLoc the location of the template name that started the
1821/// template-id we are checking.
1822///
1823/// \param RAngleLoc the location of the right angle bracket ('>') that
1824/// terminates the template-id.
1825///
1826/// \param Param the template template parameter whose default we are
1827/// substituting into.
1828///
1829/// \param Converted the list of template arguments provided for template
1830/// parameters that precede \p Param in the template parameter list.
1831///
1832/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001833static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001834SubstDefaultTemplateArgument(Sema &SemaRef,
1835 TemplateDecl *Template,
1836 SourceLocation TemplateLoc,
1837 SourceLocation RAngleLoc,
1838 TemplateTypeParmDecl *Param,
1839 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001840 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001841
1842 // If the argument type is dependent, instantiate it now based
1843 // on the previously-computed template arguments.
1844 if (ArgType->getType()->isDependentType()) {
1845 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1846 /*TakeArgs=*/false);
1847
1848 MultiLevelTemplateArgumentList AllTemplateArgs
1849 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1850
1851 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1852 Template, Converted.getFlatArguments(),
1853 Converted.flatSize(),
1854 SourceRange(TemplateLoc, RAngleLoc));
1855
1856 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1857 Param->getDefaultArgumentLoc(),
1858 Param->getDeclName());
1859 }
1860
1861 return ArgType;
1862}
1863
1864/// \brief Substitute template arguments into the default template argument for
1865/// the given non-type template parameter.
1866///
1867/// \param SemaRef the semantic analysis object for which we are performing
1868/// the substitution.
1869///
1870/// \param Template the template that we are synthesizing template arguments
1871/// for.
1872///
1873/// \param TemplateLoc the location of the template name that started the
1874/// template-id we are checking.
1875///
1876/// \param RAngleLoc the location of the right angle bracket ('>') that
1877/// terminates the template-id.
1878///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001879/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001880/// substituting into.
1881///
1882/// \param Converted the list of template arguments provided for template
1883/// parameters that precede \p Param in the template parameter list.
1884///
1885/// \returns the substituted template argument, or NULL if an error occurred.
1886static Sema::OwningExprResult
1887SubstDefaultTemplateArgument(Sema &SemaRef,
1888 TemplateDecl *Template,
1889 SourceLocation TemplateLoc,
1890 SourceLocation RAngleLoc,
1891 NonTypeTemplateParmDecl *Param,
1892 TemplateArgumentListBuilder &Converted) {
1893 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1894 /*TakeArgs=*/false);
1895
1896 MultiLevelTemplateArgumentList AllTemplateArgs
1897 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1898
1899 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1900 Template, Converted.getFlatArguments(),
1901 Converted.flatSize(),
1902 SourceRange(TemplateLoc, RAngleLoc));
1903
1904 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1905}
1906
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001907/// \brief Substitute template arguments into the default template argument for
1908/// the given template template parameter.
1909///
1910/// \param SemaRef the semantic analysis object for which we are performing
1911/// the substitution.
1912///
1913/// \param Template the template that we are synthesizing template arguments
1914/// for.
1915///
1916/// \param TemplateLoc the location of the template name that started the
1917/// template-id we are checking.
1918///
1919/// \param RAngleLoc the location of the right angle bracket ('>') that
1920/// terminates the template-id.
1921///
1922/// \param Param the template template parameter whose default we are
1923/// substituting into.
1924///
1925/// \param Converted the list of template arguments provided for template
1926/// parameters that precede \p Param in the template parameter list.
1927///
1928/// \returns the substituted template argument, or NULL if an error occurred.
1929static TemplateName
1930SubstDefaultTemplateArgument(Sema &SemaRef,
1931 TemplateDecl *Template,
1932 SourceLocation TemplateLoc,
1933 SourceLocation RAngleLoc,
1934 TemplateTemplateParmDecl *Param,
1935 TemplateArgumentListBuilder &Converted) {
1936 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1937 /*TakeArgs=*/false);
1938
1939 MultiLevelTemplateArgumentList AllTemplateArgs
1940 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1941
1942 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1943 Template, Converted.getFlatArguments(),
1944 Converted.flatSize(),
1945 SourceRange(TemplateLoc, RAngleLoc));
1946
1947 return SemaRef.SubstTemplateName(
1948 Param->getDefaultArgument().getArgument().getAsTemplate(),
1949 Param->getDefaultArgument().getTemplateNameLoc(),
1950 AllTemplateArgs);
1951}
1952
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001953/// \brief If the given template parameter has a default template
1954/// argument, substitute into that default template argument and
1955/// return the corresponding template argument.
1956TemplateArgumentLoc
1957Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1958 SourceLocation TemplateLoc,
1959 SourceLocation RAngleLoc,
1960 Decl *Param,
1961 TemplateArgumentListBuilder &Converted) {
1962 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1963 if (!TypeParm->hasDefaultArgument())
1964 return TemplateArgumentLoc();
1965
John McCallbcd03502009-12-07 02:54:59 +00001966 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001967 TemplateLoc,
1968 RAngleLoc,
1969 TypeParm,
1970 Converted);
1971 if (DI)
1972 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1973
1974 return TemplateArgumentLoc();
1975 }
1976
1977 if (NonTypeTemplateParmDecl *NonTypeParm
1978 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1979 if (!NonTypeParm->hasDefaultArgument())
1980 return TemplateArgumentLoc();
1981
1982 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1983 TemplateLoc,
1984 RAngleLoc,
1985 NonTypeParm,
1986 Converted);
1987 if (Arg.isInvalid())
1988 return TemplateArgumentLoc();
1989
1990 Expr *ArgE = Arg.takeAs<Expr>();
1991 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1992 }
1993
1994 TemplateTemplateParmDecl *TempTempParm
1995 = cast<TemplateTemplateParmDecl>(Param);
1996 if (!TempTempParm->hasDefaultArgument())
1997 return TemplateArgumentLoc();
1998
1999 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2000 TemplateLoc,
2001 RAngleLoc,
2002 TempTempParm,
2003 Converted);
2004 if (TName.isNull())
2005 return TemplateArgumentLoc();
2006
2007 return TemplateArgumentLoc(TemplateArgument(TName),
2008 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2009 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2010}
2011
Douglas Gregorda0fb532009-11-11 19:31:23 +00002012/// \brief Check that the given template argument corresponds to the given
2013/// template parameter.
2014bool Sema::CheckTemplateArgument(NamedDecl *Param,
2015 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002016 TemplateDecl *Template,
2017 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002018 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002019 TemplateArgumentListBuilder &Converted,
2020 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00002021 // Check template type parameters.
2022 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002023 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002024
Douglas Gregoreebed722009-11-11 19:41:09 +00002025 // Check non-type template parameters.
2026 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00002027 // Do substitution on the type of the non-type template parameter
2028 // with the template arguments we've seen thus far.
2029 QualType NTTPType = NTTP->getType();
2030 if (NTTPType->isDependentType()) {
2031 // Do substitution on the type of the non-type template parameter.
2032 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2033 NTTP, Converted.getFlatArguments(),
2034 Converted.flatSize(),
2035 SourceRange(TemplateLoc, RAngleLoc));
2036
2037 TemplateArgumentList TemplateArgs(Context, Converted,
2038 /*TakeArgs=*/false);
2039 NTTPType = SubstType(NTTPType,
2040 MultiLevelTemplateArgumentList(TemplateArgs),
2041 NTTP->getLocation(),
2042 NTTP->getDeclName());
2043 // If that worked, check the non-type template parameter type
2044 // for validity.
2045 if (!NTTPType.isNull())
2046 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2047 NTTP->getLocation());
2048 if (NTTPType.isNull())
2049 return true;
2050 }
2051
2052 switch (Arg.getArgument().getKind()) {
2053 case TemplateArgument::Null:
2054 assert(false && "Should never see a NULL template argument here");
2055 return true;
2056
2057 case TemplateArgument::Expression: {
2058 Expr *E = Arg.getArgument().getAsExpr();
2059 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002060 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002061 return true;
2062
2063 Converted.Append(Result);
2064 break;
2065 }
2066
2067 case TemplateArgument::Declaration:
2068 case TemplateArgument::Integral:
2069 // We've already checked this template argument, so just copy
2070 // it to the list of converted arguments.
2071 Converted.Append(Arg.getArgument());
2072 break;
2073
2074 case TemplateArgument::Template:
2075 // We were given a template template argument. It may not be ill-formed;
2076 // see below.
2077 if (DependentTemplateName *DTN
2078 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2079 // We have a template argument such as \c T::template X, which we
2080 // parsed as a template template argument. However, since we now
2081 // know that we need a non-type template argument, convert this
2082 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00002083 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2084 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002085 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00002086 DTN->getIdentifier(),
2087 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00002088
2089 TemplateArgument Result;
2090 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2091 return true;
2092
2093 Converted.Append(Result);
2094 break;
2095 }
2096
2097 // We have a template argument that actually does refer to a class
2098 // template, template alias, or template template parameter, and
2099 // therefore cannot be a non-type template argument.
2100 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2101 << Arg.getSourceRange();
2102
2103 Diag(Param->getLocation(), diag::note_template_param_here);
2104 return true;
2105
2106 case TemplateArgument::Type: {
2107 // We have a non-type template parameter but the template
2108 // argument is a type.
2109
2110 // C++ [temp.arg]p2:
2111 // In a template-argument, an ambiguity between a type-id and
2112 // an expression is resolved to a type-id, regardless of the
2113 // form of the corresponding template-parameter.
2114 //
2115 // We warn specifically about this case, since it can be rather
2116 // confusing for users.
2117 QualType T = Arg.getArgument().getAsType();
2118 SourceRange SR = Arg.getSourceRange();
2119 if (T->isFunctionType())
2120 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2121 else
2122 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2123 Diag(Param->getLocation(), diag::note_template_param_here);
2124 return true;
2125 }
2126
2127 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002128 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002129 break;
2130 }
2131
2132 return false;
2133 }
2134
2135
2136 // Check template template parameters.
2137 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2138
2139 // Substitute into the template parameter list of the template
2140 // template parameter, since previously-supplied template arguments
2141 // may appear within the template template parameter.
2142 {
2143 // Set up a template instantiation context.
2144 LocalInstantiationScope Scope(*this);
2145 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2146 TempParm, Converted.getFlatArguments(),
2147 Converted.flatSize(),
2148 SourceRange(TemplateLoc, RAngleLoc));
2149
2150 TemplateArgumentList TemplateArgs(Context, Converted,
2151 /*TakeArgs=*/false);
2152 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2153 SubstDecl(TempParm, CurContext,
2154 MultiLevelTemplateArgumentList(TemplateArgs)));
2155 if (!TempParm)
2156 return true;
2157
2158 // FIXME: TempParam is leaked.
2159 }
2160
2161 switch (Arg.getArgument().getKind()) {
2162 case TemplateArgument::Null:
2163 assert(false && "Should never see a NULL template argument here");
2164 return true;
2165
2166 case TemplateArgument::Template:
2167 if (CheckTemplateArgument(TempParm, Arg))
2168 return true;
2169
2170 Converted.Append(Arg.getArgument());
2171 break;
2172
2173 case TemplateArgument::Expression:
2174 case TemplateArgument::Type:
2175 // We have a template template parameter but the template
2176 // argument does not refer to a template.
2177 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2178 return true;
2179
2180 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002181 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002182 "Declaration argument with template template parameter");
2183 break;
2184 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002185 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002186 "Integral argument with template template parameter");
2187 break;
2188
2189 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002190 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002191 break;
2192 }
2193
2194 return false;
2195}
2196
Douglas Gregord32e0282009-02-09 23:23:08 +00002197/// \brief Check that the given template argument list is well-formed
2198/// for specializing the given template.
2199bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2200 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002201 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002202 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002203 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002204 TemplateParameterList *Params = Template->getTemplateParameters();
2205 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002206 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002207 bool Invalid = false;
2208
John McCall6b51f282009-11-23 01:53:49 +00002209 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2210
Mike Stump11289f42009-09-09 15:08:12 +00002211 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002212 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002213
Anders Carlsson15201f12009-06-13 02:08:00 +00002214 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002215 (NumArgs < Params->getMinRequiredArguments() &&
2216 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002217 // FIXME: point at either the first arg beyond what we can handle,
2218 // or the '>', depending on whether we have too many or too few
2219 // arguments.
2220 SourceRange Range;
2221 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002222 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002223 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2224 << (NumArgs > NumParams)
2225 << (isa<ClassTemplateDecl>(Template)? 0 :
2226 isa<FunctionTemplateDecl>(Template)? 1 :
2227 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2228 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002229 Diag(Template->getLocation(), diag::note_template_decl_here)
2230 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002231 Invalid = true;
2232 }
Mike Stump11289f42009-09-09 15:08:12 +00002233
2234 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002235 // [...] The type and form of each template-argument specified in
2236 // a template-id shall match the type and form specified for the
2237 // corresponding parameter declared by the template in its
2238 // template-parameter-list.
2239 unsigned ArgIdx = 0;
2240 for (TemplateParameterList::iterator Param = Params->begin(),
2241 ParamEnd = Params->end();
2242 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002243 if (ArgIdx > NumArgs && PartialTemplateArgs)
2244 break;
Mike Stump11289f42009-09-09 15:08:12 +00002245
Douglas Gregoreebed722009-11-11 19:41:09 +00002246 // If we have a template parameter pack, check every remaining template
2247 // argument against that template parameter pack.
2248 if ((*Param)->isTemplateParameterPack()) {
2249 Converted.BeginPack();
2250 for (; ArgIdx < NumArgs; ++ArgIdx) {
2251 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2252 TemplateLoc, RAngleLoc, Converted)) {
2253 Invalid = true;
2254 break;
2255 }
2256 }
2257 Converted.EndPack();
2258 continue;
2259 }
2260
Douglas Gregor84d49a22009-11-11 21:54:23 +00002261 if (ArgIdx < NumArgs) {
2262 // Check the template argument we were given.
2263 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2264 TemplateLoc, RAngleLoc, Converted))
2265 return true;
2266
2267 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002268 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002269
Douglas Gregor84d49a22009-11-11 21:54:23 +00002270 // We have a default template argument that we will use.
2271 TemplateArgumentLoc Arg;
2272
2273 // Retrieve the default template argument from the template
2274 // parameter. For each kind of template parameter, we substitute the
2275 // template arguments provided thus far and any "outer" template arguments
2276 // (when the template parameter was part of a nested template) into
2277 // the default argument.
2278 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2279 if (!TTP->hasDefaultArgument()) {
2280 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2281 break;
2282 }
2283
John McCallbcd03502009-12-07 02:54:59 +00002284 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002285 Template,
2286 TemplateLoc,
2287 RAngleLoc,
2288 TTP,
2289 Converted);
2290 if (!ArgType)
2291 return true;
2292
2293 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2294 ArgType);
2295 } else if (NonTypeTemplateParmDecl *NTTP
2296 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2297 if (!NTTP->hasDefaultArgument()) {
2298 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2299 break;
2300 }
2301
2302 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2303 TemplateLoc,
2304 RAngleLoc,
2305 NTTP,
2306 Converted);
2307 if (E.isInvalid())
2308 return true;
2309
2310 Expr *Ex = E.takeAs<Expr>();
2311 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2312 } else {
2313 TemplateTemplateParmDecl *TempParm
2314 = cast<TemplateTemplateParmDecl>(*Param);
2315
2316 if (!TempParm->hasDefaultArgument()) {
2317 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2318 break;
2319 }
2320
2321 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2322 TemplateLoc,
2323 RAngleLoc,
2324 TempParm,
2325 Converted);
2326 if (Name.isNull())
2327 return true;
2328
2329 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2330 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2331 TempParm->getDefaultArgument().getTemplateNameLoc());
2332 }
2333
2334 // Introduce an instantiation record that describes where we are using
2335 // the default template argument.
2336 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2337 Converted.getFlatArguments(),
2338 Converted.flatSize(),
2339 SourceRange(TemplateLoc, RAngleLoc));
2340
2341 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002342 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002343 RAngleLoc, Converted))
2344 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002345 }
2346
2347 return Invalid;
2348}
2349
2350/// \brief Check a template argument against its corresponding
2351/// template type parameter.
2352///
2353/// This routine implements the semantics of C++ [temp.arg.type]. It
2354/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002355bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002356 TypeSourceInfo *ArgInfo) {
2357 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002358 QualType Arg = ArgInfo->getType();
2359
Douglas Gregord32e0282009-02-09 23:23:08 +00002360 // C++ [temp.arg.type]p2:
2361 // A local type, a type with no linkage, an unnamed type or a type
2362 // compounded from any of these types shall not be used as a
2363 // template-argument for a template type-parameter.
2364 //
Douglas Gregor959d5a02010-05-22 16:17:30 +00002365 // FIXME: Perform the unnamed type check.
2366 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002367 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002368 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002369 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002370 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002371 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002372 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002373 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall0ad16662009-10-29 08:12:44 +00002374 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2375 << QualType(Tag, 0) << SR;
2376 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002377 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002378 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002379 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2380 return true;
Douglas Gregor959d5a02010-05-22 16:17:30 +00002381 } else if (Arg->isVariablyModifiedType()) {
2382 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2383 << Arg;
2384 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002385 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002386 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002387 }
2388
2389 return false;
2390}
2391
Douglas Gregorccb07762009-02-11 19:52:55 +00002392/// \brief Checks whether the given template argument is the address
2393/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002394static bool
2395CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2396 NonTypeTemplateParmDecl *Param,
2397 QualType ParamType,
2398 Expr *ArgIn,
2399 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002400 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002401 Expr *Arg = ArgIn;
2402 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002403
2404 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002405 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002406 Arg = Cast->getSubExpr();
2407
2408 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002409 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002410 // A template-argument for a non-type, non-template
2411 // template-parameter shall be one of: [...]
2412 //
2413 // -- the address of an object or function with external
2414 // linkage, including function templates and function
2415 // template-ids but excluding non-static class members,
2416 // expressed as & id-expression where the & is optional if
2417 // the name refers to a function or array, or if the
2418 // corresponding template-parameter is a reference; or
2419 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002420
Douglas Gregorccb07762009-02-11 19:52:55 +00002421 // Ignore (and complain about) any excess parentheses.
2422 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2423 if (!Invalid) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002424 S.Diag(Arg->getSourceRange().getBegin(),
2425 diag::err_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002426 << Arg->getSourceRange();
2427 Invalid = true;
2428 }
2429
2430 Arg = Parens->getSubExpr();
2431 }
2432
Douglas Gregorb242683d2010-04-01 18:32:35 +00002433 bool AddressTaken = false;
2434 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002435 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002436 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002437 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002438 AddressTaken = true;
2439 AddrOpLoc = UnOp->getOperatorLoc();
2440 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002441 } else
2442 DRE = dyn_cast<DeclRefExpr>(Arg);
2443
Douglas Gregorb242683d2010-04-01 18:32:35 +00002444 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002445 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2446 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002447 S.Diag(Param->getLocation(), diag::note_template_param_here);
2448 return true;
2449 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002450
2451 // Stop checking the precise nature of the argument if it is value dependent,
2452 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002453 if (Arg->isValueDependent()) {
2454 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002455 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002456 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002457
Douglas Gregorb242683d2010-04-01 18:32:35 +00002458 if (!isa<ValueDecl>(DRE->getDecl())) {
2459 S.Diag(Arg->getSourceRange().getBegin(),
2460 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002461 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002462 S.Diag(Param->getLocation(), diag::note_template_param_here);
2463 return true;
2464 }
2465
2466 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002467
2468 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002469 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2470 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002471 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002472 S.Diag(Param->getLocation(), diag::note_template_param_here);
2473 return true;
2474 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002475
2476 // Cannot refer to non-static member functions
2477 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002478 if (!Method->isStatic()) {
2479 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002480 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002481 S.Diag(Param->getLocation(), diag::note_template_param_here);
2482 return true;
2483 }
Mike Stump11289f42009-09-09 15:08:12 +00002484
Douglas Gregorccb07762009-02-11 19:52:55 +00002485 // Functions must have external linkage.
2486 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002487 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002488 S.Diag(Arg->getSourceRange().getBegin(),
2489 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002490 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002491 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002492 << true;
2493 return true;
2494 }
2495
2496 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002497 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002498
Douglas Gregorb242683d2010-04-01 18:32:35 +00002499 // If the template parameter has pointer type, the function decays.
2500 if (ParamType->isPointerType() && !AddressTaken)
2501 ArgType = S.Context.getPointerType(Func->getType());
2502 else if (AddressTaken && ParamType->isReferenceType()) {
2503 // If we originally had an address-of operator, but the
2504 // parameter has reference type, complain and (if things look
2505 // like they will work) drop the address-of operator.
2506 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2507 ParamType.getNonReferenceType())) {
2508 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2509 << ParamType;
2510 S.Diag(Param->getLocation(), diag::note_template_param_here);
2511 return true;
2512 }
2513
2514 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2515 << ParamType
2516 << FixItHint::CreateRemoval(AddrOpLoc);
2517 S.Diag(Param->getLocation(), diag::note_template_param_here);
2518
2519 ArgType = Func->getType();
2520 }
2521 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002522 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002523 S.Diag(Arg->getSourceRange().getBegin(),
2524 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002525 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002526 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002527 << true;
2528 return true;
2529 }
2530
Douglas Gregorb242683d2010-04-01 18:32:35 +00002531 // A value of reference type is not an object.
2532 if (Var->getType()->isReferenceType()) {
2533 S.Diag(Arg->getSourceRange().getBegin(),
2534 diag::err_template_arg_reference_var)
2535 << Var->getType() << Arg->getSourceRange();
2536 S.Diag(Param->getLocation(), diag::note_template_param_here);
2537 return true;
2538 }
2539
Douglas Gregorccb07762009-02-11 19:52:55 +00002540 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002541 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002542
2543 // If the template parameter has pointer type, we must have taken
2544 // the address of this object.
2545 if (ParamType->isReferenceType()) {
2546 if (AddressTaken) {
2547 // If we originally had an address-of operator, but the
2548 // parameter has reference type, complain and (if things look
2549 // like they will work) drop the address-of operator.
2550 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2551 ParamType.getNonReferenceType())) {
2552 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2553 << ParamType;
2554 S.Diag(Param->getLocation(), diag::note_template_param_here);
2555 return true;
2556 }
2557
2558 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2559 << ParamType
2560 << FixItHint::CreateRemoval(AddrOpLoc);
2561 S.Diag(Param->getLocation(), diag::note_template_param_here);
2562
2563 ArgType = Var->getType();
2564 }
2565 } else if (!AddressTaken && ParamType->isPointerType()) {
2566 if (Var->getType()->isArrayType()) {
2567 // Array-to-pointer decay.
2568 ArgType = S.Context.getArrayDecayedType(Var->getType());
2569 } else {
2570 // If the template parameter has pointer type but the address of
2571 // this object was not taken, complain and (possibly) recover by
2572 // taking the address of the entity.
2573 ArgType = S.Context.getPointerType(Var->getType());
2574 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2575 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2576 << ParamType;
2577 S.Diag(Param->getLocation(), diag::note_template_param_here);
2578 return true;
2579 }
2580
2581 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2582 << ParamType
2583 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2584
2585 S.Diag(Param->getLocation(), diag::note_template_param_here);
2586 }
2587 }
2588 } else {
2589 // We found something else, but we don't know specifically what it is.
2590 S.Diag(Arg->getSourceRange().getBegin(),
2591 diag::err_template_arg_not_object_or_func)
2592 << Arg->getSourceRange();
2593 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2594 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002595 }
Mike Stump11289f42009-09-09 15:08:12 +00002596
Douglas Gregorb242683d2010-04-01 18:32:35 +00002597 if (ParamType->isPointerType() &&
2598 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2599 S.IsQualificationConversion(ArgType, ParamType)) {
2600 // For pointer-to-object types, qualification conversions are
2601 // permitted.
2602 } else {
2603 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2604 if (!ParamRef->getPointeeType()->isFunctionType()) {
2605 // C++ [temp.arg.nontype]p5b3:
2606 // For a non-type template-parameter of type reference to
2607 // object, no conversions apply. The type referred to by the
2608 // reference may be more cv-qualified than the (otherwise
2609 // identical) type of the template- argument. The
2610 // template-parameter is bound directly to the
2611 // template-argument, which shall be an lvalue.
2612
2613 // FIXME: Other qualifiers?
2614 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2615 unsigned ArgQuals = ArgType.getCVRQualifiers();
2616
2617 if ((ParamQuals | ArgQuals) != ParamQuals) {
2618 S.Diag(Arg->getSourceRange().getBegin(),
2619 diag::err_template_arg_ref_bind_ignores_quals)
2620 << ParamType << Arg->getType()
2621 << Arg->getSourceRange();
2622 S.Diag(Param->getLocation(), diag::note_template_param_here);
2623 return true;
2624 }
2625 }
2626 }
2627
2628 // At this point, the template argument refers to an object or
2629 // function with external linkage. We now need to check whether the
2630 // argument and parameter types are compatible.
2631 if (!S.Context.hasSameUnqualifiedType(ArgType,
2632 ParamType.getNonReferenceType())) {
2633 // We can't perform this conversion or binding.
2634 if (ParamType->isReferenceType())
2635 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2636 << ParamType << Arg->getType() << Arg->getSourceRange();
2637 else
2638 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2639 << Arg->getType() << ParamType << Arg->getSourceRange();
2640 S.Diag(Param->getLocation(), diag::note_template_param_here);
2641 return true;
2642 }
2643 }
2644
2645 // Create the template argument.
2646 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002647 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002648 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002649}
2650
2651/// \brief Checks whether the given template argument is a pointer to
2652/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002653bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2654 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002655 bool Invalid = false;
2656
2657 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002658 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002659 Arg = Cast->getSubExpr();
2660
2661 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002662 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002663 // A template-argument for a non-type, non-template
2664 // template-parameter shall be one of: [...]
2665 //
2666 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002667 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002668
2669 // Ignore (and complain about) any excess parentheses.
2670 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2671 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002672 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002673 diag::err_template_arg_extra_parens)
2674 << Arg->getSourceRange();
2675 Invalid = true;
2676 }
2677
2678 Arg = Parens->getSubExpr();
2679 }
2680
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002681 // A pointer-to-member constant written &Class::member.
2682 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002683 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2684 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2685 if (DRE && !DRE->getQualifier())
2686 DRE = 0;
2687 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002688 }
2689 // A constant of pointer-to-member type.
2690 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2691 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2692 if (VD->getType()->isMemberPointerType()) {
2693 if (isa<NonTypeTemplateParmDecl>(VD) ||
2694 (isa<VarDecl>(VD) &&
2695 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2696 if (Arg->isTypeDependent() || Arg->isValueDependent())
2697 Converted = TemplateArgument(Arg->Retain());
2698 else
2699 Converted = TemplateArgument(VD->getCanonicalDecl());
2700 return Invalid;
2701 }
2702 }
2703 }
2704
2705 DRE = 0;
2706 }
2707
Douglas Gregorccb07762009-02-11 19:52:55 +00002708 if (!DRE)
2709 return Diag(Arg->getSourceRange().getBegin(),
2710 diag::err_template_arg_not_pointer_to_member_form)
2711 << Arg->getSourceRange();
2712
2713 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2714 assert((isa<FieldDecl>(DRE->getDecl()) ||
2715 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2716 "Only non-static member pointers can make it here");
2717
2718 // Okay: this is the address of a non-static member, and therefore
2719 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002720 if (Arg->isTypeDependent() || Arg->isValueDependent())
2721 Converted = TemplateArgument(Arg->Retain());
2722 else
2723 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002724 return Invalid;
2725 }
2726
2727 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002728 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002729 diag::err_template_arg_not_pointer_to_member_form)
2730 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002731 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002732 diag::note_template_arg_refers_here);
2733 return true;
2734}
2735
Douglas Gregord32e0282009-02-09 23:23:08 +00002736/// \brief Check a template argument against its corresponding
2737/// non-type template parameter.
2738///
Douglas Gregor463421d2009-03-03 04:44:36 +00002739/// This routine implements the semantics of C++ [temp.arg.nontype].
2740/// It returns true if an error occurred, and false otherwise. \p
2741/// InstantiatedParamType is the type of the non-type template
2742/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002743///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002744/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002745bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002746 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002747 TemplateArgument &Converted,
2748 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002749 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2750
Douglas Gregor86560402009-02-10 23:36:10 +00002751 // If either the parameter has a dependent type or the argument is
2752 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002753 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2754 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002755 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002756 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002757 }
Douglas Gregor86560402009-02-10 23:36:10 +00002758
2759 // C++ [temp.arg.nontype]p5:
2760 // The following conversions are performed on each expression used
2761 // as a non-type template-argument. If a non-type
2762 // template-argument cannot be converted to the type of the
2763 // corresponding template-parameter then the program is
2764 // ill-formed.
2765 //
2766 // -- for a non-type template-parameter of integral or
2767 // enumeration type, integral promotions (4.5) and integral
2768 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002769 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002770 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002771 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002772 // C++ [temp.arg.nontype]p1:
2773 // A template-argument for a non-type, non-template
2774 // template-parameter shall be one of:
2775 //
2776 // -- an integral constant-expression of integral or enumeration
2777 // type; or
2778 // -- the name of a non-type template-parameter; or
2779 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002780 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002781 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002782 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002783 diag::err_template_arg_not_integral_or_enumeral)
2784 << ArgType << Arg->getSourceRange();
2785 Diag(Param->getLocation(), diag::note_template_param_here);
2786 return true;
2787 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002788 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002789 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2790 << ArgType << Arg->getSourceRange();
2791 return true;
2792 }
2793
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002794 // From here on out, all we care about are the unqualified forms
2795 // of the parameter and argument types.
2796 ParamType = ParamType.getUnqualifiedType();
2797 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00002798
2799 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002800 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002801 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002802 } else if (CTAK == CTAK_Deduced) {
2803 // C++ [temp.deduct.type]p17:
2804 // If, in the declaration of a function template with a non-type
2805 // template-parameter, the non-type template- parameter is used
2806 // in an expression in the function parameter-list and, if the
2807 // corresponding template-argument is deduced, the
2808 // template-argument type shall match the type of the
2809 // template-parameter exactly, except that a template-argument
2810 // deduced from an array bound may be of any integral type.
2811 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2812 << ArgType << ParamType;
2813 Diag(Param->getLocation(), diag::note_template_param_here);
2814 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00002815 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2816 !ParamType->isEnumeralType()) {
2817 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002818 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002819 } else {
2820 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002821 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002822 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002823 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002824 Diag(Param->getLocation(), diag::note_template_param_here);
2825 return true;
2826 }
2827
Douglas Gregor52aba872009-03-14 00:20:21 +00002828 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002829 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002830 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002831
2832 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002833 llvm::APSInt OldValue = Value;
2834
2835 // Coerce the template argument's value to the value it will have
2836 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002837 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002838 if (Value.getBitWidth() != AllowedBits)
2839 Value.extOrTrunc(AllowedBits);
2840 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002841
2842 // Complain if an unsigned parameter received a negative value.
2843 if (IntegerType->isUnsignedIntegerType()
2844 && (OldValue.isSigned() && OldValue.isNegative())) {
2845 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2846 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2847 << Arg->getSourceRange();
2848 Diag(Param->getLocation(), diag::note_template_param_here);
2849 }
2850
2851 // Complain if we overflowed the template parameter's type.
2852 unsigned RequiredBits;
2853 if (IntegerType->isUnsignedIntegerType())
2854 RequiredBits = OldValue.getActiveBits();
2855 else if (OldValue.isUnsigned())
2856 RequiredBits = OldValue.getActiveBits() + 1;
2857 else
2858 RequiredBits = OldValue.getMinSignedBits();
2859 if (RequiredBits > AllowedBits) {
2860 Diag(Arg->getSourceRange().getBegin(),
2861 diag::warn_template_arg_too_large)
2862 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2863 << Arg->getSourceRange();
2864 Diag(Param->getLocation(), diag::note_template_param_here);
2865 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002866 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002867
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002868 // Add the value of this argument to the list of converted
2869 // arguments. We use the bitwidth and signedness of the template
2870 // parameter.
2871 if (Arg->isValueDependent()) {
2872 // The argument is value-dependent. Create a new
2873 // TemplateArgument with the converted expression.
2874 Converted = TemplateArgument(Arg);
2875 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002876 }
2877
John McCall0ad16662009-10-29 08:12:44 +00002878 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002879 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002880 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002881 return false;
2882 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002883
John McCall16df1e52010-03-30 21:47:33 +00002884 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2885
Douglas Gregorb242683d2010-04-01 18:32:35 +00002886 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2887 // from a template argument of type std::nullptr_t to a non-type
2888 // template parameter of type pointer to object, pointer to
2889 // function, or pointer-to-member, respectively.
2890 if (ArgType->isNullPtrType() &&
2891 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2892 Converted = TemplateArgument((NamedDecl *)0);
2893 return false;
2894 }
2895
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002896 // Handle pointer-to-function, reference-to-function, and
2897 // pointer-to-member-function all in (roughly) the same way.
2898 if (// -- For a non-type template-parameter of type pointer to
2899 // function, only the function-to-pointer conversion (4.3) is
2900 // applied. If the template-argument represents a set of
2901 // overloaded functions (or a pointer to such), the matching
2902 // function is selected from the set (13.4).
2903 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002904 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002905 // -- For a non-type template-parameter of type reference to
2906 // function, no conversions apply. If the template-argument
2907 // represents a set of overloaded functions, the matching
2908 // function is selected from the set (13.4).
2909 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002910 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002911 // -- For a non-type template-parameter of type pointer to
2912 // member function, no conversions apply. If the
2913 // template-argument represents a set of overloaded member
2914 // functions, the matching member function is selected from
2915 // the set (13.4).
2916 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002917 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002918 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002919
Douglas Gregor064fdb22010-04-14 23:11:21 +00002920 if (Arg->getType() == Context.OverloadTy) {
2921 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2922 true,
2923 FoundResult)) {
2924 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2925 return true;
2926
2927 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2928 ArgType = Arg->getType();
2929 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00002930 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002931 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002932
Douglas Gregorb242683d2010-04-01 18:32:35 +00002933 if (!ParamType->isMemberPointerType())
2934 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2935 ParamType,
2936 Arg, Converted);
2937
2938 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
2939 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2940 Arg->isLvalue(Context) == Expr::LV_Valid);
2941 } else if (!Context.hasSameUnqualifiedType(ArgType,
2942 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002943 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002944 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002945 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002946 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002947 Diag(Param->getLocation(), diag::note_template_param_here);
2948 return true;
2949 }
Mike Stump11289f42009-09-09 15:08:12 +00002950
Douglas Gregorb242683d2010-04-01 18:32:35 +00002951 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002952 }
2953
Chris Lattner696197c2009-02-20 21:37:53 +00002954 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002955 // -- for a non-type template-parameter of type pointer to
2956 // object, qualification conversions (4.4) and the
2957 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002958 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002959 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002960 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002961
Douglas Gregorb242683d2010-04-01 18:32:35 +00002962 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2963 ParamType,
2964 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00002965 }
Mike Stump11289f42009-09-09 15:08:12 +00002966
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002967 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002968 // -- For a non-type template-parameter of type reference to
2969 // object, no conversions apply. The type referred to by the
2970 // reference may be more cv-qualified than the (otherwise
2971 // identical) type of the template-argument. The
2972 // template-parameter is bound directly to the
2973 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002974 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002975 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002976
Douglas Gregor064fdb22010-04-14 23:11:21 +00002977 if (Arg->getType() == Context.OverloadTy) {
2978 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2979 ParamRefType->getPointeeType(),
2980 true,
2981 FoundResult)) {
2982 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2983 return true;
2984
2985 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2986 ArgType = Arg->getType();
2987 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00002988 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002989 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002990
Douglas Gregorb242683d2010-04-01 18:32:35 +00002991 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2992 ParamType,
2993 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002994 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002995
2996 // -- For a non-type template-parameter of type pointer to data
2997 // member, qualification conversions (4.4) are applied.
2998 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2999
Douglas Gregor1515f762009-02-11 18:22:40 +00003000 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00003001 // Types match exactly: nothing more to do here.
3002 } else if (IsQualificationConversion(ArgType, ParamType)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003003 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
3004 Arg->isLvalue(Context) == Expr::LV_Valid);
Douglas Gregor0e558532009-02-11 16:16:59 +00003005 } else {
3006 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003007 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00003008 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003009 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00003010 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003011 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00003012 }
3013
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00003014 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00003015}
3016
3017/// \brief Check a template argument against its corresponding
3018/// template template parameter.
3019///
3020/// This routine implements the semantics of C++ [temp.arg.template].
3021/// It returns true if an error occurred, and false otherwise.
3022bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003023 const TemplateArgumentLoc &Arg) {
3024 TemplateName Name = Arg.getArgument().getAsTemplate();
3025 TemplateDecl *Template = Name.getAsTemplateDecl();
3026 if (!Template) {
3027 // Any dependent template name is fine.
3028 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3029 return false;
3030 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003031
3032 // C++ [temp.arg.template]p1:
3033 // A template-argument for a template template-parameter shall be
3034 // the name of a class template, expressed as id-expression. Only
3035 // primary class templates are considered when matching the
3036 // template template argument with the corresponding parameter;
3037 // partial specializations are not considered even if their
3038 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003039 //
3040 // Note that we also allow template template parameters here, which
3041 // will happen when we are dealing with, e.g., class template
3042 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003043 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003044 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003045 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003046 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003047 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003048 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003049 << Template;
3050 }
3051
3052 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3053 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003054 true,
3055 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003056 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003057}
3058
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003059/// \brief Given a non-type template argument that refers to a
3060/// declaration and the type of its corresponding non-type template
3061/// parameter, produce an expression that properly refers to that
3062/// declaration.
3063Sema::OwningExprResult
3064Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3065 QualType ParamType,
3066 SourceLocation Loc) {
3067 assert(Arg.getKind() == TemplateArgument::Declaration &&
3068 "Only declaration template arguments permitted here");
3069 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3070
3071 if (VD->getDeclContext()->isRecord() &&
3072 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3073 // If the value is a class member, we might have a pointer-to-member.
3074 // Determine whether the non-type template template parameter is of
3075 // pointer-to-member type. If so, we need to build an appropriate
3076 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3077 // would refer to the member itself.
3078 if (ParamType->isMemberPointerType()) {
3079 QualType ClassType
3080 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3081 NestedNameSpecifier *Qualifier
3082 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
3083 CXXScopeSpec SS;
3084 SS.setScopeRep(Qualifier);
3085 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
3086 VD->getType().getNonReferenceType(),
3087 Loc,
3088 &SS);
3089 if (RefExpr.isInvalid())
3090 return ExprError();
3091
3092 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003093
3094 // We might need to perform a trailing qualification conversion, since
3095 // the element type on the parameter could be more qualified than the
3096 // element type in the expression we constructed.
3097 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3098 ParamType.getUnqualifiedType())) {
3099 Expr *RefE = RefExpr.takeAs<Expr>();
3100 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(),
3101 CastExpr::CK_NoOp);
3102 RefExpr = Owned(RefE);
3103 }
3104
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003105 assert(!RefExpr.isInvalid() &&
3106 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003107 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003108 return move(RefExpr);
3109 }
3110 }
3111
3112 QualType T = VD->getType().getNonReferenceType();
3113 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003114 // When the non-type template parameter is a pointer, take the
3115 // address of the declaration.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003116 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3117 if (RefExpr.isInvalid())
3118 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003119
3120 if (T->isFunctionType() || T->isArrayType()) {
3121 // Decay functions and arrays.
3122 Expr *RefE = (Expr *)RefExpr.get();
3123 DefaultFunctionArrayConversion(RefE);
3124 if (RefE != RefExpr.get()) {
3125 RefExpr.release();
3126 RefExpr = Owned(RefE);
3127 }
3128
3129 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003130 }
3131
Douglas Gregorb242683d2010-04-01 18:32:35 +00003132 // Take the address of everything else
3133 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003134 }
3135
3136 // If the non-type template parameter has reference type, qualify the
3137 // resulting declaration reference with the extra qualifiers on the
3138 // type that the reference refers to.
3139 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3140 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3141
3142 return BuildDeclRefExpr(VD, T, Loc);
3143}
3144
3145/// \brief Construct a new expression that refers to the given
3146/// integral template argument with the given source-location
3147/// information.
3148///
3149/// This routine takes care of the mapping from an integral template
3150/// argument (which may have any integral type) to the appropriate
3151/// literal value.
3152Sema::OwningExprResult
3153Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3154 SourceLocation Loc) {
3155 assert(Arg.getKind() == TemplateArgument::Integral &&
3156 "Operation is only value for integral template arguments");
3157 QualType T = Arg.getIntegralType();
3158 if (T->isCharType() || T->isWideCharType())
3159 return Owned(new (Context) CharacterLiteral(
3160 Arg.getAsIntegral()->getZExtValue(),
3161 T->isWideCharType(),
3162 T,
3163 Loc));
3164 if (T->isBooleanType())
3165 return Owned(new (Context) CXXBoolLiteralExpr(
3166 Arg.getAsIntegral()->getBoolValue(),
3167 T,
3168 Loc));
3169
3170 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3171}
3172
3173
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003174/// \brief Determine whether the given template parameter lists are
3175/// equivalent.
3176///
Mike Stump11289f42009-09-09 15:08:12 +00003177/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003178/// source code as part of a new template declaration.
3179///
3180/// \param Old The old template parameter list, typically found via
3181/// name lookup of the template declared with this template parameter
3182/// list.
3183///
3184/// \param Complain If true, this routine will produce a diagnostic if
3185/// the template parameter lists are not equivalent.
3186///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003187/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003188///
3189/// \param TemplateArgLoc If this source location is valid, then we
3190/// are actually checking the template parameter list of a template
3191/// argument (New) against the template parameter list of its
3192/// corresponding template template parameter (Old). We produce
3193/// slightly different diagnostics in this scenario.
3194///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003195/// \returns True if the template parameter lists are equal, false
3196/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003197bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003198Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3199 TemplateParameterList *Old,
3200 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003201 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003202 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003203 if (Old->size() != New->size()) {
3204 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003205 unsigned NextDiag = diag::err_template_param_list_different_arity;
3206 if (TemplateArgLoc.isValid()) {
3207 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3208 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003209 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003210 Diag(New->getTemplateLoc(), NextDiag)
3211 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003212 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003213 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003214 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003215 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003216 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3217 }
3218
3219 return false;
3220 }
3221
3222 for (TemplateParameterList::iterator OldParm = Old->begin(),
3223 OldParmEnd = Old->end(), NewParm = New->begin();
3224 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3225 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003226 if (Complain) {
3227 unsigned NextDiag = diag::err_template_param_different_kind;
3228 if (TemplateArgLoc.isValid()) {
3229 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3230 NextDiag = diag::note_template_param_different_kind;
3231 }
3232 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003233 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003234 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003235 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003236 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003237 return false;
3238 }
3239
Douglas Gregor2e87ca22010-06-04 08:34:32 +00003240 if (TemplateTypeParmDecl *OldTTP
3241 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3242 // Template type parameters are equivalent if either both are template
3243 // type parameter packs or neither are (since we know we're at the same
3244 // index).
3245 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3246 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3247 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3248 // allow one to match a template parameter pack in the template
3249 // parameter list of a template template parameter to one or more
3250 // template parameters in the template parameter list of the
3251 // corresponding template template argument.
3252 if (Complain) {
3253 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3254 if (TemplateArgLoc.isValid()) {
3255 Diag(TemplateArgLoc,
3256 diag::err_template_arg_template_params_mismatch);
3257 NextDiag = diag::note_template_parameter_pack_non_pack;
3258 }
3259 Diag(NewTTP->getLocation(), NextDiag)
3260 << 0 << NewTTP->isParameterPack();
3261 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3262 << 0 << OldTTP->isParameterPack();
3263 }
3264 return false;
3265 }
Mike Stump11289f42009-09-09 15:08:12 +00003266 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003267 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3268 // The types of non-type template parameters must agree.
3269 NonTypeTemplateParmDecl *NewNTTP
3270 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003271
3272 // If we are matching a template template argument to a template
3273 // template parameter and one of the non-type template parameter types
3274 // is dependent, then we must wait until template instantiation time
3275 // to actually compare the arguments.
3276 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3277 (OldNTTP->getType()->isDependentType() ||
3278 NewNTTP->getType()->isDependentType()))
3279 continue;
3280
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003281 if (Context.getCanonicalType(OldNTTP->getType()) !=
3282 Context.getCanonicalType(NewNTTP->getType())) {
3283 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003284 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3285 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003286 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003287 diag::err_template_arg_template_params_mismatch);
3288 NextDiag = diag::note_template_nontype_parm_different_type;
3289 }
3290 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003291 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003292 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003293 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003294 diag::note_template_nontype_parm_prev_declaration)
3295 << OldNTTP->getType();
3296 }
3297 return false;
3298 }
3299 } else {
3300 // The template parameter lists of template template
3301 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003302 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003303 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003304 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003305 = cast<TemplateTemplateParmDecl>(*OldParm);
3306 TemplateTemplateParmDecl *NewTTP
3307 = cast<TemplateTemplateParmDecl>(*NewParm);
3308 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3309 OldTTP->getTemplateParameters(),
3310 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003311 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003312 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003313 return false;
3314 }
3315 }
3316
3317 return true;
3318}
3319
3320/// \brief Check whether a template can be declared within this scope.
3321///
3322/// If the template declaration is valid in this scope, returns
3323/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003324bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003325Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003326 // Find the nearest enclosing declaration scope.
3327 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3328 (S->getFlags() & Scope::TemplateParamScope) != 0)
3329 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003330
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003331 // C++ [temp]p2:
3332 // A template-declaration can appear only as a namespace scope or
3333 // class scope declaration.
3334 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003335 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3336 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003337 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003338 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003339
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003340 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003341 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003342
3343 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3344 return false;
3345
Mike Stump11289f42009-09-09 15:08:12 +00003346 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003347 diag::err_template_outside_namespace_or_class_scope)
3348 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003349}
Douglas Gregor67a65642009-02-17 23:15:12 +00003350
Douglas Gregor54888652009-10-07 00:13:32 +00003351/// \brief Determine what kind of template specialization the given declaration
3352/// is.
3353static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3354 if (!D)
3355 return TSK_Undeclared;
3356
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003357 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3358 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003359 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3360 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003361 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3362 return Var->getTemplateSpecializationKind();
3363
Douglas Gregor54888652009-10-07 00:13:32 +00003364 return TSK_Undeclared;
3365}
3366
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003367/// \brief Check whether a specialization is well-formed in the current
3368/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003369///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003370/// This routine determines whether a template specialization can be declared
3371/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003372///
3373/// \param S the semantic analysis object for which this check is being
3374/// performed.
3375///
3376/// \param Specialized the entity being specialized or instantiated, which
3377/// may be a kind of template (class template, function template, etc.) or
3378/// a member of a class template (member function, static data member,
3379/// member class).
3380///
3381/// \param PrevDecl the previous declaration of this entity, if any.
3382///
3383/// \param Loc the location of the explicit specialization or instantiation of
3384/// this entity.
3385///
3386/// \param IsPartialSpecialization whether this is a partial specialization of
3387/// a class template.
3388///
Douglas Gregor54888652009-10-07 00:13:32 +00003389/// \returns true if there was an error that we cannot recover from, false
3390/// otherwise.
3391static bool CheckTemplateSpecializationScope(Sema &S,
3392 NamedDecl *Specialized,
3393 NamedDecl *PrevDecl,
3394 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003395 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003396 // Keep these "kind" numbers in sync with the %select statements in the
3397 // various diagnostics emitted by this routine.
3398 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003399 bool isTemplateSpecialization = false;
3400 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003401 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003402 isTemplateSpecialization = true;
3403 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003404 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003405 isTemplateSpecialization = true;
3406 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003407 EntityKind = 3;
3408 else if (isa<VarDecl>(Specialized))
3409 EntityKind = 4;
3410 else if (isa<RecordDecl>(Specialized))
3411 EntityKind = 5;
3412 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003413 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3414 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003415 return true;
3416 }
3417
Douglas Gregorf47b9112009-02-25 22:02:03 +00003418 // C++ [temp.expl.spec]p2:
3419 // An explicit specialization shall be declared in the namespace
3420 // of which the template is a member, or, for member templates, in
3421 // the namespace of which the enclosing class or enclosing class
3422 // template is a member. An explicit specialization of a member
3423 // function, member class or static data member of a class
3424 // template shall be declared in the namespace of which the class
3425 // template is a member. Such a declaration may also be a
3426 // definition. If the declaration is not a definition, the
3427 // specialization may be defined later in the name- space in which
3428 // the explicit specialization was declared, or in a namespace
3429 // that encloses the one in which the explicit specialization was
3430 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003431 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3432 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003433 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003434 return true;
3435 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003436
Douglas Gregor40fb7442009-10-07 17:30:37 +00003437 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3438 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003439 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003440 return true;
3441 }
3442
Douglas Gregore4b05162009-10-07 17:21:34 +00003443 // C++ [temp.class.spec]p6:
3444 // A class template partial specialization may be declared or redeclared
3445 // in any namespace scope in which its definition may be defined (14.5.1
3446 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003447 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003448 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003449 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003450 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003451 if ((!PrevDecl ||
3452 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3453 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3454 // There is no prior declaration of this entity, so this
3455 // specialization must be in the same context as the template
3456 // itself.
3457 if (!DC->Equals(SpecializedContext)) {
3458 if (isa<TranslationUnitDecl>(SpecializedContext))
3459 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3460 << EntityKind << Specialized;
3461 else if (isa<NamespaceDecl>(SpecializedContext))
3462 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3463 << EntityKind << Specialized
3464 << cast<NamedDecl>(SpecializedContext);
3465
3466 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3467 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003468 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003469 }
Douglas Gregor54888652009-10-07 00:13:32 +00003470
3471 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003472 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003473 // Note that HandleDeclarator() performs this check for explicit
3474 // specializations of function templates, static data members, and member
3475 // functions, so we skip the check here for those kinds of entities.
3476 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003477 // Should we refactor that check, so that it occurs later?
3478 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003479 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3480 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003481 if (isa<TranslationUnitDecl>(SpecializedContext))
3482 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3483 << EntityKind << Specialized;
3484 else if (isa<NamespaceDecl>(SpecializedContext))
3485 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3486 << EntityKind << Specialized
3487 << cast<NamedDecl>(SpecializedContext);
3488
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003489 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003490 }
Douglas Gregor54888652009-10-07 00:13:32 +00003491
3492 // FIXME: check for specialization-after-instantiation errors and such.
3493
Douglas Gregorf47b9112009-02-25 22:02:03 +00003494 return false;
3495}
Douglas Gregor54888652009-10-07 00:13:32 +00003496
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003497/// \brief Check the non-type template arguments of a class template
3498/// partial specialization according to C++ [temp.class.spec]p9.
3499///
Douglas Gregor09a30232009-06-12 22:08:06 +00003500/// \param TemplateParams the template parameters of the primary class
3501/// template.
3502///
3503/// \param TemplateArg the template arguments of the class template
3504/// partial specialization.
3505///
3506/// \param MirrorsPrimaryTemplate will be set true if the class
3507/// template partial specialization arguments are identical to the
3508/// implicit template arguments of the primary template. This is not
3509/// necessarily an error (C++0x), and it is left to the caller to diagnose
3510/// this condition when it is an error.
3511///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003512/// \returns true if there was an error, false otherwise.
3513bool Sema::CheckClassTemplatePartialSpecializationArgs(
3514 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003515 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003516 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003517 // FIXME: the interface to this function will have to change to
3518 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003519 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003520
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003521 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003522
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003523 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003524 // Determine whether the template argument list of the partial
3525 // specialization is identical to the implicit argument list of
3526 // the primary template. The caller may need to diagnostic this as
3527 // an error per C++ [temp.class.spec]p9b3.
3528 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003529 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003530 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3531 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003532 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003533 MirrorsPrimaryTemplate = false;
3534 } else if (TemplateTemplateParmDecl *TTP
3535 = dyn_cast<TemplateTemplateParmDecl>(
3536 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003537 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003538 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003539 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003540 if (!ArgDecl ||
3541 ArgDecl->getIndex() != TTP->getIndex() ||
3542 ArgDecl->getDepth() != TTP->getDepth())
3543 MirrorsPrimaryTemplate = false;
3544 }
3545 }
3546
Mike Stump11289f42009-09-09 15:08:12 +00003547 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003548 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003549 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003550 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003551 }
3552
Anders Carlsson40c1d492009-06-13 18:20:51 +00003553 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003554 if (!ArgExpr) {
3555 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003556 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003557 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003558
3559 // C++ [temp.class.spec]p8:
3560 // A non-type argument is non-specialized if it is the name of a
3561 // non-type parameter. All other non-type arguments are
3562 // specialized.
3563 //
3564 // Below, we check the two conditions that only apply to
3565 // specialized non-type arguments, so skip any non-specialized
3566 // arguments.
3567 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003568 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003569 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003570 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003571 (Param->getIndex() != NTTP->getIndex() ||
3572 Param->getDepth() != NTTP->getDepth()))
3573 MirrorsPrimaryTemplate = false;
3574
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003575 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003576 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003577
3578 // C++ [temp.class.spec]p9:
3579 // Within the argument list of a class template partial
3580 // specialization, the following restrictions apply:
3581 // -- A partially specialized non-type argument expression
3582 // shall not involve a template parameter of the partial
3583 // specialization except when the argument expression is a
3584 // simple identifier.
3585 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003586 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003587 diag::err_dependent_non_type_arg_in_partial_spec)
3588 << ArgExpr->getSourceRange();
3589 return true;
3590 }
3591
3592 // -- The type of a template parameter corresponding to a
3593 // specialized non-type argument shall not be dependent on a
3594 // parameter of the specialization.
3595 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003596 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003597 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3598 << Param->getType()
3599 << ArgExpr->getSourceRange();
3600 Diag(Param->getLocation(), diag::note_template_param_here);
3601 return true;
3602 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003603
3604 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003605 }
3606
3607 return false;
3608}
3609
Douglas Gregorc854c662010-02-26 06:03:23 +00003610/// \brief Retrieve the previous declaration of the given declaration.
3611static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3612 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3613 return VD->getPreviousDeclaration();
3614 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3615 return FD->getPreviousDeclaration();
3616 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3617 return TD->getPreviousDeclaration();
3618 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3619 return TD->getPreviousDeclaration();
3620 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3621 return FTD->getPreviousDeclaration();
3622 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3623 return CTD->getPreviousDeclaration();
3624 return 0;
3625}
3626
Douglas Gregorc08f4892009-03-25 00:13:59 +00003627Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003628Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3629 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003630 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003631 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003632 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003633 SourceLocation TemplateNameLoc,
3634 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003635 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003636 SourceLocation RAngleLoc,
3637 AttributeList *Attr,
3638 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003639 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003640
Douglas Gregor67a65642009-02-17 23:15:12 +00003641 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003642 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003643 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003644 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3645
3646 if (!ClassTemplate) {
3647 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3648 << (Name.getAsTemplateDecl() &&
3649 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3650 return true;
3651 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003652
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003653 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003654 bool isPartialSpecialization = false;
3655
Douglas Gregorf47b9112009-02-25 22:02:03 +00003656 // Check the validity of the template headers that introduce this
3657 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003658 // FIXME: We probably shouldn't complain about these headers for
3659 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003660 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003661 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3662 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003663 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003664 TUK == TUK_Friend,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003665 isExplicitSpecialization);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003666 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3667 if (TemplateParams)
3668 --NumMatchedTemplateParamLists;
3669
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003670 if (TemplateParams && TemplateParams->size() > 0) {
3671 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003672
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003673 // C++ [temp.class.spec]p10:
3674 // The template parameter list of a specialization shall not
3675 // contain default template argument values.
3676 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3677 Decl *Param = TemplateParams->getParam(I);
3678 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3679 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003680 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003681 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003682 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003683 }
3684 } else if (NonTypeTemplateParmDecl *NTTP
3685 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3686 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003687 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003688 diag::err_default_arg_in_partial_spec)
3689 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003690 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003691 DefArg->Destroy(Context);
3692 }
3693 } else {
3694 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003695 if (TTP->hasDefaultArgument()) {
3696 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003697 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003698 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003699 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00003700 }
3701 }
3702 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003703 } else if (TemplateParams) {
3704 if (TUK == TUK_Friend)
3705 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003706 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003707 SourceRange(TemplateParams->getTemplateLoc(),
3708 TemplateParams->getRAngleLoc()))
3709 << SourceRange(LAngleLoc, RAngleLoc);
3710 else
3711 isExplicitSpecialization = true;
3712 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003713 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003714 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003715 isExplicitSpecialization = true;
3716 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003717
Douglas Gregor67a65642009-02-17 23:15:12 +00003718 // Check that the specialization uses the same tag kind as the
3719 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003720 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3721 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00003722 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003723 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003724 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003725 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003726 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003727 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003728 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003729 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003730 diag::note_previous_use);
3731 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3732 }
3733
Douglas Gregorc40290e2009-03-09 23:48:35 +00003734 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003735 TemplateArgumentListInfo TemplateArgs;
3736 TemplateArgs.setLAngleLoc(LAngleLoc);
3737 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003738 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003739
Douglas Gregor67a65642009-02-17 23:15:12 +00003740 // Check that the template argument list is well-formed for this
3741 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003742 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3743 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003744 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3745 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003746 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003747
Mike Stump11289f42009-09-09 15:08:12 +00003748 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003749 ClassTemplate->getTemplateParameters()->size()) &&
3750 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003751
Douglas Gregor2373c592009-05-31 09:31:02 +00003752 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003753 // corresponds to these arguments.
3754 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003755 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003756 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003757 if (CheckClassTemplatePartialSpecializationArgs(
3758 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003759 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003760 return true;
3761
Douglas Gregor09a30232009-06-12 22:08:06 +00003762 if (MirrorsPrimaryTemplate) {
3763 // C++ [temp.class.spec]p9b3:
3764 //
Mike Stump11289f42009-09-09 15:08:12 +00003765 // -- The argument list of the specialization shall not be identical
3766 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003767 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003768 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003769 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003770 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003771 ClassTemplate->getIdentifier(),
3772 TemplateNameLoc,
3773 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003774 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003775 AS_none);
3776 }
3777
Douglas Gregor2208a292009-09-26 20:57:03 +00003778 // FIXME: Diagnose friend partial specializations
3779
Douglas Gregor92354b62010-02-09 00:37:32 +00003780 if (!Name.isDependent() &&
3781 !TemplateSpecializationType::anyDependentTemplateArguments(
3782 TemplateArgs.getArgumentArray(),
3783 TemplateArgs.size())) {
3784 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3785 << ClassTemplate->getDeclName();
3786 isPartialSpecialization = false;
3787 } else {
3788 // FIXME: Template parameter list matters, too
3789 ClassTemplatePartialSpecializationDecl::Profile(ID,
3790 Converted.getFlatArguments(),
3791 Converted.flatSize(),
3792 Context);
3793 }
3794 }
3795
3796 if (!isPartialSpecialization)
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003797 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003798 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003799 Converted.flatSize(),
3800 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003801 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003802 ClassTemplateSpecializationDecl *PrevDecl = 0;
3803
3804 if (isPartialSpecialization)
3805 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003806 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003807 InsertPos);
3808 else
3809 PrevDecl
3810 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003811
3812 ClassTemplateSpecializationDecl *Specialization = 0;
3813
Douglas Gregorf47b9112009-02-25 22:02:03 +00003814 // Check whether we can declare a class template specialization in
3815 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003816 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003817 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003818 TemplateNameLoc,
3819 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003820 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003821
Douglas Gregor15301382009-07-30 17:40:51 +00003822 // The canonical type
3823 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003824 if (PrevDecl &&
3825 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003826 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003827 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003828 // arguments was referenced but not declared, or we're only
3829 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003830 // declaration node as our own, updating its source location to
3831 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003832 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003833 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003834 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003835 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003836 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003837 // Build the canonical type that describes the converted template
3838 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003839 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3840 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003841 Converted.getFlatArguments(),
3842 Converted.flatSize());
3843
Douglas Gregor2373c592009-05-31 09:31:02 +00003844 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003845 ClassTemplatePartialSpecializationDecl *PrevPartial
3846 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00003847 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
3848 : ClassTemplate->getPartialSpecializations().size();
Mike Stump11289f42009-09-09 15:08:12 +00003849 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00003850 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00003851 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003852 TemplateNameLoc,
3853 TemplateParams,
3854 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003855 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003856 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003857 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00003858 PrevPartial,
3859 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00003860 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003861 if (NumMatchedTemplateParamLists > 0) {
3862 Partial->setTemplateParameterListsInfo(NumMatchedTemplateParamLists,
3863 (TemplateParameterList**) TemplateParameterLists.release());
3864 }
Douglas Gregor2373c592009-05-31 09:31:02 +00003865
3866 if (PrevPartial) {
3867 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3868 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3869 } else {
3870 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3871 }
3872 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003873
Douglas Gregor21610382009-10-29 00:04:11 +00003874 // If we are providing an explicit specialization of a member class
3875 // template specialization, make a note of that.
3876 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3877 PrevPartial->setMemberSpecialization();
3878
Douglas Gregor91772d12009-06-13 00:26:55 +00003879 // Check that all of the template parameters of the class template
3880 // partial specialization are deducible from the template
3881 // arguments. If not, this class template partial specialization
3882 // will never be used.
3883 llvm::SmallVector<bool, 8> DeducibleParams;
3884 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003885 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003886 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003887 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003888 unsigned NumNonDeducible = 0;
3889 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3890 if (!DeducibleParams[I])
3891 ++NumNonDeducible;
3892
3893 if (NumNonDeducible) {
3894 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3895 << (NumNonDeducible > 1)
3896 << SourceRange(TemplateNameLoc, RAngleLoc);
3897 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3898 if (!DeducibleParams[I]) {
3899 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3900 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003901 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003902 diag::note_partial_spec_unused_parameter)
3903 << Param->getDeclName();
3904 else
Mike Stump11289f42009-09-09 15:08:12 +00003905 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003906 diag::note_partial_spec_unused_parameter)
3907 << std::string("<anonymous>");
3908 }
3909 }
3910 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003911 } else {
3912 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003913 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003914 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00003915 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00003916 ClassTemplate->getDeclContext(),
3917 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003918 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003919 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003920 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00003921 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003922 if (NumMatchedTemplateParamLists > 0) {
3923 Specialization->setTemplateParameterListsInfo(
3924 NumMatchedTemplateParamLists,
3925 (TemplateParameterList**) TemplateParameterLists.release());
3926 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003927
3928 if (PrevDecl) {
3929 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3930 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3931 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003932 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003933 InsertPos);
3934 }
Douglas Gregor15301382009-07-30 17:40:51 +00003935
3936 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003937 }
3938
Douglas Gregor06db9f52009-10-12 20:18:28 +00003939 // C++ [temp.expl.spec]p6:
3940 // If a template, a member template or the member of a class template is
3941 // explicitly specialized then that specialization shall be declared
3942 // before the first use of that specialization that would cause an implicit
3943 // instantiation to take place, in every translation unit in which such a
3944 // use occurs; no diagnostic is required.
3945 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003946 bool Okay = false;
3947 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3948 // Is there any previous explicit specialization declaration?
3949 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3950 Okay = true;
3951 break;
3952 }
3953 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003954
Douglas Gregorc854c662010-02-26 06:03:23 +00003955 if (!Okay) {
3956 SourceRange Range(TemplateNameLoc, RAngleLoc);
3957 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3958 << Context.getTypeDeclType(Specialization) << Range;
3959
3960 Diag(PrevDecl->getPointOfInstantiation(),
3961 diag::note_instantiation_required_here)
3962 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003963 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003964 return true;
3965 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003966 }
3967
Douglas Gregor2208a292009-09-26 20:57:03 +00003968 // If this is not a friend, note that this is an explicit specialization.
3969 if (TUK != TUK_Friend)
3970 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003971
3972 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003973 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003974 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003975 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003976 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003977 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003978 Diag(Def->getLocation(), diag::note_previous_definition);
3979 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003980 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003981 }
3982 }
3983
Douglas Gregord56a91e2009-02-26 22:19:44 +00003984 // Build the fully-sugared type for this class template
3985 // specialization as the user wrote in the specialization
3986 // itself. This means that we'll pretty-print the type retrieved
3987 // from the specialization's declaration the way that the user
3988 // actually wrote the specialization, rather than formatting the
3989 // name based on the "canonical" representation used to store the
3990 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003991 TypeSourceInfo *WrittenTy
3992 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3993 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00003994 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003995 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara8075c852010-06-12 07:44:57 +00003996 Specialization->setTemplateKeywordLoc(KWLoc);
3997 }
Douglas Gregorc40290e2009-03-09 23:48:35 +00003998 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003999
Douglas Gregor1e249f82009-02-25 22:18:32 +00004000 // C++ [temp.expl.spec]p9:
4001 // A template explicit specialization is in the scope of the
4002 // namespace in which the template was defined.
4003 //
4004 // We actually implement this paragraph where we set the semantic
4005 // context (in the creation of the ClassTemplateSpecializationDecl),
4006 // but we also maintain the lexical context where the actual
4007 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00004008 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00004009
Douglas Gregor67a65642009-02-17 23:15:12 +00004010 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00004011 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00004012 Specialization->startDefinition();
4013
Douglas Gregor2208a292009-09-26 20:57:03 +00004014 if (TUK == TUK_Friend) {
4015 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4016 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00004017 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00004018 /*FIXME:*/KWLoc);
4019 Friend->setAccess(AS_public);
4020 CurContext->addDecl(Friend);
4021 } else {
4022 // Add the specialization into its lexical context, so that it can
4023 // be seen when iterating through the list of declarations in that
4024 // context. However, specializations are not found by name lookup.
4025 CurContext->addDecl(Specialization);
4026 }
Chris Lattner83f095c2009-03-28 19:18:32 +00004027 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00004028}
Douglas Gregor333489b2009-03-27 23:10:48 +00004029
Mike Stump11289f42009-09-09 15:08:12 +00004030Sema::DeclPtrTy
4031Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004032 MultiTemplateParamsArg TemplateParameterLists,
4033 Declarator &D) {
4034 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4035}
4036
Mike Stump11289f42009-09-09 15:08:12 +00004037Sema::DeclPtrTy
4038Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004039 MultiTemplateParamsArg TemplateParameterLists,
4040 Declarator &D) {
4041 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4042 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4043 "Not a function declarator!");
4044 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00004045
Douglas Gregor17a7c122009-06-24 00:54:41 +00004046 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004047 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004048 }
Mike Stump11289f42009-09-09 15:08:12 +00004049
Douglas Gregor17a7c122009-06-24 00:54:41 +00004050 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004051
4052 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004053 move(TemplateParameterLists),
4054 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004055 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00004056 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00004057 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004058 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00004059 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
4060 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004061 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00004062}
4063
John McCall4f7ced62010-02-11 01:33:53 +00004064/// \brief Strips various properties off an implicit instantiation
4065/// that has just been explicitly specialized.
4066static void StripImplicitInstantiation(NamedDecl *D) {
4067 D->invalidateAttrs();
4068
4069 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4070 FD->setInlineSpecified(false);
4071 }
4072}
4073
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004074/// \brief Diagnose cases where we have an explicit template specialization
4075/// before/after an explicit template instantiation, producing diagnostics
4076/// for those cases where they are required and determining whether the
4077/// new specialization/instantiation will have any effect.
4078///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004079/// \param NewLoc the location of the new explicit specialization or
4080/// instantiation.
4081///
4082/// \param NewTSK the kind of the new explicit specialization or instantiation.
4083///
4084/// \param PrevDecl the previous declaration of the entity.
4085///
4086/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4087///
4088/// \param PrevPointOfInstantiation if valid, indicates where the previus
4089/// declaration was instantiated (either implicitly or explicitly).
4090///
Abramo Bagnara8075c852010-06-12 07:44:57 +00004091/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004092/// specialization or instantiation has no effect and should be ignored.
4093///
4094/// \returns true if there was an error that should prevent the introduction of
4095/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004096bool
4097Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4098 TemplateSpecializationKind NewTSK,
4099 NamedDecl *PrevDecl,
4100 TemplateSpecializationKind PrevTSK,
4101 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004102 bool &HasNoEffect) {
4103 HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004104
4105 switch (NewTSK) {
4106 case TSK_Undeclared:
4107 case TSK_ImplicitInstantiation:
4108 assert(false && "Don't check implicit instantiations here");
4109 return false;
4110
4111 case TSK_ExplicitSpecialization:
4112 switch (PrevTSK) {
4113 case TSK_Undeclared:
4114 case TSK_ExplicitSpecialization:
4115 // Okay, we're just specializing something that is either already
4116 // explicitly specialized or has merely been mentioned without any
4117 // instantiation.
4118 return false;
4119
4120 case TSK_ImplicitInstantiation:
4121 if (PrevPointOfInstantiation.isInvalid()) {
4122 // The declaration itself has not actually been instantiated, so it is
4123 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004124 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004125 return false;
4126 }
4127 // Fall through
4128
4129 case TSK_ExplicitInstantiationDeclaration:
4130 case TSK_ExplicitInstantiationDefinition:
4131 assert((PrevTSK == TSK_ImplicitInstantiation ||
4132 PrevPointOfInstantiation.isValid()) &&
4133 "Explicit instantiation without point of instantiation?");
4134
4135 // C++ [temp.expl.spec]p6:
4136 // If a template, a member template or the member of a class template
4137 // is explicitly specialized then that specialization shall be declared
4138 // before the first use of that specialization that would cause an
4139 // implicit instantiation to take place, in every translation unit in
4140 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004141 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4142 // Is there any previous explicit specialization declaration?
4143 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4144 return false;
4145 }
4146
Douglas Gregor1d957a32009-10-27 18:42:08 +00004147 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004148 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004149 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004150 << (PrevTSK != TSK_ImplicitInstantiation);
4151
4152 return true;
4153 }
4154 break;
4155
4156 case TSK_ExplicitInstantiationDeclaration:
4157 switch (PrevTSK) {
4158 case TSK_ExplicitInstantiationDeclaration:
4159 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00004160 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004161 return false;
4162
4163 case TSK_Undeclared:
4164 case TSK_ImplicitInstantiation:
4165 // We're explicitly instantiating something that may have already been
4166 // implicitly instantiated; that's fine.
4167 return false;
4168
4169 case TSK_ExplicitSpecialization:
4170 // C++0x [temp.explicit]p4:
4171 // For a given set of template parameters, if an explicit instantiation
4172 // of a template appears after a declaration of an explicit
4173 // specialization for that template, the explicit instantiation has no
4174 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00004175 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004176 return false;
4177
4178 case TSK_ExplicitInstantiationDefinition:
4179 // C++0x [temp.explicit]p10:
4180 // If an entity is the subject of both an explicit instantiation
4181 // declaration and an explicit instantiation definition in the same
4182 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004183 Diag(NewLoc,
4184 diag::err_explicit_instantiation_declaration_after_definition);
4185 Diag(PrevPointOfInstantiation,
4186 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004187 assert(PrevPointOfInstantiation.isValid() &&
4188 "Explicit instantiation without point of instantiation?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00004189 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004190 return false;
4191 }
4192 break;
4193
4194 case TSK_ExplicitInstantiationDefinition:
4195 switch (PrevTSK) {
4196 case TSK_Undeclared:
4197 case TSK_ImplicitInstantiation:
4198 // We're explicitly instantiating something that may have already been
4199 // implicitly instantiated; that's fine.
4200 return false;
4201
4202 case TSK_ExplicitSpecialization:
4203 // C++ DR 259, C++0x [temp.explicit]p4:
4204 // For a given set of template parameters, if an explicit
4205 // instantiation of a template appears after a declaration of
4206 // an explicit specialization for that template, the explicit
4207 // instantiation has no effect.
4208 //
4209 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004210 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004211 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004212 if (!getLangOptions().CPlusPlus0x) {
4213 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004214 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004215 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004216 diag::note_previous_template_specialization);
4217 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004218 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004219 return false;
4220
4221 case TSK_ExplicitInstantiationDeclaration:
4222 // We're explicity instantiating a definition for something for which we
4223 // were previously asked to suppress instantiations. That's fine.
4224 return false;
4225
4226 case TSK_ExplicitInstantiationDefinition:
4227 // C++0x [temp.spec]p5:
4228 // For a given template and a given set of template-arguments,
4229 // - an explicit instantiation definition shall appear at most once
4230 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004231 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004232 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004233 Diag(PrevPointOfInstantiation,
4234 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004235 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004236 return false;
4237 }
4238 break;
4239 }
4240
4241 assert(false && "Missing specialization/instantiation case?");
4242
4243 return false;
4244}
4245
John McCallb9c78482010-04-08 09:05:18 +00004246/// \brief Perform semantic analysis for the given dependent function
4247/// template specialization. The only possible way to get a dependent
4248/// function template specialization is with a friend declaration,
4249/// like so:
4250///
4251/// template <class T> void foo(T);
4252/// template <class T> class A {
4253/// friend void foo<>(T);
4254/// };
4255///
4256/// There really isn't any useful analysis we can do here, so we
4257/// just store the information.
4258bool
4259Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4260 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4261 LookupResult &Previous) {
4262 // Remove anything from Previous that isn't a function template in
4263 // the correct context.
4264 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4265 LookupResult::Filter F = Previous.makeFilter();
4266 while (F.hasNext()) {
4267 NamedDecl *D = F.next()->getUnderlyingDecl();
4268 if (!isa<FunctionTemplateDecl>(D) ||
4269 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4270 F.erase();
4271 }
4272 F.done();
4273
4274 // Should this be diagnosed here?
4275 if (Previous.empty()) return true;
4276
4277 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4278 ExplicitTemplateArgs);
4279 return false;
4280}
4281
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004282/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004283/// specialization.
4284///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004285/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004286/// explicit function template specialization. On successful completion,
4287/// the function declaration \p FD will become a function template
4288/// specialization.
4289///
4290/// \param FD the function declaration, which will be updated to become a
4291/// function template specialization.
4292///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004293/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4294/// if any. Note that this may be valid info even when 0 arguments are
4295/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4296/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004297///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004298/// \param PrevDecl the set of declarations that may be specialized by
4299/// this function specialization.
4300bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004301Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004302 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004303 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004304 // The set of function template specializations that could match this
4305 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004306 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004307
4308 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00004309 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4310 I != E; ++I) {
4311 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4312 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004313 // Only consider templates found within the same semantic lookup scope as
4314 // FD.
4315 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4316 continue;
4317
4318 // C++ [temp.expl.spec]p11:
4319 // A trailing template-argument can be left unspecified in the
4320 // template-id naming an explicit function template specialization
4321 // provided it can be deduced from the function argument type.
4322 // Perform template argument deduction to determine whether we may be
4323 // specializing this template.
4324 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004325 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004326 FunctionDecl *Specialization = 0;
4327 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004328 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004329 FD->getType(),
4330 Specialization,
4331 Info)) {
4332 // FIXME: Template argument deduction failed; record why it failed, so
4333 // that we can provide nifty diagnostics.
4334 (void)TDK;
4335 continue;
4336 }
4337
4338 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004339 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004340 }
4341 }
4342
Douglas Gregor5de279c2009-09-26 03:41:46 +00004343 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004344 UnresolvedSetIterator Result
4345 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4346 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004347 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004348 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004349 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004350 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004351 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004352 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004353 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004354
4355 // Ignore access information; it doesn't figure into redeclaration checking.
4356 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004357 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004358
4359 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004360 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004361
4362 // If this is a friend declaration, then we're not really declaring
4363 // an explicit specialization.
4364 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004365
Douglas Gregor54888652009-10-07 00:13:32 +00004366 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004367 if (!isFriend &&
4368 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004369 Specialization->getPrimaryTemplate(),
4370 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004371 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004372 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004373
4374 // C++ [temp.expl.spec]p6:
4375 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004376 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004377 // before the first use of that specialization that would cause an implicit
4378 // instantiation to take place, in every translation unit in which such a
4379 // use occurs; no diagnostic is required.
4380 FunctionTemplateSpecializationInfo *SpecInfo
4381 = Specialization->getTemplateSpecializationInfo();
4382 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004383
Abramo Bagnara8075c852010-06-12 07:44:57 +00004384 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00004385 if (!isFriend &&
4386 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004387 TSK_ExplicitSpecialization,
4388 Specialization,
4389 SpecInfo->getTemplateSpecializationKind(),
4390 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004391 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004392 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004393
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004394 // Mark the prior declaration as an explicit specialization, so that later
4395 // clients know that this is an explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004396 if (!isFriend)
4397 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004398
4399 // Turn the given function declaration into a function template
4400 // specialization, with the template arguments from the previous
4401 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004402 // Take copies of (semantic and syntactic) template argument lists.
4403 const TemplateArgumentList* TemplArgs = new (Context)
4404 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4405 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4406 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004407 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004408 TemplArgs, /*InsertPos=*/0,
4409 SpecInfo->getTemplateSpecializationKind(),
4410 TemplArgsAsWritten);
4411
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004412 // The "previous declaration" for this function template specialization is
4413 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004414 Previous.clear();
4415 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004416 return false;
4417}
4418
Douglas Gregor86d142a2009-10-08 07:24:58 +00004419/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004420/// specialization.
4421///
4422/// This routine performs all of the semantic analysis required for an
4423/// explicit member function specialization. On successful completion,
4424/// the function declaration \p FD will become a member function
4425/// specialization.
4426///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004427/// \param Member the member declaration, which will be updated to become a
4428/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004429///
John McCall1f82f242009-11-18 22:49:29 +00004430/// \param Previous the set of declarations, one of which may be specialized
4431/// by this function specialization; the set will be modified to contain the
4432/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004433bool
John McCall1f82f242009-11-18 22:49:29 +00004434Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004435 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004436
Douglas Gregor86d142a2009-10-08 07:24:58 +00004437 // Try to find the member we are instantiating.
4438 NamedDecl *Instantiation = 0;
4439 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004440 MemberSpecializationInfo *MSInfo = 0;
4441
John McCall1f82f242009-11-18 22:49:29 +00004442 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004443 // Nowhere to look anyway.
4444 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004445 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4446 I != E; ++I) {
4447 NamedDecl *D = (*I)->getUnderlyingDecl();
4448 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004449 if (Context.hasSameType(Function->getType(), Method->getType())) {
4450 Instantiation = Method;
4451 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004452 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004453 break;
4454 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004455 }
4456 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004457 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004458 VarDecl *PrevVar;
4459 if (Previous.isSingleResult() &&
4460 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004461 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004462 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004463 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004464 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004465 }
4466 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004467 CXXRecordDecl *PrevRecord;
4468 if (Previous.isSingleResult() &&
4469 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4470 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004471 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004472 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004473 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004474 }
4475
4476 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004477 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004478 // specializations are always out-of-line, the caller will complain about
4479 // this mismatch later.
4480 return false;
4481 }
John McCalle820e5e2010-04-13 20:37:33 +00004482
4483 // If this is a friend, just bail out here before we start turning
4484 // things into explicit specializations.
4485 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4486 // Preserve instantiation information.
4487 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4488 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4489 cast<CXXMethodDecl>(InstantiatedFrom),
4490 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4491 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4492 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4493 cast<CXXRecordDecl>(InstantiatedFrom),
4494 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4495 }
4496
4497 Previous.clear();
4498 Previous.addDecl(Instantiation);
4499 return false;
4500 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004501
Douglas Gregor86d142a2009-10-08 07:24:58 +00004502 // Make sure that this is a specialization of a member.
4503 if (!InstantiatedFrom) {
4504 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4505 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004506 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4507 return true;
4508 }
4509
Douglas Gregor06db9f52009-10-12 20:18:28 +00004510 // C++ [temp.expl.spec]p6:
4511 // If a template, a member template or the member of a class template is
4512 // explicitly specialized then that spe- cialization shall be declared
4513 // before the first use of that specialization that would cause an implicit
4514 // instantiation to take place, in every translation unit in which such a
4515 // use occurs; no diagnostic is required.
4516 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004517
Abramo Bagnara8075c852010-06-12 07:44:57 +00004518 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00004519 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4520 TSK_ExplicitSpecialization,
4521 Instantiation,
4522 MSInfo->getTemplateSpecializationKind(),
4523 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004524 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004525 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004526
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004527 // Check the scope of this explicit specialization.
4528 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004529 InstantiatedFrom,
4530 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004531 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004532 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004533
Douglas Gregor86d142a2009-10-08 07:24:58 +00004534 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004535 // the original declaration to note that it is an explicit specialization
4536 // (if it was previously an implicit instantiation). This latter step
4537 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004538 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004539 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4540 if (InstantiationFunction->getTemplateSpecializationKind() ==
4541 TSK_ImplicitInstantiation) {
4542 InstantiationFunction->setTemplateSpecializationKind(
4543 TSK_ExplicitSpecialization);
4544 InstantiationFunction->setLocation(Member->getLocation());
4545 }
4546
Douglas Gregor86d142a2009-10-08 07:24:58 +00004547 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4548 cast<CXXMethodDecl>(InstantiatedFrom),
4549 TSK_ExplicitSpecialization);
4550 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004551 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4552 if (InstantiationVar->getTemplateSpecializationKind() ==
4553 TSK_ImplicitInstantiation) {
4554 InstantiationVar->setTemplateSpecializationKind(
4555 TSK_ExplicitSpecialization);
4556 InstantiationVar->setLocation(Member->getLocation());
4557 }
4558
Douglas Gregor86d142a2009-10-08 07:24:58 +00004559 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4560 cast<VarDecl>(InstantiatedFrom),
4561 TSK_ExplicitSpecialization);
4562 } else {
4563 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004564 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4565 if (InstantiationClass->getTemplateSpecializationKind() ==
4566 TSK_ImplicitInstantiation) {
4567 InstantiationClass->setTemplateSpecializationKind(
4568 TSK_ExplicitSpecialization);
4569 InstantiationClass->setLocation(Member->getLocation());
4570 }
4571
Douglas Gregor86d142a2009-10-08 07:24:58 +00004572 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004573 cast<CXXRecordDecl>(InstantiatedFrom),
4574 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004575 }
4576
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004577 // Save the caller the trouble of having to figure out which declaration
4578 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004579 Previous.clear();
4580 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004581 return false;
4582}
4583
Douglas Gregore47f5a72009-10-14 23:41:34 +00004584/// \brief Check the scope of an explicit instantiation.
4585static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4586 SourceLocation InstLoc,
4587 bool WasQualifiedName) {
4588 DeclContext *ExpectedContext
4589 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4590 DeclContext *CurContext = S.CurContext->getLookupContext();
4591
4592 // C++0x [temp.explicit]p2:
4593 // An explicit instantiation shall appear in an enclosing namespace of its
4594 // template.
4595 //
4596 // This is DR275, which we do not retroactively apply to C++98/03.
4597 if (S.getLangOptions().CPlusPlus0x &&
4598 !CurContext->Encloses(ExpectedContext)) {
4599 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004600 S.Diag(InstLoc,
4601 S.getLangOptions().CPlusPlus0x?
4602 diag::err_explicit_instantiation_out_of_scope
4603 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004604 << D << NS;
4605 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004606 S.Diag(InstLoc,
4607 S.getLangOptions().CPlusPlus0x?
4608 diag::err_explicit_instantiation_must_be_global
4609 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004610 << D;
4611 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4612 return;
4613 }
4614
4615 // C++0x [temp.explicit]p2:
4616 // If the name declared in the explicit instantiation is an unqualified
4617 // name, the explicit instantiation shall appear in the namespace where
4618 // its template is declared or, if that namespace is inline (7.3.1), any
4619 // namespace from its enclosing namespace set.
4620 if (WasQualifiedName)
4621 return;
4622
4623 if (CurContext->Equals(ExpectedContext))
4624 return;
4625
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004626 S.Diag(InstLoc,
4627 S.getLangOptions().CPlusPlus0x?
4628 diag::err_explicit_instantiation_unqualified_wrong_namespace
4629 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004630 << D << ExpectedContext;
4631 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4632}
4633
4634/// \brief Determine whether the given scope specifier has a template-id in it.
4635static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4636 if (!SS.isSet())
4637 return false;
4638
4639 // C++0x [temp.explicit]p2:
4640 // If the explicit instantiation is for a member function, a member class
4641 // or a static data member of a class template specialization, the name of
4642 // the class template specialization in the qualified-id for the member
4643 // name shall be a simple-template-id.
4644 //
4645 // C++98 has the same restriction, just worded differently.
4646 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4647 NNS; NNS = NNS->getPrefix())
4648 if (Type *T = NNS->getAsType())
4649 if (isa<TemplateSpecializationType>(T))
4650 return true;
4651
4652 return false;
4653}
4654
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004655// Explicit instantiation of a class template specialization
Douglas Gregora1f49972009-05-13 00:25:59 +00004656Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004657Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004658 SourceLocation ExternLoc,
4659 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004660 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004661 SourceLocation KWLoc,
4662 const CXXScopeSpec &SS,
4663 TemplateTy TemplateD,
4664 SourceLocation TemplateNameLoc,
4665 SourceLocation LAngleLoc,
4666 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004667 SourceLocation RAngleLoc,
4668 AttributeList *Attr) {
4669 // Find the class template we're specializing
4670 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004671 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004672 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4673
4674 // Check that the specialization uses the same tag kind as the
4675 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004676 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4677 assert(Kind != TTK_Enum &&
4678 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004679 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004680 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004681 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004682 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004683 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004684 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004685 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004686 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004687 diag::note_previous_use);
4688 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4689 }
4690
Douglas Gregore47f5a72009-10-14 23:41:34 +00004691 // C++0x [temp.explicit]p2:
4692 // There are two forms of explicit instantiation: an explicit instantiation
4693 // definition and an explicit instantiation declaration. An explicit
4694 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004695 TemplateSpecializationKind TSK
4696 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4697 : TSK_ExplicitInstantiationDeclaration;
4698
Douglas Gregora1f49972009-05-13 00:25:59 +00004699 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004700 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004701 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004702
4703 // Check that the template argument list is well-formed for this
4704 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004705 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4706 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004707 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4708 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004709 return true;
4710
Mike Stump11289f42009-09-09 15:08:12 +00004711 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004712 ClassTemplate->getTemplateParameters()->size()) &&
4713 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004714
Douglas Gregora1f49972009-05-13 00:25:59 +00004715 // Find the class template specialization declaration that
4716 // corresponds to these arguments.
4717 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004718 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004719 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004720 Converted.flatSize(),
4721 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004722 void *InsertPos = 0;
4723 ClassTemplateSpecializationDecl *PrevDecl
4724 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4725
Abramo Bagnara8075c852010-06-12 07:44:57 +00004726 TemplateSpecializationKind PrevDecl_TSK
4727 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4728
Douglas Gregor54888652009-10-07 00:13:32 +00004729 // C++0x [temp.explicit]p2:
4730 // [...] An explicit instantiation shall appear in an enclosing
4731 // namespace of its template. [...]
4732 //
4733 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004734 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4735 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004736
Douglas Gregora1f49972009-05-13 00:25:59 +00004737 ClassTemplateSpecializationDecl *Specialization = 0;
4738
Douglas Gregor0681a352009-11-25 06:01:46 +00004739 bool ReusedDecl = false;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004740 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004741 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00004742 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004743 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004744 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004745 HasNoEffect))
Douglas Gregora1f49972009-05-13 00:25:59 +00004746 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004747
Abramo Bagnara8075c852010-06-12 07:44:57 +00004748 // Even though HasNoEffect == true means that this explicit instantiation
4749 // has no effect on semantics, we go on to put its syntax in the AST.
4750
4751 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4752 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004753 // Since the only prior class template specialization with these
4754 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00004755 // declaration node as our own, updating the source location
4756 // for the template name to reflect our new declaration.
4757 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004758 Specialization = PrevDecl;
4759 Specialization->setLocation(TemplateNameLoc);
4760 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004761 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004762 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004763 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004764
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004765 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004766 // Create a new class template specialization declaration node for
4767 // this explicit specialization.
4768 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004769 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00004770 ClassTemplate->getDeclContext(),
4771 TemplateNameLoc,
4772 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004773 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004774 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004775
Abramo Bagnara8075c852010-06-12 07:44:57 +00004776 if (!HasNoEffect) {
4777 if (PrevDecl) {
4778 // Remove the previous declaration from the folding set, since we want
4779 // to introduce a new declaration.
4780 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4781 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4782 }
4783 // Insert the new specialization.
4784 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
4785 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004786 }
4787
4788 // Build the fully-sugared type for this explicit instantiation as
4789 // the user wrote in the explicit instantiation itself. This means
4790 // that we'll pretty-print the type retrieved from the
4791 // specialization's declaration the way that the user actually wrote
4792 // the explicit instantiation, rather than formatting the name based
4793 // on the "canonical" representation used to store the template
4794 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004795 TypeSourceInfo *WrittenTy
4796 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4797 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004798 Context.getTypeDeclType(Specialization));
4799 Specialization->setTypeAsWritten(WrittenTy);
4800 TemplateArgsIn.release();
4801
Abramo Bagnara8075c852010-06-12 07:44:57 +00004802 // Set source locations for keywords.
4803 Specialization->setExternLoc(ExternLoc);
4804 Specialization->setTemplateKeywordLoc(TemplateLoc);
4805
4806 // Add the explicit instantiation into its lexical context. However,
4807 // since explicit instantiations are never found by name lookup, we
4808 // just put it into the declaration context directly.
4809 Specialization->setLexicalDeclContext(CurContext);
4810 CurContext->addDecl(Specialization);
4811
4812 // Syntax is now OK, so return if it has no other effect on semantics.
4813 if (HasNoEffect) {
4814 // Set the template specialization kind.
4815 Specialization->setTemplateSpecializationKind(TSK);
4816 return DeclPtrTy::make(Specialization);
Douglas Gregor0681a352009-11-25 06:01:46 +00004817 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004818
4819 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004820 // A definition of a class template or class member template
4821 // shall be in scope at the point of the explicit instantiation of
4822 // the class template or class member template.
4823 //
4824 // This check comes when we actually try to perform the
4825 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004826 ClassTemplateSpecializationDecl *Def
4827 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004828 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004829 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004830 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004831 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00004832 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004833 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
4834 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004835
Douglas Gregor1d957a32009-10-27 18:42:08 +00004836 // Instantiate the members of this class template specialization.
4837 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004838 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004839 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004840 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4841
4842 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4843 // TSK_ExplicitInstantiationDefinition
4844 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4845 TSK == TSK_ExplicitInstantiationDefinition)
4846 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004847
Douglas Gregor12e49d32009-10-15 22:53:21 +00004848 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004849 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004850
Abramo Bagnara8075c852010-06-12 07:44:57 +00004851 // Set the template specialization kind.
4852 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00004853 return DeclPtrTy::make(Specialization);
4854}
4855
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004856// Explicit instantiation of a member class of a class template.
4857Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004858Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004859 SourceLocation ExternLoc,
4860 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004861 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004862 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004863 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004864 IdentifierInfo *Name,
4865 SourceLocation NameLoc,
4866 AttributeList *Attr) {
4867
Douglas Gregord6ab8742009-05-28 23:31:59 +00004868 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004869 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004870 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004871 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004872 MultiTemplateParamsArg(*this, 0, 0),
4873 Owned, IsDependent);
4874 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4875
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004876 if (!TagD)
4877 return true;
4878
4879 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4880 if (Tag->isEnum()) {
4881 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4882 << Context.getTypeDeclType(Tag);
4883 return true;
4884 }
4885
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004886 if (Tag->isInvalidDecl())
4887 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004888
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004889 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4890 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4891 if (!Pattern) {
4892 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4893 << Context.getTypeDeclType(Record);
4894 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4895 return true;
4896 }
4897
Douglas Gregore47f5a72009-10-14 23:41:34 +00004898 // C++0x [temp.explicit]p2:
4899 // If the explicit instantiation is for a class or member class, the
4900 // elaborated-type-specifier in the declaration shall include a
4901 // simple-template-id.
4902 //
4903 // C++98 has the same restriction, just worded differently.
4904 if (!ScopeSpecifierHasTemplateId(SS))
4905 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4906 << Record << SS.getRange();
4907
4908 // C++0x [temp.explicit]p2:
4909 // There are two forms of explicit instantiation: an explicit instantiation
4910 // definition and an explicit instantiation declaration. An explicit
4911 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004912 TemplateSpecializationKind TSK
4913 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4914 : TSK_ExplicitInstantiationDeclaration;
4915
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004916 // C++0x [temp.explicit]p2:
4917 // [...] An explicit instantiation shall appear in an enclosing
4918 // namespace of its template. [...]
4919 //
4920 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004921 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004922
4923 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004924 CXXRecordDecl *PrevDecl
4925 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004926 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004927 PrevDecl = Record;
4928 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004929 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00004930 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004931 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004932 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004933 PrevDecl,
4934 MSInfo->getTemplateSpecializationKind(),
4935 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004936 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004937 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004938 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004939 return TagD;
4940 }
4941
Douglas Gregor12e49d32009-10-15 22:53:21 +00004942 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004943 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004944 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004945 // C++ [temp.explicit]p3:
4946 // A definition of a member class of a class template shall be in scope
4947 // at the point of an explicit instantiation of the member class.
4948 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004949 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004950 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004951 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4952 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004953 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4954 << Pattern;
4955 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004956 } else {
4957 if (InstantiateClass(NameLoc, Record, Def,
4958 getTemplateInstantiationArgs(Record),
4959 TSK))
4960 return true;
4961
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004962 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004963 if (!RecordDef)
4964 return true;
4965 }
4966 }
4967
4968 // Instantiate all of the members of the class.
4969 InstantiateClassMembers(NameLoc, RecordDef,
4970 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004971
Douglas Gregor88d292c2010-05-13 16:44:06 +00004972 if (TSK == TSK_ExplicitInstantiationDefinition)
4973 MarkVTableUsed(NameLoc, RecordDef, true);
4974
Mike Stump87c57ac2009-05-16 07:39:55 +00004975 // FIXME: We don't have any representation for explicit instantiations of
4976 // member classes. Such a representation is not needed for compilation, but it
4977 // should be available for clients that want to see all of the declarations in
4978 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004979 return TagD;
4980}
4981
Douglas Gregor450f00842009-09-25 18:43:00 +00004982Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4983 SourceLocation ExternLoc,
4984 SourceLocation TemplateLoc,
4985 Declarator &D) {
4986 // Explicit instantiations always require a name.
4987 DeclarationName Name = GetNameForDeclarator(D);
4988 if (!Name) {
4989 if (!D.isInvalidType())
4990 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4991 diag::err_explicit_instantiation_requires_name)
4992 << D.getDeclSpec().getSourceRange()
4993 << D.getSourceRange();
4994
4995 return true;
4996 }
4997
4998 // The scope passed in may not be a decl scope. Zip up the scope tree until
4999 // we find one that is.
5000 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5001 (S->getFlags() & Scope::TemplateParamScope) != 0)
5002 S = S->getParent();
5003
5004 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00005005 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5006 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00005007 if (R.isNull())
5008 return true;
5009
5010 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5011 // Cannot explicitly instantiate a typedef.
5012 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5013 << Name;
5014 return true;
5015 }
5016
Douglas Gregor3c74d412009-10-14 20:14:33 +00005017 // C++0x [temp.explicit]p1:
5018 // [...] An explicit instantiation of a function template shall not use the
5019 // inline or constexpr specifiers.
5020 // Presumably, this also applies to member functions of class templates as
5021 // well.
5022 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5023 Diag(D.getDeclSpec().getInlineSpecLoc(),
5024 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00005025 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00005026
5027 // FIXME: check for constexpr specifier.
5028
Douglas Gregore47f5a72009-10-14 23:41:34 +00005029 // C++0x [temp.explicit]p2:
5030 // There are two forms of explicit instantiation: an explicit instantiation
5031 // definition and an explicit instantiation declaration. An explicit
5032 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00005033 TemplateSpecializationKind TSK
5034 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5035 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005036
John McCall27b18f82009-11-17 02:14:36 +00005037 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
5038 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00005039
5040 if (!R->isFunctionType()) {
5041 // C++ [temp.explicit]p1:
5042 // A [...] static data member of a class template can be explicitly
5043 // instantiated from the member definition associated with its class
5044 // template.
John McCall27b18f82009-11-17 02:14:36 +00005045 if (Previous.isAmbiguous())
5046 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00005047
John McCall67c00872009-12-02 08:25:40 +00005048 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005049 if (!Prev || !Prev->isStaticDataMember()) {
5050 // We expect to see a data data member here.
5051 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5052 << Name;
5053 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5054 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005055 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005056 return true;
5057 }
5058
5059 if (!Prev->getInstantiatedFromStaticDataMember()) {
5060 // FIXME: Check for explicit specialization?
5061 Diag(D.getIdentifierLoc(),
5062 diag::err_explicit_instantiation_data_member_not_instantiated)
5063 << Prev;
5064 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5065 // FIXME: Can we provide a note showing where this was declared?
5066 return true;
5067 }
5068
Douglas Gregore47f5a72009-10-14 23:41:34 +00005069 // C++0x [temp.explicit]p2:
5070 // If the explicit instantiation is for a member function, a member class
5071 // or a static data member of a class template specialization, the name of
5072 // the class template specialization in the qualified-id for the member
5073 // name shall be a simple-template-id.
5074 //
5075 // C++98 has the same restriction, just worded differently.
5076 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5077 Diag(D.getIdentifierLoc(),
5078 diag::err_explicit_instantiation_without_qualified_id)
5079 << Prev << D.getCXXScopeSpec().getRange();
5080
5081 // Check the scope of this explicit instantiation.
5082 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5083
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005084 // Verify that it is okay to explicitly instantiate here.
5085 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5086 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00005087 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005088 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005089 MSInfo->getTemplateSpecializationKind(),
5090 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005091 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005092 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005093 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005094 return DeclPtrTy();
5095
Douglas Gregor450f00842009-09-25 18:43:00 +00005096 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005097 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005098 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00005099 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
5100 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00005101
5102 // FIXME: Create an ExplicitInstantiation node?
5103 return DeclPtrTy();
5104 }
5105
Douglas Gregor0e876e02009-09-25 23:53:26 +00005106 // If the declarator is a template-id, translate the parser's template
5107 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005108 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005109 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005110 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5111 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005112 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5113 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005114 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5115 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005116 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005117 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005118 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005119 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005120 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005121
Douglas Gregor450f00842009-09-25 18:43:00 +00005122 // C++ [temp.explicit]p1:
5123 // A [...] function [...] can be explicitly instantiated from its template.
5124 // A member function [...] of a class template can be explicitly
5125 // instantiated from the member definition associated with its class
5126 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005127 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005128 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5129 P != PEnd; ++P) {
5130 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005131 if (!HasExplicitTemplateArgs) {
5132 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5133 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5134 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005135
John McCall58cc69d2010-01-27 01:50:18 +00005136 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005137 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5138 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005139 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005140 }
5141 }
5142
5143 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5144 if (!FunTmpl)
5145 continue;
5146
John McCallbc077cf2010-02-08 23:07:23 +00005147 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005148 FunctionDecl *Specialization = 0;
5149 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005150 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005151 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005152 R, Specialization, Info)) {
5153 // FIXME: Keep track of almost-matches?
5154 (void)TDK;
5155 continue;
5156 }
5157
John McCall58cc69d2010-01-27 01:50:18 +00005158 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005159 }
5160
5161 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005162 UnresolvedSetIterator Result
5163 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005164 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005165 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5166 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5167 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005168
John McCall58cc69d2010-01-27 01:50:18 +00005169 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005170 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005171
5172 // Ignore access control bits, we don't need them for redeclaration checking.
5173 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005174
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005175 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005176 Diag(D.getIdentifierLoc(),
5177 diag::err_explicit_instantiation_member_function_not_instantiated)
5178 << Specialization
5179 << (Specialization->getTemplateSpecializationKind() ==
5180 TSK_ExplicitSpecialization);
5181 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5182 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005183 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005184
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005185 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005186 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5187 PrevDecl = Specialization;
5188
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005189 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005190 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005191 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005192 PrevDecl,
5193 PrevDecl->getTemplateSpecializationKind(),
5194 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005195 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005196 return true;
5197
5198 // FIXME: We may still want to build some representation of this
5199 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00005200 if (HasNoEffect)
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005201 return DeclPtrTy();
5202 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005203
5204 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005205
5206 if (TSK == TSK_ExplicitInstantiationDefinition)
5207 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5208 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005209
Douglas Gregore47f5a72009-10-14 23:41:34 +00005210 // C++0x [temp.explicit]p2:
5211 // If the explicit instantiation is for a member function, a member class
5212 // or a static data member of a class template specialization, the name of
5213 // the class template specialization in the qualified-id for the member
5214 // name shall be a simple-template-id.
5215 //
5216 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005217 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005218 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005219 D.getCXXScopeSpec().isSet() &&
5220 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5221 Diag(D.getIdentifierLoc(),
5222 diag::err_explicit_instantiation_without_qualified_id)
5223 << Specialization << D.getCXXScopeSpec().getRange();
5224
5225 CheckExplicitInstantiationScope(*this,
5226 FunTmpl? (NamedDecl *)FunTmpl
5227 : Specialization->getInstantiatedFromMemberFunction(),
5228 D.getIdentifierLoc(),
5229 D.getCXXScopeSpec().isSet());
5230
Douglas Gregor450f00842009-09-25 18:43:00 +00005231 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5232 return DeclPtrTy();
5233}
5234
Douglas Gregor333489b2009-03-27 23:10:48 +00005235Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005236Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5237 const CXXScopeSpec &SS, IdentifierInfo *Name,
5238 SourceLocation TagLoc, SourceLocation NameLoc) {
5239 // This has to hold, because SS is expected to be defined.
5240 assert(Name && "Expected a name in a dependent tag");
5241
5242 NestedNameSpecifier *NNS
5243 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5244 if (!NNS)
5245 return true;
5246
Abramo Bagnara6150c882010-05-11 21:36:43 +00005247 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005248
Douglas Gregorba41d012010-04-24 16:38:41 +00005249 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5250 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005251 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005252 return true;
5253 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005254
5255 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5256 return Context.getDependentNameType(Kwd, NNS, Name).getAsOpaquePtr();
John McCall7f41d982009-09-11 04:59:25 +00005257}
5258
5259Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00005260Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5261 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005262 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005263 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5264 if (!NNS)
5265 return true;
5266
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005267 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005268 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005269 if (T.isNull())
5270 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005271
5272 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5273 if (isa<DependentNameType>(T)) {
5274 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005275 TL.setKeywordLoc(TypenameLoc);
5276 TL.setQualifierRange(SS.getRange());
5277 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005278 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005279 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005280 TL.setKeywordLoc(TypenameLoc);
5281 TL.setQualifierRange(SS.getRange());
5282 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005283 }
5284
5285 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor333489b2009-03-27 23:10:48 +00005286}
5287
Douglas Gregordce2b622009-04-01 00:28:59 +00005288Sema::TypeResult
5289Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5290 SourceLocation TemplateLoc, TypeTy *Ty) {
John McCallf7bcc812010-05-28 23:32:21 +00005291 TypeSourceInfo *InnerTSI = 0;
5292 QualType T = GetTypeFromParser(Ty, &InnerTSI);
Mike Stump11289f42009-09-09 15:08:12 +00005293 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00005294 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
John McCallf7bcc812010-05-28 23:32:21 +00005295
5296 assert(isa<TemplateSpecializationType>(T) &&
5297 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005298
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005299 if (computeDeclContext(SS, false)) {
5300 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005301 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005302 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005303
5304 // Push the inner type, preserving its source locations if possible.
5305 TypeLocBuilder Builder;
5306 if (InnerTSI)
5307 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5308 else
5309 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5310
Abramo Bagnara6150c882010-05-11 21:36:43 +00005311 T = Context.getElaboratedType(ETK_Typename, NNS, T);
John McCallf7bcc812010-05-28 23:32:21 +00005312 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5313 TL.setKeywordLoc(TypenameLoc);
5314 TL.setQualifierRange(SS.getRange());
5315
5316 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCall99b2fe52010-04-29 23:50:39 +00005317 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005318 }
Mike Stump11289f42009-09-09 15:08:12 +00005319
John McCallc392f372010-06-11 00:33:02 +00005320 // TODO: it's really silly that we make a template specialization
5321 // type earlier only to drop it again here.
5322 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5323 DependentTemplateName *DTN =
5324 TST->getTemplateName().getAsDependentTemplateName();
5325 assert(DTN && "dependent template has non-dependent name?");
5326 T = Context.getDependentTemplateSpecializationType(ETK_Typename, NNS,
5327 DTN->getIdentifier(),
5328 TST->getNumArgs(),
5329 TST->getArgs());
John McCall99b2fe52010-04-29 23:50:39 +00005330 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCallc392f372010-06-11 00:33:02 +00005331 DependentTemplateSpecializationTypeLoc TL =
5332 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5333 if (InnerTSI) {
5334 TemplateSpecializationTypeLoc TSTL =
5335 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5336 TL.setLAngleLoc(TSTL.getLAngleLoc());
5337 TL.setRAngleLoc(TSTL.getRAngleLoc());
5338 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5339 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5340 } else {
5341 TL.initializeLocal(SourceLocation());
5342 }
John McCallf7bcc812010-05-28 23:32:21 +00005343 TL.setKeywordLoc(TypenameLoc);
5344 TL.setQualifierRange(SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005345 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00005346}
5347
Douglas Gregor333489b2009-03-27 23:10:48 +00005348/// \brief Build the type that describes a C++ typename specifier,
5349/// e.g., "typename T::type".
5350QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005351Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5352 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005353 SourceLocation KeywordLoc, SourceRange NNSRange,
5354 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005355 CXXScopeSpec SS;
5356 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005357 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005358
John McCall0b66eb32010-05-01 00:40:08 +00005359 DeclContext *Ctx = computeDeclContext(SS);
5360 if (!Ctx) {
5361 // If the nested-name-specifier is dependent and couldn't be
5362 // resolved to a type, build a typename type.
5363 assert(NNS->isDependent());
5364 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005365 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005366
John McCall0b66eb32010-05-01 00:40:08 +00005367 // If the nested-name-specifier refers to the current instantiation,
5368 // the "typename" keyword itself is superfluous. In C++03, the
5369 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5370 // allows such extraneous "typename" keywords, and we retroactively
5371 // apply this DR to C++03 code. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005372
John McCall0b66eb32010-05-01 00:40:08 +00005373 if (RequireCompleteDeclContext(SS, Ctx))
5374 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005375
5376 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005377 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005378 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005379 unsigned DiagID = 0;
5380 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005381 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005382 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005383 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005384 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005385
5386 case LookupResult::NotFoundInCurrentInstantiation:
5387 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005388 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005389
5390 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00005391 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005392 // We found a type. Build an ElaboratedType, since the
5393 // typename-specifier was just sugar.
5394 return Context.getElaboratedType(ETK_Typename, NNS,
5395 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005396 }
5397
5398 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005399 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005400 break;
5401
John McCalle61f2ba2009-11-18 02:36:19 +00005402 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005403 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005404 return QualType();
5405
Douglas Gregor333489b2009-03-27 23:10:48 +00005406 case LookupResult::FoundOverloaded:
5407 DiagID = diag::err_typename_nested_not_type;
5408 Referenced = *Result.begin();
5409 break;
5410
John McCall6538c932009-10-10 05:48:19 +00005411 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005412 return QualType();
5413 }
5414
5415 // If we get here, it's because name lookup did not find a
5416 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005417 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5418 IILoc);
5419 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005420 if (Referenced)
5421 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5422 << Name;
5423 return QualType();
5424}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005425
5426namespace {
5427 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005428 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005429 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005430 SourceLocation Loc;
5431 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005432
Douglas Gregor15acfb92009-08-06 16:20:37 +00005433 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005434 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5435
Mike Stump11289f42009-09-09 15:08:12 +00005436 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005437 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005438 DeclarationName Entity)
5439 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005440 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005441
5442 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005443 /// transformed.
5444 ///
5445 /// For the purposes of type reconstruction, a type has already been
5446 /// transformed if it is NULL or if it is not dependent.
5447 bool AlreadyTransformed(QualType T) {
5448 return T.isNull() || !T->isDependentType();
5449 }
Mike Stump11289f42009-09-09 15:08:12 +00005450
5451 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005452 /// rebuilt.
5453 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005454
Douglas Gregor15acfb92009-08-06 16:20:37 +00005455 /// \brief Returns the name of the entity whose type is being rebuilt.
5456 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005457
Douglas Gregoref6ab412009-10-27 06:26:26 +00005458 /// \brief Sets the "base" location and entity when that
5459 /// information is known based on another transformation.
5460 void setBase(SourceLocation Loc, DeclarationName Entity) {
5461 this->Loc = Loc;
5462 this->Entity = Entity;
5463 }
5464
Douglas Gregor15acfb92009-08-06 16:20:37 +00005465 /// \brief Transforms an expression by returning the expression itself
5466 /// (an identity function).
5467 ///
5468 /// FIXME: This is completely unsafe; we will need to actually clone the
5469 /// expressions.
5470 Sema::OwningExprResult TransformExpr(Expr *E) {
Douglas Gregor14cf7522010-04-30 18:55:50 +00005471 return getSema().Owned(E->Retain());
Douglas Gregor15acfb92009-08-06 16:20:37 +00005472 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00005473 };
5474}
5475
Douglas Gregor15acfb92009-08-06 16:20:37 +00005476/// \brief Rebuilds a type within the context of the current instantiation.
5477///
Mike Stump11289f42009-09-09 15:08:12 +00005478/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005479/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005480/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005481/// partial specialization thereof). This routine will rebuild that type now
5482/// that we have entered the declarator's scope, which may produce different
5483/// canonical types, e.g.,
5484///
5485/// \code
5486/// template<typename T>
5487/// struct X {
5488/// typedef T* pointer;
5489/// pointer data();
5490/// };
5491///
5492/// template<typename T>
5493/// typename X<T>::pointer X<T>::data() { ... }
5494/// \endcode
5495///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005496/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005497/// since we do not know that we can look into X<T> when we parsed the type.
5498/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005499/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005500/// as the canonical type of T*, allowing the return types of the out-of-line
5501/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005502TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5503 SourceLocation Loc,
5504 DeclarationName Name) {
5505 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005506 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005507
Douglas Gregor15acfb92009-08-06 16:20:37 +00005508 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5509 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005510}
Douglas Gregorbe999392009-09-15 16:23:51 +00005511
John McCall99b2fe52010-04-29 23:50:39 +00005512bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5513 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005514
5515 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5516 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5517 DeclarationName());
5518 NestedNameSpecifier *Rebuilt =
5519 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005520 if (!Rebuilt) return true;
5521
5522 SS.setScopeRep(Rebuilt);
5523 return false;
John McCall2408e322010-04-27 00:57:59 +00005524}
5525
Douglas Gregorbe999392009-09-15 16:23:51 +00005526/// \brief Produces a formatted string that describes the binding of
5527/// template parameters to template arguments.
5528std::string
5529Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5530 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005531 // FIXME: For variadic templates, we'll need to get the structured list.
5532 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5533 Args.flat_size());
5534}
5535
5536std::string
5537Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5538 const TemplateArgument *Args,
5539 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005540 std::string Result;
5541
Douglas Gregore62e6a02009-11-11 19:13:48 +00005542 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005543 return Result;
5544
5545 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005546 if (I >= NumArgs)
5547 break;
5548
Douglas Gregorbe999392009-09-15 16:23:51 +00005549 if (I == 0)
5550 Result += "[with ";
5551 else
5552 Result += ", ";
5553
5554 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5555 Result += Id->getName();
5556 } else {
5557 Result += '$';
5558 Result += llvm::utostr(I);
5559 }
5560
5561 Result += " = ";
5562
5563 switch (Args[I].getKind()) {
5564 case TemplateArgument::Null:
5565 Result += "<no value>";
5566 break;
5567
5568 case TemplateArgument::Type: {
5569 std::string TypeStr;
5570 Args[I].getAsType().getAsStringInternal(TypeStr,
5571 Context.PrintingPolicy);
5572 Result += TypeStr;
5573 break;
5574 }
5575
5576 case TemplateArgument::Declaration: {
5577 bool Unnamed = true;
5578 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5579 if (ND->getDeclName()) {
5580 Unnamed = false;
5581 Result += ND->getNameAsString();
5582 }
5583 }
5584
5585 if (Unnamed) {
5586 Result += "<anonymous>";
5587 }
5588 break;
5589 }
5590
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005591 case TemplateArgument::Template: {
5592 std::string Str;
5593 llvm::raw_string_ostream OS(Str);
5594 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5595 Result += OS.str();
5596 break;
5597 }
5598
Douglas Gregorbe999392009-09-15 16:23:51 +00005599 case TemplateArgument::Integral: {
5600 Result += Args[I].getAsIntegral()->toString(10);
5601 break;
5602 }
5603
5604 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005605 // FIXME: This is non-optimal, since we're regurgitating the
5606 // expression we were given.
5607 std::string Str;
5608 {
5609 llvm::raw_string_ostream OS(Str);
5610 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5611 Context.PrintingPolicy);
5612 }
5613 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005614 break;
5615 }
5616
5617 case TemplateArgument::Pack:
5618 // FIXME: Format template argument packs
5619 Result += "<template argument pack>";
5620 break;
5621 }
5622 }
5623
5624 Result += ']';
5625 return Result;
5626}