blob: 175ddf639cb79f8a3ec4219bf0e0aff46e8b031a [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000018#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000020#include "clang/Parse/DeclSpec.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000021#include "clang/Parse/Template.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregorb7bfe792009-09-02 22:59:36 +000027/// \brief Determine whether the declaration found is acceptable as the name
28/// of a template and, if so, return that template declaration. Otherwise,
29/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000030static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
31 NamedDecl *Orig) {
32 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000033
Douglas Gregorb7bfe792009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
John McCalle9cccd82010-06-16 08:42:20 +000035 return Orig;
Mike Stump11289f42009-09-09 15:08:12 +000036
Douglas Gregorb7bfe792009-09-02 22:59:36 +000037 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
38 // C++ [temp.local]p1:
39 // Like normal (non-template) classes, class templates have an
40 // injected-class-name (Clause 9). The injected-class-name
41 // can be used with or without a template-argument-list. When
42 // it is used without a template-argument-list, it is
43 // equivalent to the injected-class-name followed by the
44 // template-parameters of the class template enclosed in
45 // <>. When it is used with a template-argument-list, it
46 // refers to the specified class template specialization,
47 // which could be the current specialization or another
48 // specialization.
49 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000051 if (Record->getDescribedClassTemplate())
52 return Record->getDescribedClassTemplate();
53
54 if (ClassTemplateSpecializationDecl *Spec
55 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
56 return Spec->getSpecializedTemplate();
57 }
Mike Stump11289f42009-09-09 15:08:12 +000058
Douglas Gregorb7bfe792009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump11289f42009-09-09 15:08:12 +000061
Douglas Gregorb7bfe792009-09-02 22:59:36 +000062 return 0;
63}
64
John McCalle66edc12009-11-24 19:00:30 +000065static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor41f90302010-04-12 20:54:26 +000066 // The set of class templates we've already seen.
67 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000068 LookupResult::Filter filter = R.makeFilter();
69 while (filter.hasNext()) {
70 NamedDecl *Orig = filter.next();
John McCalle9cccd82010-06-16 08:42:20 +000071 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
John McCalle66edc12009-11-24 19:00:30 +000072 if (!Repl)
73 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +000074 else if (Repl != Orig) {
75
76 // C++ [temp.local]p3:
77 // A lookup that finds an injected-class-name (10.2) can result in an
78 // ambiguity in certain cases (for example, if it is found in more than
79 // one base class). If all of the injected-class-names that are found
80 // refer to specializations of the same class template, and if the name
81 // is followed by a template-argument-list, the reference refers to the
82 // class template itself and not a specialization thereof, and is not
83 // ambiguous.
84 //
85 // FIXME: Will we eventually have to do the same for alias templates?
86 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
87 if (!ClassTemplates.insert(ClassTmpl)) {
88 filter.erase();
89 continue;
90 }
91
John McCalle66edc12009-11-24 19:00:30 +000092 filter.replace(Repl);
Douglas Gregor41f90302010-04-12 20:54:26 +000093 }
John McCalle66edc12009-11-24 19:00:30 +000094 }
95 filter.done();
96}
97
Douglas Gregorb7bfe792009-09-02 22:59:36 +000098TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +000099 CXXScopeSpec &SS,
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.
John McCalle66edc12009-11-24 19:00:30 +0000241 if (S) LookupName(Found, S);
242 ObjectTypeSearchedInScope = true;
243 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000244 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000245 // We cannot look into a dependent object type or nested nme
246 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000247 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000248 return;
249 } else {
250 // Perform unqualified name lookup in the current scope.
251 LookupName(Found, S);
252 }
253
Douglas Gregorc119dd52010-01-12 17:06:20 +0000254 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000255 // If we did not find any names, attempt to correct any typos.
256 DeclarationName Name = Found.getLookupName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000257 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregorc048c522010-06-29 19:27:42 +0000258 false, CTC_CXXCasts)) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000259 FilterAcceptableTemplateNames(Context, Found);
John McCalle9cccd82010-06-16 08:42:20 +0000260 if (!Found.empty()) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000261 if (LookupCtx)
262 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
263 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000264 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000265 Found.getLookupName().getAsString());
266 else
267 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
268 << Name << Found.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +0000269 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000270 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000271 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
272 Diag(Template->getLocation(), diag::note_previous_decl)
273 << Template->getDeclName();
John McCalle9cccd82010-06-16 08:42:20 +0000274 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000275 } else {
276 Found.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +0000277 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000278 }
279 }
280
John McCalle66edc12009-11-24 19:00:30 +0000281 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000282 if (Found.empty()) {
283 if (isDependent)
284 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000285 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000286 }
John McCalle66edc12009-11-24 19:00:30 +0000287
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
John McCalle9cccd82010-06-16 08:42:20 +0000306 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000307 // - 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
Douglas Gregor2ebcae12010-06-16 15:23:05 +0000454/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000455/// If the type parameter has a default argument, it will be added
456/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000457Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000458 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000459 SourceLocation KeyLoc,
460 IdentifierInfo *ParamName,
461 SourceLocation ParamNameLoc,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000462 unsigned Depth, unsigned Position,
463 SourceLocation EqualLoc,
464 TypeTy *DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000465 assert(S->isTemplateParamScope() &&
466 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000467 bool Invalid = false;
468
469 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000470 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000471 LookupOrdinaryName,
472 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000473 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000474 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000475 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000476 }
477
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000478 SourceLocation Loc = ParamNameLoc;
479 if (!ParamName)
480 Loc = KeyLoc;
481
Douglas Gregor5101c242008-12-05 18:15:24 +0000482 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000483 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
484 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000485 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000486 if (Invalid)
487 Param->setInvalidDecl();
488
489 if (ParamName) {
490 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000491 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000492 IdResolver.AddDecl(Param);
493 }
494
Douglas Gregordc13ded2010-07-01 00:00:45 +0000495 // Handle the default argument, if provided.
496 if (DefaultArg) {
497 TypeSourceInfo *DefaultTInfo;
498 GetTypeFromParser(DefaultArg, &DefaultTInfo);
499
500 assert(DefaultTInfo && "expected source information for type");
501
502 // C++0x [temp.param]p9:
503 // A default template-argument may be specified for any kind of
504 // template-parameter that is not a template parameter pack.
505 if (Ellipsis) {
506 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
507 return DeclPtrTy::make(Param);
508 }
509
510 // Check the template argument itself.
511 if (CheckTemplateArgument(Param, DefaultTInfo)) {
512 Param->setInvalidDecl();
513 return DeclPtrTy::make(Param);;
514 }
515
516 Param->setDefaultArgument(DefaultTInfo, false);
517 }
518
Chris Lattner83f095c2009-03-28 19:18:32 +0000519 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000520}
521
Douglas Gregor463421d2009-03-03 04:44:36 +0000522/// \brief Check that the type of a non-type template parameter is
523/// well-formed.
524///
525/// \returns the (possibly-promoted) parameter type if valid;
526/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000527QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000528Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000529 // We don't allow variably-modified types as the type of non-type template
530 // parameters.
531 if (T->isVariablyModifiedType()) {
532 Diag(Loc, diag::err_variably_modified_nontype_template_param)
533 << T;
534 return QualType();
535 }
536
Douglas Gregor463421d2009-03-03 04:44:36 +0000537 // C++ [temp.param]p4:
538 //
539 // A non-type template-parameter shall have one of the following
540 // (optionally cv-qualified) types:
541 //
542 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000543 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000544 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000545 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000546 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000547 T->isReferenceType() ||
548 // -- pointer to member.
549 T->isMemberPointerType() ||
550 // If T is a dependent type, we can't do the check now, so we
551 // assume that it is well-formed.
552 T->isDependentType())
553 return T;
554 // C++ [temp.param]p8:
555 //
556 // A non-type template-parameter of type "array of T" or
557 // "function returning T" is adjusted to be of type "pointer to
558 // T" or "pointer to function returning T", respectively.
559 else if (T->isArrayType())
560 // FIXME: Keep the type prior to promotion?
561 return Context.getArrayDecayedType(T);
562 else if (T->isFunctionType())
563 // FIXME: Keep the type prior to promotion?
564 return Context.getPointerType(T);
Douglas Gregor959d5a02010-05-22 16:17:30 +0000565
Douglas Gregor463421d2009-03-03 04:44:36 +0000566 Diag(Loc, diag::err_template_nontype_parm_bad_type)
567 << T;
568
569 return QualType();
570}
571
Chris Lattner83f095c2009-03-28 19:18:32 +0000572Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000573 unsigned Depth,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000574 unsigned Position,
575 SourceLocation EqualLoc,
576 ExprArg DefaultArg) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000577 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
578 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000579
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000580 assert(S->isTemplateParamScope() &&
581 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000582 bool Invalid = false;
583
584 IdentifierInfo *ParamName = D.getIdentifier();
585 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000586 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000587 LookupOrdinaryName,
588 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000589 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000590 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000591 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000592 }
593
Douglas Gregor463421d2009-03-03 04:44:36 +0000594 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000595 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000596 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000597 Invalid = true;
598 }
Douglas Gregor81338792009-02-10 17:43:50 +0000599
Douglas Gregor5101c242008-12-05 18:15:24 +0000600 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000601 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
602 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000603 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000604 if (Invalid)
605 Param->setInvalidDecl();
606
607 if (D.getIdentifier()) {
608 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000609 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000610 IdResolver.AddDecl(Param);
611 }
Douglas Gregordc13ded2010-07-01 00:00:45 +0000612
613 // Check the well-formedness of the default template argument, if provided.
614 if (Expr *Default = static_cast<Expr *>(DefaultArg.get())) {
615 TemplateArgument Converted;
616 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
617 Param->setInvalidDecl();
618 return DeclPtrTy::make(Param);;
619 }
620
621 Param->setDefaultArgument(DefaultArg.takeAs<Expr>(), false);
622 }
623
Chris Lattner83f095c2009-03-28 19:18:32 +0000624 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000625}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000626
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000627/// ActOnTemplateTemplateParameter - Called when a C++ template template
628/// parameter (e.g. T in template <template <typename> class T> class array)
629/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000630Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
631 SourceLocation TmpLoc,
632 TemplateParamsTy *Params,
633 IdentifierInfo *Name,
634 SourceLocation NameLoc,
635 unsigned Depth,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000636 unsigned Position,
637 SourceLocation EqualLoc,
638 const ParsedTemplateArgument &Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000639 assert(S->isTemplateParamScope() &&
640 "Template template parameter not in template parameter scope!");
641
642 // Construct the parameter object.
643 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000644 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
645 TmpLoc, Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000646 (TemplateParameterList*)Params);
647
Douglas Gregordc13ded2010-07-01 00:00:45 +0000648 // If the template template parameter has a name, then link the identifier
649 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000650 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000651 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000652 IdResolver.AddDecl(Param);
653 }
654
Douglas Gregordc13ded2010-07-01 00:00:45 +0000655 if (!Default.isInvalid()) {
656 // Check only that we have a template template argument. We don't want to
657 // try to check well-formedness now, because our template template parameter
658 // might have dependent types in its template parameters, which we wouldn't
659 // be able to match now.
660 //
661 // If none of the template template parameter's template arguments mention
662 // other template parameters, we could actually perform more checking here.
663 // However, it isn't worth doing.
664 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
665 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
666 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
667 << DefaultArg.getSourceRange();
668 return DeclPtrTy::make(Param);
669 }
670
671 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000672 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000673
Douglas Gregordc13ded2010-07-01 00:00:45 +0000674 return DeclPtrTy::make(Param);
Douglas Gregordba32632009-02-10 19:49:53 +0000675}
676
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000677/// ActOnTemplateParameterList - Builds a TemplateParameterList that
678/// contains the template parameters in Params/NumParams.
679Sema::TemplateParamsTy *
680Sema::ActOnTemplateParameterList(unsigned Depth,
681 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000682 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000683 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000684 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000685 SourceLocation RAngleLoc) {
686 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000687 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000688
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000689 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000690 (NamedDecl**)Params, NumParams,
691 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000692}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000693
John McCall3e11ebe2010-03-15 10:12:16 +0000694static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
695 if (SS.isSet())
696 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
697 SS.getRange());
698}
699
Douglas Gregorc08f4892009-03-25 00:13:59 +0000700Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000701Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000702 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000703 IdentifierInfo *Name, SourceLocation NameLoc,
704 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000705 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000706 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000707 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000708 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000709 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000710 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000711
712 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000713 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000714 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000715
Abramo Bagnara6150c882010-05-11 21:36:43 +0000716 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
717 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000718
719 // There is no such thing as an unnamed class template.
720 if (!Name) {
721 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000722 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000723 }
724
725 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000726 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000727 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000728 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000729 if (SS.isNotEmpty() && !SS.isInvalid()) {
730 SemanticContext = computeDeclContext(SS, true);
731 if (!SemanticContext) {
732 // FIXME: Produce a reasonable diagnostic here
733 return true;
734 }
Mike Stump11289f42009-09-09 15:08:12 +0000735
John McCall0b66eb32010-05-01 00:40:08 +0000736 if (RequireCompleteDeclContext(SS, SemanticContext))
737 return true;
738
John McCall27b18f82009-11-17 02:14:36 +0000739 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000740 } else {
741 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000742 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000743 }
Mike Stump11289f42009-09-09 15:08:12 +0000744
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000745 if (Previous.isAmbiguous())
746 return true;
747
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000748 NamedDecl *PrevDecl = 0;
749 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000750 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000751
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000752 // If there is a previous declaration with the same name, check
753 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000754 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000755 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000756
757 // We may have found the injected-class-name of a class template,
758 // class template partial specialization, or class template specialization.
759 // In these cases, grab the template that is being defined or specialized.
760 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
761 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
762 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
763 PrevClassTemplate
764 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
765 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
766 PrevClassTemplate
767 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
768 ->getSpecializedTemplate();
769 }
770 }
771
John McCalld43784f2009-12-18 11:25:59 +0000772 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000773 // C++ [namespace.memdef]p3:
774 // [...] When looking for a prior declaration of a class or a function
775 // declared as a friend, and when the name of the friend class or
776 // function is neither a qualified name nor a template-id, scopes outside
777 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000778 if (!SS.isSet()) {
779 DeclContext *OutermostContext = CurContext;
780 while (!OutermostContext->isFileContext())
781 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000782
Douglas Gregorb74b1032010-04-18 17:37:40 +0000783 if (PrevDecl &&
784 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
785 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
786 SemanticContext = PrevDecl->getDeclContext();
787 } else {
788 // Declarations in outer scopes don't matter. However, the outermost
789 // context we computed is the semantic context for our new
790 // declaration.
791 PrevDecl = PrevClassTemplate = 0;
792 SemanticContext = OutermostContext;
793 }
John McCall90d3bb92009-12-17 23:21:11 +0000794 }
Douglas Gregorb74b1032010-04-18 17:37:40 +0000795
John McCall90d3bb92009-12-17 23:21:11 +0000796 if (CurContext->isDependentContext()) {
797 // If this is a dependent context, we don't want to link the friend
798 // class template to the template in scope, because that would perform
799 // checking of the template parameter lists that can't be performed
800 // until the outer context is instantiated.
801 PrevDecl = PrevClassTemplate = 0;
802 }
803 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
804 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000805
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000806 if (PrevClassTemplate) {
807 // Ensure that the template parameter lists are compatible.
808 if (!TemplateParameterListsAreEqual(TemplateParams,
809 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000810 /*Complain=*/true,
811 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000812 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000813
814 // C++ [temp.class]p4:
815 // In a redeclaration, partial specialization, explicit
816 // specialization or explicit instantiation of a class template,
817 // the class-key shall agree in kind with the original class
818 // template declaration (7.1.5.3).
819 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000820 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000821 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000822 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000823 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000824 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000825 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000826 }
827
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000828 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000829 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000830 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000831 Diag(NameLoc, diag::err_redefinition) << Name;
832 Diag(Def->getLocation(), diag::note_previous_definition);
833 // FIXME: Would it make sense to try to "forget" the previous
834 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000835 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000836 }
837 }
838 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
839 // Maybe we will complain about the shadowed template parameter.
840 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
841 // Just pretend that we didn't see the previous declaration.
842 PrevDecl = 0;
843 } else if (PrevDecl) {
844 // C++ [temp]p5:
845 // A class template shall not have the same name as any other
846 // template, class, function, object, enumeration, enumerator,
847 // namespace, or type in the same scope (3.3), except as specified
848 // in (14.5.4).
849 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
850 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000851 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000852 }
853
Douglas Gregordba32632009-02-10 19:49:53 +0000854 // Check the template parameter list of this declaration, possibly
855 // merging in the template parameter list from the previous class
856 // template declaration.
857 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000858 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
859 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000860 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000861
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000862 if (SS.isSet()) {
863 // If the name of the template was qualified, we must be defining the
864 // template out-of-line.
865 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
866 !(TUK == TUK_Friend && CurContext->isDependentContext()))
867 Diag(NameLoc, diag::err_member_def_does_not_match)
868 << Name << SemanticContext << SS.getRange();
869 }
870
Mike Stump11289f42009-09-09 15:08:12 +0000871 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000872 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000873 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000874 PrevClassTemplate->getTemplatedDecl() : 0,
875 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000876 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000877
878 ClassTemplateDecl *NewTemplate
879 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
880 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000881 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000882 NewClass->setDescribedClassTemplate(NewTemplate);
883
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000884 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000885 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +0000886 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000887 assert(T->isDependentType() && "Class template type is not dependent?");
888 (void)T;
889
Douglas Gregorcf915552009-10-13 16:30:37 +0000890 // If we are providing an explicit specialization of a member that is a
891 // class template, make a note of that.
892 if (PrevClassTemplate &&
893 PrevClassTemplate->getInstantiatedFromMemberTemplate())
894 PrevClassTemplate->setMemberSpecialization();
895
Anders Carlsson137108d2009-03-26 01:24:28 +0000896 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000897 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000898 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000899
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000900 // Set the lexical context of these templates
901 NewClass->setLexicalDeclContext(CurContext);
902 NewTemplate->setLexicalDeclContext(CurContext);
903
John McCall9bb74a52009-07-31 02:45:11 +0000904 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000905 NewClass->startDefinition();
906
907 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000908 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000909
John McCall27b5c252009-09-14 21:59:20 +0000910 if (TUK != TUK_Friend)
911 PushOnScopeChains(NewTemplate, S);
912 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000913 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000914 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000915 NewClass->setAccess(PrevClassTemplate->getAccess());
916 }
John McCall27b5c252009-09-14 21:59:20 +0000917
Douglas Gregor3dad8422009-09-26 06:47:28 +0000918 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
919 PrevClassTemplate != NULL);
920
John McCall27b5c252009-09-14 21:59:20 +0000921 // Friend templates are visible in fairly strange ways.
922 if (!CurContext->isDependentContext()) {
923 DeclContext *DC = SemanticContext->getLookupContext();
924 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
925 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
926 PushOnScopeChains(NewTemplate, EnclosingScope,
927 /* AddToContext = */ false);
928 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000929
930 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
931 NewClass->getLocation(),
932 NewTemplate,
933 /*FIXME:*/NewClass->getLocation());
934 Friend->setAccess(AS_public);
935 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000936 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000937
Douglas Gregordba32632009-02-10 19:49:53 +0000938 if (Invalid) {
939 NewTemplate->setInvalidDecl();
940 NewClass->setInvalidDecl();
941 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000942 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000943}
944
Douglas Gregored5731f2009-11-25 17:50:39 +0000945/// \brief Diagnose the presence of a default template argument on a
946/// template parameter, which is ill-formed in certain contexts.
947///
948/// \returns true if the default template argument should be dropped.
949static bool DiagnoseDefaultTemplateArgument(Sema &S,
950 Sema::TemplateParamListContext TPC,
951 SourceLocation ParamLoc,
952 SourceRange DefArgRange) {
953 switch (TPC) {
954 case Sema::TPC_ClassTemplate:
955 return false;
956
957 case Sema::TPC_FunctionTemplate:
958 // C++ [temp.param]p9:
959 // A default template-argument shall not be specified in a
960 // function template declaration or a function template
961 // definition [...]
962 // (This sentence is not in C++0x, per DR226).
963 if (!S.getLangOptions().CPlusPlus0x)
964 S.Diag(ParamLoc,
965 diag::err_template_parameter_default_in_function_template)
966 << DefArgRange;
967 return false;
968
969 case Sema::TPC_ClassTemplateMember:
970 // C++0x [temp.param]p9:
971 // A default template-argument shall not be specified in the
972 // template-parameter-lists of the definition of a member of a
973 // class template that appears outside of the member's class.
974 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
975 << DefArgRange;
976 return true;
977
978 case Sema::TPC_FriendFunctionTemplate:
979 // C++ [temp.param]p9:
980 // A default template-argument shall not be specified in a
981 // friend template declaration.
982 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
983 << DefArgRange;
984 return true;
985
986 // FIXME: C++0x [temp.param]p9 allows default template-arguments
987 // for friend function templates if there is only a single
988 // declaration (and it is a definition). Strange!
989 }
990
991 return false;
992}
993
Douglas Gregordba32632009-02-10 19:49:53 +0000994/// \brief Checks the validity of a template parameter list, possibly
995/// considering the template parameter list from a previous
996/// declaration.
997///
998/// If an "old" template parameter list is provided, it must be
999/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1000/// template parameter list.
1001///
1002/// \param NewParams Template parameter list for a new template
1003/// declaration. This template parameter list will be updated with any
1004/// default arguments that are carried through from the previous
1005/// template parameter list.
1006///
1007/// \param OldParams If provided, template parameter list from a
1008/// previous declaration of the same template. Default template
1009/// arguments will be merged from the old template parameter list to
1010/// the new template parameter list.
1011///
Douglas Gregored5731f2009-11-25 17:50:39 +00001012/// \param TPC Describes the context in which we are checking the given
1013/// template parameter list.
1014///
Douglas Gregordba32632009-02-10 19:49:53 +00001015/// \returns true if an error occurred, false otherwise.
1016bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001017 TemplateParameterList *OldParams,
1018 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001019 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001020
Douglas Gregordba32632009-02-10 19:49:53 +00001021 // C++ [temp.param]p10:
1022 // The set of default template-arguments available for use with a
1023 // template declaration or definition is obtained by merging the
1024 // default arguments from the definition (if in scope) and all
1025 // declarations in scope in the same way default function
1026 // arguments are (8.3.6).
1027 bool SawDefaultArgument = false;
1028 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001029
Anders Carlsson327865d2009-06-12 23:20:15 +00001030 bool SawParameterPack = false;
1031 SourceLocation ParameterPackLoc;
1032
Mike Stumpc89c8e32009-02-11 23:03:27 +00001033 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001034 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001035 if (OldParams)
1036 OldParam = OldParams->begin();
1037
1038 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1039 NewParamEnd = NewParams->end();
1040 NewParam != NewParamEnd; ++NewParam) {
1041 // Variables used to diagnose redundant default arguments
1042 bool RedundantDefaultArg = false;
1043 SourceLocation OldDefaultLoc;
1044 SourceLocation NewDefaultLoc;
1045
1046 // Variables used to diagnose missing default arguments
1047 bool MissingDefaultArg = false;
1048
Anders Carlsson327865d2009-06-12 23:20:15 +00001049 // C++0x [temp.param]p11:
1050 // If a template parameter of a class template is a template parameter pack,
1051 // it must be the last template parameter.
1052 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001053 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001054 diag::err_template_param_pack_must_be_last_template_parameter);
1055 Invalid = true;
1056 }
1057
Douglas Gregordba32632009-02-10 19:49:53 +00001058 if (TemplateTypeParmDecl *NewTypeParm
1059 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001060 // Check the presence of a default argument here.
1061 if (NewTypeParm->hasDefaultArgument() &&
1062 DiagnoseDefaultTemplateArgument(*this, TPC,
1063 NewTypeParm->getLocation(),
1064 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001065 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001066 NewTypeParm->removeDefaultArgument();
1067
1068 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001069 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001070 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001071
Anders Carlsson327865d2009-06-12 23:20:15 +00001072 if (NewTypeParm->isParameterPack()) {
1073 assert(!NewTypeParm->hasDefaultArgument() &&
1074 "Parameter packs can't have a default argument!");
1075 SawParameterPack = true;
1076 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001077 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001078 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001079 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1080 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1081 SawDefaultArgument = true;
1082 RedundantDefaultArg = true;
1083 PreviousDefaultArgLoc = NewDefaultLoc;
1084 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1085 // Merge the default argument from the old declaration to the
1086 // new declaration.
1087 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001088 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001089 true);
1090 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1091 } else if (NewTypeParm->hasDefaultArgument()) {
1092 SawDefaultArgument = true;
1093 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1094 } else if (SawDefaultArgument)
1095 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001096 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001097 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001098 // Check the presence of a default argument here.
1099 if (NewNonTypeParm->hasDefaultArgument() &&
1100 DiagnoseDefaultTemplateArgument(*this, TPC,
1101 NewNonTypeParm->getLocation(),
1102 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001103 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001104 }
1105
Mike Stump12b8ce12009-08-04 21:02:39 +00001106 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001107 NonTypeTemplateParmDecl *OldNonTypeParm
1108 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001109 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001110 NewNonTypeParm->hasDefaultArgument()) {
1111 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1112 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1113 SawDefaultArgument = true;
1114 RedundantDefaultArg = true;
1115 PreviousDefaultArgLoc = NewDefaultLoc;
1116 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1117 // Merge the default argument from the old declaration to the
1118 // new declaration.
1119 SawDefaultArgument = true;
1120 // FIXME: We need to create a new kind of "default argument"
1121 // expression that points to a previous template template
1122 // parameter.
1123 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001124 OldNonTypeParm->getDefaultArgument(),
1125 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001126 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1127 } else if (NewNonTypeParm->hasDefaultArgument()) {
1128 SawDefaultArgument = true;
1129 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1130 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001131 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001132 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001133 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001134 TemplateTemplateParmDecl *NewTemplateParm
1135 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001136 if (NewTemplateParm->hasDefaultArgument() &&
1137 DiagnoseDefaultTemplateArgument(*this, TPC,
1138 NewTemplateParm->getLocation(),
1139 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001140 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001141
1142 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001143 TemplateTemplateParmDecl *OldTemplateParm
1144 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001145 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001146 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001147 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1148 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001149 SawDefaultArgument = true;
1150 RedundantDefaultArg = true;
1151 PreviousDefaultArgLoc = NewDefaultLoc;
1152 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1153 // Merge the default argument from the old declaration to the
1154 // new declaration.
1155 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001156 // FIXME: We need to create a new kind of "default argument" expression
1157 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001158 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001159 OldTemplateParm->getDefaultArgument(),
1160 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001161 PreviousDefaultArgLoc
1162 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001163 } else if (NewTemplateParm->hasDefaultArgument()) {
1164 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001165 PreviousDefaultArgLoc
1166 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001167 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001168 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001169 }
1170
1171 if (RedundantDefaultArg) {
1172 // C++ [temp.param]p12:
1173 // A template-parameter shall not be given default arguments
1174 // by two different declarations in the same scope.
1175 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1176 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1177 Invalid = true;
1178 } else if (MissingDefaultArg) {
1179 // C++ [temp.param]p11:
1180 // If a template-parameter has a default template-argument,
1181 // all subsequent template-parameters shall have a default
1182 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001183 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001184 diag::err_template_param_default_arg_missing);
1185 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1186 Invalid = true;
1187 }
1188
1189 // If we have an old template parameter list that we're merging
1190 // in, move on to the next parameter.
1191 if (OldParams)
1192 ++OldParam;
1193 }
1194
1195 return Invalid;
1196}
Douglas Gregord32e0282009-02-09 23:23:08 +00001197
Mike Stump11289f42009-09-09 15:08:12 +00001198/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001199/// specifier, returning the template parameter list that applies to the
1200/// name.
1201///
1202/// \param DeclStartLoc the start of the declaration that has a scope
1203/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001204///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001205/// \param SS the scope specifier that will be matched to the given template
1206/// parameter lists. This scope specifier precedes a qualified name that is
1207/// being declared.
1208///
1209/// \param ParamLists the template parameter lists, from the outermost to the
1210/// innermost template parameter lists.
1211///
1212/// \param NumParamLists the number of template parameter lists in ParamLists.
1213///
John McCalle820e5e2010-04-13 20:37:33 +00001214/// \param IsFriend Whether to apply the slightly different rules for
1215/// matching template parameters to scope specifiers in friend
1216/// declarations.
1217///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001218/// \param IsExplicitSpecialization will be set true if the entity being
1219/// declared is an explicit specialization, false otherwise.
1220///
Mike Stump11289f42009-09-09 15:08:12 +00001221/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001222/// name that is preceded by the scope specifier @p SS. This template
1223/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001224/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001225/// template specialization), or may be NULL (if we were's declaring isn't
1226/// itself a template).
1227TemplateParameterList *
1228Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1229 const CXXScopeSpec &SS,
1230 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001231 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001232 bool IsFriend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001233 bool &IsExplicitSpecialization,
1234 bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001235 IsExplicitSpecialization = false;
1236
Douglas Gregord8d297c2009-07-21 23:53:31 +00001237 // Find the template-ids that occur within the nested-name-specifier. These
1238 // template-ids will match up with the template parameter lists.
1239 llvm::SmallVector<const TemplateSpecializationType *, 4>
1240 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001241 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1242 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001243 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1244 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001245 const Type *T = NNS->getAsType();
1246 if (!T) break;
1247
1248 // C++0x [temp.expl.spec]p17:
1249 // A member or a member template may be nested within many
1250 // enclosing class templates. In an explicit specialization for
1251 // such a member, the member declaration shall be preceded by a
1252 // template<> for each enclosing class template that is
1253 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001254 //
1255 // Following the existing practice of GNU and EDG, we allow a typedef of a
1256 // template specialization type.
1257 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1258 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001259
Mike Stump11289f42009-09-09 15:08:12 +00001260 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001261 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001262 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1263 if (!Template)
1264 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001265
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001266 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001267 ClassTemplateSpecializationDecl *SpecDecl
1268 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1269 // If the nested name specifier refers to an explicit specialization,
1270 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001271 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1272 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001273 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001274 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001275 }
Mike Stump11289f42009-09-09 15:08:12 +00001276
Douglas Gregord8d297c2009-07-21 23:53:31 +00001277 TemplateIdsInSpecifier.push_back(SpecType);
1278 }
1279 }
Mike Stump11289f42009-09-09 15:08:12 +00001280
Douglas Gregord8d297c2009-07-21 23:53:31 +00001281 // Reverse the list of template-ids in the scope specifier, so that we can
1282 // more easily match up the template-ids and the template parameter lists.
1283 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001284
Douglas Gregord8d297c2009-07-21 23:53:31 +00001285 SourceLocation FirstTemplateLoc = DeclStartLoc;
1286 if (NumParamLists)
1287 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001288
Douglas Gregord8d297c2009-07-21 23:53:31 +00001289 // Match the template-ids found in the specifier to the template parameter
1290 // lists.
1291 unsigned Idx = 0;
1292 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1293 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001294 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1295 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001296 if (Idx >= NumParamLists) {
1297 // We have a template-id without a corresponding template parameter
1298 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001299
1300 // ...which is fine if this is a friend declaration.
1301 if (IsFriend) {
1302 IsExplicitSpecialization = true;
1303 break;
1304 }
1305
Douglas Gregord8d297c2009-07-21 23:53:31 +00001306 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001307 // FIXME: the location information here isn't great.
1308 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001309 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001310 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001311 << SS.getRange();
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001312 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001313 } else {
1314 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1315 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001316 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001317 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001318 }
1319 return 0;
1320 }
Mike Stump11289f42009-09-09 15:08:12 +00001321
Douglas Gregord8d297c2009-07-21 23:53:31 +00001322 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001323 if (DependentTemplateId) {
John McCall2408e322010-04-27 00:57:59 +00001324 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00001325
John McCall2408e322010-04-27 00:57:59 +00001326 // Are there cases in (e.g.) friends where this won't match?
1327 if (const InjectedClassNameType *Injected
1328 = TemplateId->getAs<InjectedClassNameType>()) {
1329 CXXRecordDecl *Record = Injected->getDecl();
1330 if (ClassTemplatePartialSpecializationDecl *Partial =
1331 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1332 ExpectedTemplateParams = Partial->getTemplateParameters();
1333 else
1334 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1335 ->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001336 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001337
John McCall2408e322010-04-27 00:57:59 +00001338 if (ExpectedTemplateParams)
1339 TemplateParameterListsAreEqual(ParamLists[Idx],
1340 ExpectedTemplateParams,
1341 true, TPL_TemplateMatch);
1342
Douglas Gregored5731f2009-11-25 17:50:39 +00001343 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001344 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001345 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001346 diag::err_template_param_list_matches_nontemplate)
1347 << TemplateId
1348 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001349 else
1350 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001351 }
Mike Stump11289f42009-09-09 15:08:12 +00001352
Douglas Gregord8d297c2009-07-21 23:53:31 +00001353 // If there were at least as many template-ids as there were template
1354 // parameter lists, then there are no template parameter lists remaining for
1355 // the declaration itself.
1356 if (Idx >= NumParamLists)
1357 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001358
Douglas Gregord8d297c2009-07-21 23:53:31 +00001359 // If there were too many template parameter lists, complain about that now.
1360 if (Idx != NumParamLists - 1) {
1361 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001362 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001363 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001364 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1365 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001366 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1367 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001368
1369 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1370 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1371 diag::note_explicit_template_spec_does_not_need_header)
1372 << ExplicitSpecializationsInSpecifier.back();
1373 ExplicitSpecializationsInSpecifier.pop_back();
1374 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001375
1376 // We have a template parameter list with no corresponding scope, which
1377 // means that the resulting template declaration can't be instantiated
1378 // properly (we'll end up with dependent nodes when we shouldn't).
1379 if (!isExplicitSpecHeader)
1380 Invalid = true;
1381
Douglas Gregord8d297c2009-07-21 23:53:31 +00001382 ++Idx;
1383 }
1384 }
Mike Stump11289f42009-09-09 15:08:12 +00001385
Douglas Gregord8d297c2009-07-21 23:53:31 +00001386 // Return the last template parameter list, which corresponds to the
1387 // entity being declared.
1388 return ParamLists[NumParamLists - 1];
1389}
1390
Douglas Gregordc572a32009-03-30 22:58:21 +00001391QualType Sema::CheckTemplateIdType(TemplateName Name,
1392 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001393 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001394 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001395 if (!Template) {
1396 // The template name does not resolve to a template, so we just
1397 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001398 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001399 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001400
Douglas Gregorc40290e2009-03-09 23:48:35 +00001401 // Check that the template argument list is well-formed for this
1402 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001403 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001404 TemplateArgs.size());
1405 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001406 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001407 return QualType();
1408
Mike Stump11289f42009-09-09 15:08:12 +00001409 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001410 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001411 "Converted template argument list is too short!");
1412
1413 QualType CanonType;
1414
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001415 if (Name.isDependent() ||
1416 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001417 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001418 // This class template specialization is a dependent
1419 // type. Therefore, its canonical type is another class template
1420 // specialization type that contains all of the converted
1421 // arguments in canonical form. This ensures that, e.g., A<T> and
1422 // A<T, T> have identical types when A is declared as:
1423 //
1424 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001425 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001426 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001427 Converted.getFlatArguments(),
1428 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001429
Douglas Gregora8e02e72009-07-28 23:00:59 +00001430 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001431 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001432 // In the future, we need to teach getTemplateSpecializationType to only
1433 // build the canonical type and return that to us.
1434 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001435
1436 // This might work out to be a current instantiation, in which
1437 // case the canonical type needs to be the InjectedClassNameType.
1438 //
1439 // TODO: in theory this could be a simple hashtable lookup; most
1440 // changes to CurContext don't change the set of current
1441 // instantiations.
1442 if (isa<ClassTemplateDecl>(Template)) {
1443 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1444 // If we get out to a namespace, we're done.
1445 if (Ctx->isFileContext()) break;
1446
1447 // If this isn't a record, keep looking.
1448 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1449 if (!Record) continue;
1450
1451 // Look for one of the two cases with InjectedClassNameTypes
1452 // and check whether it's the same template.
1453 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1454 !Record->getDescribedClassTemplate())
1455 continue;
1456
1457 // Fetch the injected class name type and check whether its
1458 // injected type is equal to the type we just built.
1459 QualType ICNT = Context.getTypeDeclType(Record);
1460 QualType Injected = cast<InjectedClassNameType>(ICNT)
1461 ->getInjectedSpecializationType();
1462
1463 if (CanonType != Injected->getCanonicalTypeInternal())
1464 continue;
1465
1466 // If so, the canonical type of this TST is the injected
1467 // class name type of the record we just found.
1468 assert(ICNT.isCanonical());
1469 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00001470 break;
1471 }
1472 }
Mike Stump11289f42009-09-09 15:08:12 +00001473 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001474 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001475 // Find the class template specialization declaration that
1476 // corresponds to these arguments.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001477 void *InsertPos = 0;
1478 ClassTemplateSpecializationDecl *Decl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001479 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
1480 Converted.flatSize(), InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001481 if (!Decl) {
1482 // This is the first time we have referenced this class template
1483 // specialization. Create the canonical declaration and add it to
1484 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001485 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001486 ClassTemplate->getTemplatedDecl()->getTagKind(),
1487 ClassTemplate->getDeclContext(),
1488 ClassTemplate->getLocation(),
1489 ClassTemplate,
1490 Converted, 0);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001491 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001492 Decl->setLexicalDeclContext(CurContext);
1493 }
1494
1495 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001496 assert(isa<RecordType>(CanonType) &&
1497 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001498 }
Mike Stump11289f42009-09-09 15:08:12 +00001499
Douglas Gregorc40290e2009-03-09 23:48:35 +00001500 // Build the fully-sugared type for this class template
1501 // specialization, which refers back to the class template
1502 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00001503 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001504}
1505
Douglas Gregor67a65642009-02-17 23:15:12 +00001506Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001507Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001508 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001509 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001510 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001511 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001512
Douglas Gregorc40290e2009-03-09 23:48:35 +00001513 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001514 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001515 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001516
John McCall6b51f282009-11-23 01:53:49 +00001517 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001518 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001519
1520 if (Result.isNull())
1521 return true;
1522
John McCallbcd03502009-12-07 02:54:59 +00001523 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001524 TemplateSpecializationTypeLoc TL
1525 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1526 TL.setTemplateNameLoc(TemplateLoc);
1527 TL.setLAngleLoc(LAngleLoc);
1528 TL.setRAngleLoc(RAngleLoc);
1529 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1530 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1531
1532 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001533}
John McCall06f6fe8d2009-09-04 01:14:41 +00001534
John McCalld8fe9af2009-09-08 17:47:29 +00001535Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1536 TagUseKind TUK,
1537 DeclSpec::TST TagSpec,
1538 SourceLocation TagLoc) {
1539 if (TypeResult.isInvalid())
1540 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001541
John McCall0ad16662009-10-29 08:12:44 +00001542 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001543 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001544 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001545
John McCalld8fe9af2009-09-08 17:47:29 +00001546 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001547 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001548
John McCalld8fe9af2009-09-08 17:47:29 +00001549 if (const RecordType *RT = Type->getAs<RecordType>()) {
1550 RecordDecl *D = RT->getDecl();
1551
1552 IdentifierInfo *Id = D->getIdentifier();
1553 assert(Id && "templated class must have an identifier");
1554
1555 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1556 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001557 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001558 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001559 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001560 }
1561 }
1562
Abramo Bagnara6150c882010-05-11 21:36:43 +00001563 ElaboratedTypeKeyword Keyword
1564 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1565 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001566
1567 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001568}
1569
John McCalle66edc12009-11-24 19:00:30 +00001570Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1571 LookupResult &R,
1572 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001573 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001574 // FIXME: Can we do any checking at this point? I guess we could check the
1575 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001576 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001577 // though.
John McCalle66edc12009-11-24 19:00:30 +00001578
1579 // These should be filtered out by our callers.
1580 assert(!R.empty() && "empty lookup results when building templateid");
1581 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1582
1583 NestedNameSpecifier *Qualifier = 0;
1584 SourceRange QualifierRange;
1585 if (SS.isSet()) {
1586 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1587 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001588 }
John McCall58cc69d2010-01-27 01:50:18 +00001589
1590 // We don't want lookup warnings at this point.
1591 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001592
John McCalle66edc12009-11-24 19:00:30 +00001593 bool Dependent
1594 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1595 &TemplateArgs);
1596 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001597 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001598 Qualifier, QualifierRange,
1599 R.getLookupName(), R.getNameLoc(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001600 RequiresADL, TemplateArgs,
1601 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001602
1603 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001604}
1605
John McCalle66edc12009-11-24 19:00:30 +00001606// We actually only call this from template instantiation.
1607Sema::OwningExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001608Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001609 DeclarationName Name,
1610 SourceLocation NameLoc,
1611 const TemplateArgumentListInfo &TemplateArgs) {
1612 DeclContext *DC;
1613 if (!(DC = computeDeclContext(SS, false)) ||
1614 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001615 RequireCompleteDeclContext(SS, DC))
John McCalle66edc12009-11-24 19:00:30 +00001616 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001617
Douglas Gregor786123d2010-05-21 23:18:07 +00001618 bool MemberOfUnknownSpecialization;
John McCalle66edc12009-11-24 19:00:30 +00001619 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00001620 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1621 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00001622
John McCalle66edc12009-11-24 19:00:30 +00001623 if (R.isAmbiguous())
1624 return ExprError();
1625
1626 if (R.empty()) {
1627 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1628 << Name << SS.getRange();
1629 return ExprError();
1630 }
1631
1632 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1633 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1634 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1635 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1636 return ExprError();
1637 }
1638
1639 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001640}
1641
Douglas Gregorb67535d2009-03-31 00:43:58 +00001642/// \brief Form a dependent template name.
1643///
1644/// This action forms a dependent template name given the template
1645/// name and its (presumably dependent) scope specifier. For
1646/// example, given "MetaFun::template apply", the scope specifier \p
1647/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1648/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregorbb119652010-06-16 23:00:59 +00001649TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1650 SourceLocation TemplateKWLoc,
1651 CXXScopeSpec &SS,
1652 UnqualifiedId &Name,
1653 TypeTy *ObjectType,
1654 bool EnteringContext,
1655 TemplateTy &Result) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00001656 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1657 !getLangOptions().CPlusPlus0x)
1658 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1659 << FixItHint::CreateRemoval(TemplateKWLoc);
1660
Douglas Gregor9abe2372010-01-19 16:01:07 +00001661 DeclContext *LookupCtx = 0;
1662 if (SS.isSet())
1663 LookupCtx = computeDeclContext(SS, EnteringContext);
1664 if (!LookupCtx && ObjectType)
1665 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1666 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001667 // C++0x [temp.names]p5:
1668 // If a name prefixed by the keyword template is not the name of
1669 // a template, the program is ill-formed. [Note: the keyword
1670 // template may not be applied to non-template members of class
1671 // templates. -end note ] [ Note: as is the case with the
1672 // typename prefix, the template prefix is allowed in cases
1673 // where it is not strictly necessary; i.e., when the
1674 // nested-name-specifier or the expression on the left of the ->
1675 // or . is not dependent on a template-parameter, or the use
1676 // does not appear in the scope of a template. -end note]
1677 //
1678 // Note: C++03 was more strict here, because it banned the use of
1679 // the "template" keyword prior to a template-name that was not a
1680 // dependent name. C++ DR468 relaxed this requirement (the
1681 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00001682 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00001683 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001684 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00001685 EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00001686 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001687 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1688 isa<CXXRecordDecl>(LookupCtx) &&
1689 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregorbb119652010-06-16 23:00:59 +00001690 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00001691 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001692 Diag(Name.getSourceRange().getBegin(),
1693 diag::err_template_kw_refers_to_non_template)
1694 << GetNameFromUnqualifiedId(Name)
Douglas Gregorb22ee882010-05-05 05:58:24 +00001695 << Name.getSourceRange()
1696 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001697 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00001698 } else {
1699 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00001700 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001701 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001702 }
1703
Mike Stump11289f42009-09-09 15:08:12 +00001704 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001705 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001706
1707 switch (Name.getKind()) {
1708 case UnqualifiedId::IK_Identifier:
Douglas Gregorbb119652010-06-16 23:00:59 +00001709 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1710 Name.Identifier));
1711 return TNK_Dependent_template_name;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001712
Douglas Gregor71395fa2009-11-04 00:56:37 +00001713 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00001714 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00001715 Name.OperatorFunctionId.Operator));
Douglas Gregorbb119652010-06-16 23:00:59 +00001716 return TNK_Dependent_template_name;
Alexis Hunted0530f2009-11-28 08:58:14 +00001717
1718 case UnqualifiedId::IK_LiteralOperatorId:
1719 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1720
Douglas Gregor3cf81312009-11-03 23:16:33 +00001721 default:
1722 break;
1723 }
1724
1725 Diag(Name.getSourceRange().getBegin(),
1726 diag::err_template_kw_refers_to_non_template)
1727 << GetNameFromUnqualifiedId(Name)
Douglas Gregorb22ee882010-05-05 05:58:24 +00001728 << Name.getSourceRange()
1729 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001730 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001731}
1732
Mike Stump11289f42009-09-09 15:08:12 +00001733bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001734 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001735 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001736 const TemplateArgument &Arg = AL.getArgument();
1737
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001738 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001739 switch(Arg.getKind()) {
1740 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001741 // C++ [temp.arg.type]p1:
1742 // A template-argument for a template-parameter which is a
1743 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001744 break;
1745 case TemplateArgument::Template: {
1746 // We have a template type parameter but the template argument
1747 // is a template without any arguments.
1748 SourceRange SR = AL.getSourceRange();
1749 TemplateName Name = Arg.getAsTemplate();
1750 Diag(SR.getBegin(), diag::err_template_missing_args)
1751 << Name << SR;
1752 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1753 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001754
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001755 return true;
1756 }
1757 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001758 // We have a template type parameter but the template argument
1759 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001760 SourceRange SR = AL.getSourceRange();
1761 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001762 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001763
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001764 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001765 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001766 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001767
John McCallbcd03502009-12-07 02:54:59 +00001768 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001769 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001770
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001771 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001772 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001773 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001774 return false;
1775}
1776
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001777/// \brief Substitute template arguments into the default template argument for
1778/// the given template type parameter.
1779///
1780/// \param SemaRef the semantic analysis object for which we are performing
1781/// the substitution.
1782///
1783/// \param Template the template that we are synthesizing template arguments
1784/// for.
1785///
1786/// \param TemplateLoc the location of the template name that started the
1787/// template-id we are checking.
1788///
1789/// \param RAngleLoc the location of the right angle bracket ('>') that
1790/// terminates the template-id.
1791///
1792/// \param Param the template template parameter whose default we are
1793/// substituting into.
1794///
1795/// \param Converted the list of template arguments provided for template
1796/// parameters that precede \p Param in the template parameter list.
1797///
1798/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001799static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001800SubstDefaultTemplateArgument(Sema &SemaRef,
1801 TemplateDecl *Template,
1802 SourceLocation TemplateLoc,
1803 SourceLocation RAngleLoc,
1804 TemplateTypeParmDecl *Param,
1805 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001806 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001807
1808 // If the argument type is dependent, instantiate it now based
1809 // on the previously-computed template arguments.
1810 if (ArgType->getType()->isDependentType()) {
1811 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1812 /*TakeArgs=*/false);
1813
1814 MultiLevelTemplateArgumentList AllTemplateArgs
1815 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1816
1817 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1818 Template, Converted.getFlatArguments(),
1819 Converted.flatSize(),
1820 SourceRange(TemplateLoc, RAngleLoc));
1821
1822 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1823 Param->getDefaultArgumentLoc(),
1824 Param->getDeclName());
1825 }
1826
1827 return ArgType;
1828}
1829
1830/// \brief Substitute template arguments into the default template argument for
1831/// the given non-type template parameter.
1832///
1833/// \param SemaRef the semantic analysis object for which we are performing
1834/// the substitution.
1835///
1836/// \param Template the template that we are synthesizing template arguments
1837/// for.
1838///
1839/// \param TemplateLoc the location of the template name that started the
1840/// template-id we are checking.
1841///
1842/// \param RAngleLoc the location of the right angle bracket ('>') that
1843/// terminates the template-id.
1844///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001845/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001846/// substituting into.
1847///
1848/// \param Converted the list of template arguments provided for template
1849/// parameters that precede \p Param in the template parameter list.
1850///
1851/// \returns the substituted template argument, or NULL if an error occurred.
1852static Sema::OwningExprResult
1853SubstDefaultTemplateArgument(Sema &SemaRef,
1854 TemplateDecl *Template,
1855 SourceLocation TemplateLoc,
1856 SourceLocation RAngleLoc,
1857 NonTypeTemplateParmDecl *Param,
1858 TemplateArgumentListBuilder &Converted) {
1859 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1860 /*TakeArgs=*/false);
1861
1862 MultiLevelTemplateArgumentList AllTemplateArgs
1863 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1864
1865 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1866 Template, Converted.getFlatArguments(),
1867 Converted.flatSize(),
1868 SourceRange(TemplateLoc, RAngleLoc));
1869
1870 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1871}
1872
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001873/// \brief Substitute template arguments into the default template argument for
1874/// the given template template parameter.
1875///
1876/// \param SemaRef the semantic analysis object for which we are performing
1877/// the substitution.
1878///
1879/// \param Template the template that we are synthesizing template arguments
1880/// for.
1881///
1882/// \param TemplateLoc the location of the template name that started the
1883/// template-id we are checking.
1884///
1885/// \param RAngleLoc the location of the right angle bracket ('>') that
1886/// terminates the template-id.
1887///
1888/// \param Param the template template parameter whose default we are
1889/// substituting into.
1890///
1891/// \param Converted the list of template arguments provided for template
1892/// parameters that precede \p Param in the template parameter list.
1893///
1894/// \returns the substituted template argument, or NULL if an error occurred.
1895static TemplateName
1896SubstDefaultTemplateArgument(Sema &SemaRef,
1897 TemplateDecl *Template,
1898 SourceLocation TemplateLoc,
1899 SourceLocation RAngleLoc,
1900 TemplateTemplateParmDecl *Param,
1901 TemplateArgumentListBuilder &Converted) {
1902 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1903 /*TakeArgs=*/false);
1904
1905 MultiLevelTemplateArgumentList AllTemplateArgs
1906 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1907
1908 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1909 Template, Converted.getFlatArguments(),
1910 Converted.flatSize(),
1911 SourceRange(TemplateLoc, RAngleLoc));
1912
1913 return SemaRef.SubstTemplateName(
1914 Param->getDefaultArgument().getArgument().getAsTemplate(),
1915 Param->getDefaultArgument().getTemplateNameLoc(),
1916 AllTemplateArgs);
1917}
1918
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001919/// \brief If the given template parameter has a default template
1920/// argument, substitute into that default template argument and
1921/// return the corresponding template argument.
1922TemplateArgumentLoc
1923Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1924 SourceLocation TemplateLoc,
1925 SourceLocation RAngleLoc,
1926 Decl *Param,
1927 TemplateArgumentListBuilder &Converted) {
1928 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1929 if (!TypeParm->hasDefaultArgument())
1930 return TemplateArgumentLoc();
1931
John McCallbcd03502009-12-07 02:54:59 +00001932 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001933 TemplateLoc,
1934 RAngleLoc,
1935 TypeParm,
1936 Converted);
1937 if (DI)
1938 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1939
1940 return TemplateArgumentLoc();
1941 }
1942
1943 if (NonTypeTemplateParmDecl *NonTypeParm
1944 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1945 if (!NonTypeParm->hasDefaultArgument())
1946 return TemplateArgumentLoc();
1947
1948 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1949 TemplateLoc,
1950 RAngleLoc,
1951 NonTypeParm,
1952 Converted);
1953 if (Arg.isInvalid())
1954 return TemplateArgumentLoc();
1955
1956 Expr *ArgE = Arg.takeAs<Expr>();
1957 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1958 }
1959
1960 TemplateTemplateParmDecl *TempTempParm
1961 = cast<TemplateTemplateParmDecl>(Param);
1962 if (!TempTempParm->hasDefaultArgument())
1963 return TemplateArgumentLoc();
1964
1965 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1966 TemplateLoc,
1967 RAngleLoc,
1968 TempTempParm,
1969 Converted);
1970 if (TName.isNull())
1971 return TemplateArgumentLoc();
1972
1973 return TemplateArgumentLoc(TemplateArgument(TName),
1974 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1975 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1976}
1977
Douglas Gregorda0fb532009-11-11 19:31:23 +00001978/// \brief Check that the given template argument corresponds to the given
1979/// template parameter.
1980bool Sema::CheckTemplateArgument(NamedDecl *Param,
1981 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001982 TemplateDecl *Template,
1983 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001984 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001985 TemplateArgumentListBuilder &Converted,
1986 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001987 // Check template type parameters.
1988 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001989 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001990
Douglas Gregoreebed722009-11-11 19:41:09 +00001991 // Check non-type template parameters.
1992 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001993 // Do substitution on the type of the non-type template parameter
1994 // with the template arguments we've seen thus far.
1995 QualType NTTPType = NTTP->getType();
1996 if (NTTPType->isDependentType()) {
1997 // Do substitution on the type of the non-type template parameter.
1998 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1999 NTTP, Converted.getFlatArguments(),
2000 Converted.flatSize(),
2001 SourceRange(TemplateLoc, RAngleLoc));
2002
2003 TemplateArgumentList TemplateArgs(Context, Converted,
2004 /*TakeArgs=*/false);
2005 NTTPType = SubstType(NTTPType,
2006 MultiLevelTemplateArgumentList(TemplateArgs),
2007 NTTP->getLocation(),
2008 NTTP->getDeclName());
2009 // If that worked, check the non-type template parameter type
2010 // for validity.
2011 if (!NTTPType.isNull())
2012 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2013 NTTP->getLocation());
2014 if (NTTPType.isNull())
2015 return true;
2016 }
2017
2018 switch (Arg.getArgument().getKind()) {
2019 case TemplateArgument::Null:
2020 assert(false && "Should never see a NULL template argument here");
2021 return true;
2022
2023 case TemplateArgument::Expression: {
2024 Expr *E = Arg.getArgument().getAsExpr();
2025 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002026 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002027 return true;
2028
2029 Converted.Append(Result);
2030 break;
2031 }
2032
2033 case TemplateArgument::Declaration:
2034 case TemplateArgument::Integral:
2035 // We've already checked this template argument, so just copy
2036 // it to the list of converted arguments.
2037 Converted.Append(Arg.getArgument());
2038 break;
2039
2040 case TemplateArgument::Template:
2041 // We were given a template template argument. It may not be ill-formed;
2042 // see below.
2043 if (DependentTemplateName *DTN
2044 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2045 // We have a template argument such as \c T::template X, which we
2046 // parsed as a template template argument. However, since we now
2047 // know that we need a non-type template argument, convert this
2048 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00002049 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2050 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002051 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00002052 DTN->getIdentifier(),
2053 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00002054
2055 TemplateArgument Result;
2056 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2057 return true;
2058
2059 Converted.Append(Result);
2060 break;
2061 }
2062
2063 // We have a template argument that actually does refer to a class
2064 // template, template alias, or template template parameter, and
2065 // therefore cannot be a non-type template argument.
2066 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2067 << Arg.getSourceRange();
2068
2069 Diag(Param->getLocation(), diag::note_template_param_here);
2070 return true;
2071
2072 case TemplateArgument::Type: {
2073 // We have a non-type template parameter but the template
2074 // argument is a type.
2075
2076 // C++ [temp.arg]p2:
2077 // In a template-argument, an ambiguity between a type-id and
2078 // an expression is resolved to a type-id, regardless of the
2079 // form of the corresponding template-parameter.
2080 //
2081 // We warn specifically about this case, since it can be rather
2082 // confusing for users.
2083 QualType T = Arg.getArgument().getAsType();
2084 SourceRange SR = Arg.getSourceRange();
2085 if (T->isFunctionType())
2086 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2087 else
2088 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2089 Diag(Param->getLocation(), diag::note_template_param_here);
2090 return true;
2091 }
2092
2093 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002094 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002095 break;
2096 }
2097
2098 return false;
2099 }
2100
2101
2102 // Check template template parameters.
2103 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2104
2105 // Substitute into the template parameter list of the template
2106 // template parameter, since previously-supplied template arguments
2107 // may appear within the template template parameter.
2108 {
2109 // Set up a template instantiation context.
2110 LocalInstantiationScope Scope(*this);
2111 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2112 TempParm, Converted.getFlatArguments(),
2113 Converted.flatSize(),
2114 SourceRange(TemplateLoc, RAngleLoc));
2115
2116 TemplateArgumentList TemplateArgs(Context, Converted,
2117 /*TakeArgs=*/false);
2118 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2119 SubstDecl(TempParm, CurContext,
2120 MultiLevelTemplateArgumentList(TemplateArgs)));
2121 if (!TempParm)
2122 return true;
2123
2124 // FIXME: TempParam is leaked.
2125 }
2126
2127 switch (Arg.getArgument().getKind()) {
2128 case TemplateArgument::Null:
2129 assert(false && "Should never see a NULL template argument here");
2130 return true;
2131
2132 case TemplateArgument::Template:
2133 if (CheckTemplateArgument(TempParm, Arg))
2134 return true;
2135
2136 Converted.Append(Arg.getArgument());
2137 break;
2138
2139 case TemplateArgument::Expression:
2140 case TemplateArgument::Type:
2141 // We have a template template parameter but the template
2142 // argument does not refer to a template.
2143 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2144 return true;
2145
2146 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002147 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002148 "Declaration argument with template template parameter");
2149 break;
2150 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002151 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002152 "Integral argument with template template parameter");
2153 break;
2154
2155 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002156 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002157 break;
2158 }
2159
2160 return false;
2161}
2162
Douglas Gregord32e0282009-02-09 23:23:08 +00002163/// \brief Check that the given template argument list is well-formed
2164/// for specializing the given template.
2165bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2166 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002167 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002168 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002169 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002170 TemplateParameterList *Params = Template->getTemplateParameters();
2171 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002172 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002173 bool Invalid = false;
2174
John McCall6b51f282009-11-23 01:53:49 +00002175 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2176
Mike Stump11289f42009-09-09 15:08:12 +00002177 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002178 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002179
Anders Carlsson15201f12009-06-13 02:08:00 +00002180 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002181 (NumArgs < Params->getMinRequiredArguments() &&
2182 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002183 // FIXME: point at either the first arg beyond what we can handle,
2184 // or the '>', depending on whether we have too many or too few
2185 // arguments.
2186 SourceRange Range;
2187 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002188 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002189 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2190 << (NumArgs > NumParams)
2191 << (isa<ClassTemplateDecl>(Template)? 0 :
2192 isa<FunctionTemplateDecl>(Template)? 1 :
2193 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2194 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002195 Diag(Template->getLocation(), diag::note_template_decl_here)
2196 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002197 Invalid = true;
2198 }
Mike Stump11289f42009-09-09 15:08:12 +00002199
2200 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002201 // [...] The type and form of each template-argument specified in
2202 // a template-id shall match the type and form specified for the
2203 // corresponding parameter declared by the template in its
2204 // template-parameter-list.
2205 unsigned ArgIdx = 0;
2206 for (TemplateParameterList::iterator Param = Params->begin(),
2207 ParamEnd = Params->end();
2208 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002209 if (ArgIdx > NumArgs && PartialTemplateArgs)
2210 break;
Mike Stump11289f42009-09-09 15:08:12 +00002211
Douglas Gregoreebed722009-11-11 19:41:09 +00002212 // If we have a template parameter pack, check every remaining template
2213 // argument against that template parameter pack.
2214 if ((*Param)->isTemplateParameterPack()) {
2215 Converted.BeginPack();
2216 for (; ArgIdx < NumArgs; ++ArgIdx) {
2217 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2218 TemplateLoc, RAngleLoc, Converted)) {
2219 Invalid = true;
2220 break;
2221 }
2222 }
2223 Converted.EndPack();
2224 continue;
2225 }
2226
Douglas Gregor84d49a22009-11-11 21:54:23 +00002227 if (ArgIdx < NumArgs) {
2228 // Check the template argument we were given.
2229 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2230 TemplateLoc, RAngleLoc, Converted))
2231 return true;
2232
2233 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002234 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002235
Douglas Gregor84d49a22009-11-11 21:54:23 +00002236 // We have a default template argument that we will use.
2237 TemplateArgumentLoc Arg;
2238
2239 // Retrieve the default template argument from the template
2240 // parameter. For each kind of template parameter, we substitute the
2241 // template arguments provided thus far and any "outer" template arguments
2242 // (when the template parameter was part of a nested template) into
2243 // the default argument.
2244 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2245 if (!TTP->hasDefaultArgument()) {
2246 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2247 break;
2248 }
2249
John McCallbcd03502009-12-07 02:54:59 +00002250 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002251 Template,
2252 TemplateLoc,
2253 RAngleLoc,
2254 TTP,
2255 Converted);
2256 if (!ArgType)
2257 return true;
2258
2259 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2260 ArgType);
2261 } else if (NonTypeTemplateParmDecl *NTTP
2262 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2263 if (!NTTP->hasDefaultArgument()) {
2264 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2265 break;
2266 }
2267
2268 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2269 TemplateLoc,
2270 RAngleLoc,
2271 NTTP,
2272 Converted);
2273 if (E.isInvalid())
2274 return true;
2275
2276 Expr *Ex = E.takeAs<Expr>();
2277 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2278 } else {
2279 TemplateTemplateParmDecl *TempParm
2280 = cast<TemplateTemplateParmDecl>(*Param);
2281
2282 if (!TempParm->hasDefaultArgument()) {
2283 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2284 break;
2285 }
2286
2287 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2288 TemplateLoc,
2289 RAngleLoc,
2290 TempParm,
2291 Converted);
2292 if (Name.isNull())
2293 return true;
2294
2295 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2296 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2297 TempParm->getDefaultArgument().getTemplateNameLoc());
2298 }
2299
2300 // Introduce an instantiation record that describes where we are using
2301 // the default template argument.
2302 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2303 Converted.getFlatArguments(),
2304 Converted.flatSize(),
2305 SourceRange(TemplateLoc, RAngleLoc));
2306
2307 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002308 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002309 RAngleLoc, Converted))
2310 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002311 }
2312
2313 return Invalid;
2314}
2315
2316/// \brief Check a template argument against its corresponding
2317/// template type parameter.
2318///
2319/// This routine implements the semantics of C++ [temp.arg.type]. It
2320/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002321bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002322 TypeSourceInfo *ArgInfo) {
2323 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002324 QualType Arg = ArgInfo->getType();
2325
Douglas Gregord32e0282009-02-09 23:23:08 +00002326 // C++ [temp.arg.type]p2:
2327 // A local type, a type with no linkage, an unnamed type or a type
2328 // compounded from any of these types shall not be used as a
2329 // template-argument for a template type-parameter.
2330 //
Douglas Gregor959d5a02010-05-22 16:17:30 +00002331 // FIXME: Perform the unnamed type check.
2332 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002333 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002334 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002335 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002336 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002337 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002338 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002339 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall0ad16662009-10-29 08:12:44 +00002340 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2341 << QualType(Tag, 0) << SR;
2342 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002343 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002344 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002345 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2346 return true;
Douglas Gregor959d5a02010-05-22 16:17:30 +00002347 } else if (Arg->isVariablyModifiedType()) {
2348 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2349 << Arg;
2350 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002351 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002352 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002353 }
2354
2355 return false;
2356}
2357
Douglas Gregorccb07762009-02-11 19:52:55 +00002358/// \brief Checks whether the given template argument is the address
2359/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002360static bool
2361CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2362 NonTypeTemplateParmDecl *Param,
2363 QualType ParamType,
2364 Expr *ArgIn,
2365 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002366 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002367 Expr *Arg = ArgIn;
2368 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002369
2370 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002371 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002372 Arg = Cast->getSubExpr();
2373
2374 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002375 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002376 // A template-argument for a non-type, non-template
2377 // template-parameter shall be one of: [...]
2378 //
2379 // -- the address of an object or function with external
2380 // linkage, including function templates and function
2381 // template-ids but excluding non-static class members,
2382 // expressed as & id-expression where the & is optional if
2383 // the name refers to a function or array, or if the
2384 // corresponding template-parameter is a reference; or
2385 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002386
Douglas Gregorccb07762009-02-11 19:52:55 +00002387 // Ignore (and complain about) any excess parentheses.
2388 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2389 if (!Invalid) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002390 S.Diag(Arg->getSourceRange().getBegin(),
2391 diag::err_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002392 << Arg->getSourceRange();
2393 Invalid = true;
2394 }
2395
2396 Arg = Parens->getSubExpr();
2397 }
2398
Douglas Gregorb242683d2010-04-01 18:32:35 +00002399 bool AddressTaken = false;
2400 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002401 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002402 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002403 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002404 AddressTaken = true;
2405 AddrOpLoc = UnOp->getOperatorLoc();
2406 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002407 } else
2408 DRE = dyn_cast<DeclRefExpr>(Arg);
2409
Douglas Gregorb242683d2010-04-01 18:32:35 +00002410 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002411 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2412 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002413 S.Diag(Param->getLocation(), diag::note_template_param_here);
2414 return true;
2415 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002416
2417 // Stop checking the precise nature of the argument if it is value dependent,
2418 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002419 if (Arg->isValueDependent()) {
2420 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002421 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002422 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002423
Douglas Gregorb242683d2010-04-01 18:32:35 +00002424 if (!isa<ValueDecl>(DRE->getDecl())) {
2425 S.Diag(Arg->getSourceRange().getBegin(),
2426 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002427 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002428 S.Diag(Param->getLocation(), diag::note_template_param_here);
2429 return true;
2430 }
2431
2432 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002433
2434 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002435 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2436 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002437 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002438 S.Diag(Param->getLocation(), diag::note_template_param_here);
2439 return true;
2440 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002441
2442 // Cannot refer to non-static member functions
2443 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002444 if (!Method->isStatic()) {
2445 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002446 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002447 S.Diag(Param->getLocation(), diag::note_template_param_here);
2448 return true;
2449 }
Mike Stump11289f42009-09-09 15:08:12 +00002450
Douglas Gregorccb07762009-02-11 19:52:55 +00002451 // Functions must have external linkage.
2452 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002453 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002454 S.Diag(Arg->getSourceRange().getBegin(),
2455 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002456 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002457 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002458 << true;
2459 return true;
2460 }
2461
2462 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002463 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002464
Douglas Gregorb242683d2010-04-01 18:32:35 +00002465 // If the template parameter has pointer type, the function decays.
2466 if (ParamType->isPointerType() && !AddressTaken)
2467 ArgType = S.Context.getPointerType(Func->getType());
2468 else if (AddressTaken && ParamType->isReferenceType()) {
2469 // If we originally had an address-of operator, but the
2470 // parameter has reference type, complain and (if things look
2471 // like they will work) drop the address-of operator.
2472 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2473 ParamType.getNonReferenceType())) {
2474 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2475 << ParamType;
2476 S.Diag(Param->getLocation(), diag::note_template_param_here);
2477 return true;
2478 }
2479
2480 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2481 << ParamType
2482 << FixItHint::CreateRemoval(AddrOpLoc);
2483 S.Diag(Param->getLocation(), diag::note_template_param_here);
2484
2485 ArgType = Func->getType();
2486 }
2487 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002488 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002489 S.Diag(Arg->getSourceRange().getBegin(),
2490 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002491 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002492 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002493 << true;
2494 return true;
2495 }
2496
Douglas Gregorb242683d2010-04-01 18:32:35 +00002497 // A value of reference type is not an object.
2498 if (Var->getType()->isReferenceType()) {
2499 S.Diag(Arg->getSourceRange().getBegin(),
2500 diag::err_template_arg_reference_var)
2501 << Var->getType() << Arg->getSourceRange();
2502 S.Diag(Param->getLocation(), diag::note_template_param_here);
2503 return true;
2504 }
2505
Douglas Gregorccb07762009-02-11 19:52:55 +00002506 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002507 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002508
2509 // If the template parameter has pointer type, we must have taken
2510 // the address of this object.
2511 if (ParamType->isReferenceType()) {
2512 if (AddressTaken) {
2513 // If we originally had an address-of operator, but the
2514 // parameter has reference type, complain and (if things look
2515 // like they will work) drop the address-of operator.
2516 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2517 ParamType.getNonReferenceType())) {
2518 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2519 << ParamType;
2520 S.Diag(Param->getLocation(), diag::note_template_param_here);
2521 return true;
2522 }
2523
2524 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2525 << ParamType
2526 << FixItHint::CreateRemoval(AddrOpLoc);
2527 S.Diag(Param->getLocation(), diag::note_template_param_here);
2528
2529 ArgType = Var->getType();
2530 }
2531 } else if (!AddressTaken && ParamType->isPointerType()) {
2532 if (Var->getType()->isArrayType()) {
2533 // Array-to-pointer decay.
2534 ArgType = S.Context.getArrayDecayedType(Var->getType());
2535 } else {
2536 // If the template parameter has pointer type but the address of
2537 // this object was not taken, complain and (possibly) recover by
2538 // taking the address of the entity.
2539 ArgType = S.Context.getPointerType(Var->getType());
2540 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2541 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2542 << ParamType;
2543 S.Diag(Param->getLocation(), diag::note_template_param_here);
2544 return true;
2545 }
2546
2547 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2548 << ParamType
2549 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2550
2551 S.Diag(Param->getLocation(), diag::note_template_param_here);
2552 }
2553 }
2554 } else {
2555 // We found something else, but we don't know specifically what it is.
2556 S.Diag(Arg->getSourceRange().getBegin(),
2557 diag::err_template_arg_not_object_or_func)
2558 << Arg->getSourceRange();
2559 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2560 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002561 }
Mike Stump11289f42009-09-09 15:08:12 +00002562
Douglas Gregorb242683d2010-04-01 18:32:35 +00002563 if (ParamType->isPointerType() &&
2564 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2565 S.IsQualificationConversion(ArgType, ParamType)) {
2566 // For pointer-to-object types, qualification conversions are
2567 // permitted.
2568 } else {
2569 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2570 if (!ParamRef->getPointeeType()->isFunctionType()) {
2571 // C++ [temp.arg.nontype]p5b3:
2572 // For a non-type template-parameter of type reference to
2573 // object, no conversions apply. The type referred to by the
2574 // reference may be more cv-qualified than the (otherwise
2575 // identical) type of the template- argument. The
2576 // template-parameter is bound directly to the
2577 // template-argument, which shall be an lvalue.
2578
2579 // FIXME: Other qualifiers?
2580 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2581 unsigned ArgQuals = ArgType.getCVRQualifiers();
2582
2583 if ((ParamQuals | ArgQuals) != ParamQuals) {
2584 S.Diag(Arg->getSourceRange().getBegin(),
2585 diag::err_template_arg_ref_bind_ignores_quals)
2586 << ParamType << Arg->getType()
2587 << Arg->getSourceRange();
2588 S.Diag(Param->getLocation(), diag::note_template_param_here);
2589 return true;
2590 }
2591 }
2592 }
2593
2594 // At this point, the template argument refers to an object or
2595 // function with external linkage. We now need to check whether the
2596 // argument and parameter types are compatible.
2597 if (!S.Context.hasSameUnqualifiedType(ArgType,
2598 ParamType.getNonReferenceType())) {
2599 // We can't perform this conversion or binding.
2600 if (ParamType->isReferenceType())
2601 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2602 << ParamType << Arg->getType() << Arg->getSourceRange();
2603 else
2604 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2605 << Arg->getType() << ParamType << Arg->getSourceRange();
2606 S.Diag(Param->getLocation(), diag::note_template_param_here);
2607 return true;
2608 }
2609 }
2610
2611 // Create the template argument.
2612 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002613 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002614 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002615}
2616
2617/// \brief Checks whether the given template argument is a pointer to
2618/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002619bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2620 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002621 bool Invalid = false;
2622
2623 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002624 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002625 Arg = Cast->getSubExpr();
2626
2627 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002628 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002629 // A template-argument for a non-type, non-template
2630 // template-parameter shall be one of: [...]
2631 //
2632 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002633 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002634
2635 // Ignore (and complain about) any excess parentheses.
2636 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2637 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002638 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002639 diag::err_template_arg_extra_parens)
2640 << Arg->getSourceRange();
2641 Invalid = true;
2642 }
2643
2644 Arg = Parens->getSubExpr();
2645 }
2646
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002647 // A pointer-to-member constant written &Class::member.
2648 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002649 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2650 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2651 if (DRE && !DRE->getQualifier())
2652 DRE = 0;
2653 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002654 }
2655 // A constant of pointer-to-member type.
2656 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2657 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2658 if (VD->getType()->isMemberPointerType()) {
2659 if (isa<NonTypeTemplateParmDecl>(VD) ||
2660 (isa<VarDecl>(VD) &&
2661 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2662 if (Arg->isTypeDependent() || Arg->isValueDependent())
2663 Converted = TemplateArgument(Arg->Retain());
2664 else
2665 Converted = TemplateArgument(VD->getCanonicalDecl());
2666 return Invalid;
2667 }
2668 }
2669 }
2670
2671 DRE = 0;
2672 }
2673
Douglas Gregorccb07762009-02-11 19:52:55 +00002674 if (!DRE)
2675 return Diag(Arg->getSourceRange().getBegin(),
2676 diag::err_template_arg_not_pointer_to_member_form)
2677 << Arg->getSourceRange();
2678
2679 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2680 assert((isa<FieldDecl>(DRE->getDecl()) ||
2681 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2682 "Only non-static member pointers can make it here");
2683
2684 // Okay: this is the address of a non-static member, and therefore
2685 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002686 if (Arg->isTypeDependent() || Arg->isValueDependent())
2687 Converted = TemplateArgument(Arg->Retain());
2688 else
2689 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002690 return Invalid;
2691 }
2692
2693 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002694 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002695 diag::err_template_arg_not_pointer_to_member_form)
2696 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002697 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002698 diag::note_template_arg_refers_here);
2699 return true;
2700}
2701
Douglas Gregord32e0282009-02-09 23:23:08 +00002702/// \brief Check a template argument against its corresponding
2703/// non-type template parameter.
2704///
Douglas Gregor463421d2009-03-03 04:44:36 +00002705/// This routine implements the semantics of C++ [temp.arg.nontype].
2706/// It returns true if an error occurred, and false otherwise. \p
2707/// InstantiatedParamType is the type of the non-type template
2708/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002709///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002710/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002711bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002712 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002713 TemplateArgument &Converted,
2714 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002715 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2716
Douglas Gregor86560402009-02-10 23:36:10 +00002717 // If either the parameter has a dependent type or the argument is
2718 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002719 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2720 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002721 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002722 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002723 }
Douglas Gregor86560402009-02-10 23:36:10 +00002724
2725 // C++ [temp.arg.nontype]p5:
2726 // The following conversions are performed on each expression used
2727 // as a non-type template-argument. If a non-type
2728 // template-argument cannot be converted to the type of the
2729 // corresponding template-parameter then the program is
2730 // ill-formed.
2731 //
2732 // -- for a non-type template-parameter of integral or
2733 // enumeration type, integral promotions (4.5) and integral
2734 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002735 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002736 QualType ArgType = Arg->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +00002737 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002738 // C++ [temp.arg.nontype]p1:
2739 // A template-argument for a non-type, non-template
2740 // template-parameter shall be one of:
2741 //
2742 // -- an integral constant-expression of integral or enumeration
2743 // type; or
2744 // -- the name of a non-type template-parameter; or
2745 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002746 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00002747 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002748 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002749 diag::err_template_arg_not_integral_or_enumeral)
2750 << ArgType << Arg->getSourceRange();
2751 Diag(Param->getLocation(), diag::note_template_param_here);
2752 return true;
2753 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002754 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002755 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2756 << ArgType << Arg->getSourceRange();
2757 return true;
2758 }
2759
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002760 // From here on out, all we care about are the unqualified forms
2761 // of the parameter and argument types.
2762 ParamType = ParamType.getUnqualifiedType();
2763 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00002764
2765 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002766 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002767 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002768 } else if (CTAK == CTAK_Deduced) {
2769 // C++ [temp.deduct.type]p17:
2770 // If, in the declaration of a function template with a non-type
2771 // template-parameter, the non-type template- parameter is used
2772 // in an expression in the function parameter-list and, if the
2773 // corresponding template-argument is deduced, the
2774 // template-argument type shall match the type of the
2775 // template-parameter exactly, except that a template-argument
2776 // deduced from an array bound may be of any integral type.
2777 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2778 << ArgType << ParamType;
2779 Diag(Param->getLocation(), diag::note_template_param_here);
2780 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00002781 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2782 !ParamType->isEnumeralType()) {
2783 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002784 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002785 } else {
2786 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002787 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002788 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002789 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002790 Diag(Param->getLocation(), diag::note_template_param_here);
2791 return true;
2792 }
2793
Douglas Gregor52aba872009-03-14 00:20:21 +00002794 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002795 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002796 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002797
2798 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002799 llvm::APSInt OldValue = Value;
2800
2801 // Coerce the template argument's value to the value it will have
2802 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002803 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002804 if (Value.getBitWidth() != AllowedBits)
2805 Value.extOrTrunc(AllowedBits);
2806 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002807
2808 // Complain if an unsigned parameter received a negative value.
2809 if (IntegerType->isUnsignedIntegerType()
2810 && (OldValue.isSigned() && OldValue.isNegative())) {
2811 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2812 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2813 << Arg->getSourceRange();
2814 Diag(Param->getLocation(), diag::note_template_param_here);
2815 }
2816
2817 // Complain if we overflowed the template parameter's type.
2818 unsigned RequiredBits;
2819 if (IntegerType->isUnsignedIntegerType())
2820 RequiredBits = OldValue.getActiveBits();
2821 else if (OldValue.isUnsigned())
2822 RequiredBits = OldValue.getActiveBits() + 1;
2823 else
2824 RequiredBits = OldValue.getMinSignedBits();
2825 if (RequiredBits > AllowedBits) {
2826 Diag(Arg->getSourceRange().getBegin(),
2827 diag::warn_template_arg_too_large)
2828 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2829 << Arg->getSourceRange();
2830 Diag(Param->getLocation(), diag::note_template_param_here);
2831 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002832 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002833
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002834 // Add the value of this argument to the list of converted
2835 // arguments. We use the bitwidth and signedness of the template
2836 // parameter.
2837 if (Arg->isValueDependent()) {
2838 // The argument is value-dependent. Create a new
2839 // TemplateArgument with the converted expression.
2840 Converted = TemplateArgument(Arg);
2841 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002842 }
2843
John McCall0ad16662009-10-29 08:12:44 +00002844 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002845 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002846 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002847 return false;
2848 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002849
John McCall16df1e52010-03-30 21:47:33 +00002850 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2851
Douglas Gregorb242683d2010-04-01 18:32:35 +00002852 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2853 // from a template argument of type std::nullptr_t to a non-type
2854 // template parameter of type pointer to object, pointer to
2855 // function, or pointer-to-member, respectively.
2856 if (ArgType->isNullPtrType() &&
2857 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2858 Converted = TemplateArgument((NamedDecl *)0);
2859 return false;
2860 }
2861
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002862 // Handle pointer-to-function, reference-to-function, and
2863 // pointer-to-member-function all in (roughly) the same way.
2864 if (// -- For a non-type template-parameter of type pointer to
2865 // function, only the function-to-pointer conversion (4.3) is
2866 // applied. If the template-argument represents a set of
2867 // overloaded functions (or a pointer to such), the matching
2868 // function is selected from the set (13.4).
2869 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002870 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002871 // -- For a non-type template-parameter of type reference to
2872 // function, no conversions apply. If the template-argument
2873 // represents a set of overloaded functions, the matching
2874 // function is selected from the set (13.4).
2875 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002876 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002877 // -- For a non-type template-parameter of type pointer to
2878 // member function, no conversions apply. If the
2879 // template-argument represents a set of overloaded member
2880 // functions, the matching member function is selected from
2881 // the set (13.4).
2882 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002883 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002884 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002885
Douglas Gregor064fdb22010-04-14 23:11:21 +00002886 if (Arg->getType() == Context.OverloadTy) {
2887 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2888 true,
2889 FoundResult)) {
2890 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2891 return true;
2892
2893 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2894 ArgType = Arg->getType();
2895 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00002896 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002897 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002898
Douglas Gregorb242683d2010-04-01 18:32:35 +00002899 if (!ParamType->isMemberPointerType())
2900 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2901 ParamType,
2902 Arg, Converted);
2903
2904 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002905 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp, CastCategory(Arg));
Douglas Gregorb242683d2010-04-01 18:32:35 +00002906 } else if (!Context.hasSameUnqualifiedType(ArgType,
2907 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002908 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002909 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002910 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002911 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002912 Diag(Param->getLocation(), diag::note_template_param_here);
2913 return true;
2914 }
Mike Stump11289f42009-09-09 15:08:12 +00002915
Douglas Gregorb242683d2010-04-01 18:32:35 +00002916 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002917 }
2918
Chris Lattner696197c2009-02-20 21:37:53 +00002919 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002920 // -- for a non-type template-parameter of type pointer to
2921 // object, qualification conversions (4.4) and the
2922 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002923 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00002924 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002925 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002926
Douglas Gregorb242683d2010-04-01 18:32:35 +00002927 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2928 ParamType,
2929 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00002930 }
Mike Stump11289f42009-09-09 15:08:12 +00002931
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002932 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002933 // -- For a non-type template-parameter of type reference to
2934 // object, no conversions apply. The type referred to by the
2935 // reference may be more cv-qualified than the (otherwise
2936 // identical) type of the template-argument. The
2937 // template-parameter is bound directly to the
2938 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00002939 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002940 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002941
Douglas Gregor064fdb22010-04-14 23:11:21 +00002942 if (Arg->getType() == Context.OverloadTy) {
2943 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2944 ParamRefType->getPointeeType(),
2945 true,
2946 FoundResult)) {
2947 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2948 return true;
2949
2950 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2951 ArgType = Arg->getType();
2952 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00002953 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002954 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002955
Douglas Gregorb242683d2010-04-01 18:32:35 +00002956 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2957 ParamType,
2958 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002959 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002960
2961 // -- For a non-type template-parameter of type pointer to data
2962 // member, qualification conversions (4.4) are applied.
2963 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2964
Douglas Gregor1515f762009-02-11 18:22:40 +00002965 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002966 // Types match exactly: nothing more to do here.
2967 } else if (IsQualificationConversion(ArgType, ParamType)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002968 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp, CastCategory(Arg));
Douglas Gregor0e558532009-02-11 16:16:59 +00002969 } else {
2970 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002971 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002972 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002973 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002974 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002975 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002976 }
2977
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002978 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002979}
2980
2981/// \brief Check a template argument against its corresponding
2982/// template template parameter.
2983///
2984/// This routine implements the semantics of C++ [temp.arg.template].
2985/// It returns true if an error occurred, and false otherwise.
2986bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002987 const TemplateArgumentLoc &Arg) {
2988 TemplateName Name = Arg.getArgument().getAsTemplate();
2989 TemplateDecl *Template = Name.getAsTemplateDecl();
2990 if (!Template) {
2991 // Any dependent template name is fine.
2992 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2993 return false;
2994 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002995
2996 // C++ [temp.arg.template]p1:
2997 // A template-argument for a template template-parameter shall be
2998 // the name of a class template, expressed as id-expression. Only
2999 // primary class templates are considered when matching the
3000 // template template argument with the corresponding parameter;
3001 // partial specializations are not considered even if their
3002 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003003 //
3004 // Note that we also allow template template parameters here, which
3005 // will happen when we are dealing with, e.g., class template
3006 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003007 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003008 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003009 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003010 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003011 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003012 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003013 << Template;
3014 }
3015
3016 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3017 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003018 true,
3019 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003020 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003021}
3022
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003023/// \brief Given a non-type template argument that refers to a
3024/// declaration and the type of its corresponding non-type template
3025/// parameter, produce an expression that properly refers to that
3026/// declaration.
3027Sema::OwningExprResult
3028Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3029 QualType ParamType,
3030 SourceLocation Loc) {
3031 assert(Arg.getKind() == TemplateArgument::Declaration &&
3032 "Only declaration template arguments permitted here");
3033 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3034
3035 if (VD->getDeclContext()->isRecord() &&
3036 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3037 // If the value is a class member, we might have a pointer-to-member.
3038 // Determine whether the non-type template template parameter is of
3039 // pointer-to-member type. If so, we need to build an appropriate
3040 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3041 // would refer to the member itself.
3042 if (ParamType->isMemberPointerType()) {
3043 QualType ClassType
3044 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3045 NestedNameSpecifier *Qualifier
3046 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
3047 CXXScopeSpec SS;
3048 SS.setScopeRep(Qualifier);
3049 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
3050 VD->getType().getNonReferenceType(),
3051 Loc,
3052 &SS);
3053 if (RefExpr.isInvalid())
3054 return ExprError();
3055
3056 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003057
3058 // We might need to perform a trailing qualification conversion, since
3059 // the element type on the parameter could be more qualified than the
3060 // element type in the expression we constructed.
3061 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3062 ParamType.getUnqualifiedType())) {
3063 Expr *RefE = RefExpr.takeAs<Expr>();
3064 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(),
3065 CastExpr::CK_NoOp);
3066 RefExpr = Owned(RefE);
3067 }
3068
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003069 assert(!RefExpr.isInvalid() &&
3070 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003071 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003072 return move(RefExpr);
3073 }
3074 }
3075
3076 QualType T = VD->getType().getNonReferenceType();
3077 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003078 // When the non-type template parameter is a pointer, take the
3079 // address of the declaration.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003080 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3081 if (RefExpr.isInvalid())
3082 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003083
3084 if (T->isFunctionType() || T->isArrayType()) {
3085 // Decay functions and arrays.
3086 Expr *RefE = (Expr *)RefExpr.get();
3087 DefaultFunctionArrayConversion(RefE);
3088 if (RefE != RefExpr.get()) {
3089 RefExpr.release();
3090 RefExpr = Owned(RefE);
3091 }
3092
3093 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003094 }
3095
Douglas Gregorb242683d2010-04-01 18:32:35 +00003096 // Take the address of everything else
3097 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003098 }
3099
3100 // If the non-type template parameter has reference type, qualify the
3101 // resulting declaration reference with the extra qualifiers on the
3102 // type that the reference refers to.
3103 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3104 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3105
3106 return BuildDeclRefExpr(VD, T, Loc);
3107}
3108
3109/// \brief Construct a new expression that refers to the given
3110/// integral template argument with the given source-location
3111/// information.
3112///
3113/// This routine takes care of the mapping from an integral template
3114/// argument (which may have any integral type) to the appropriate
3115/// literal value.
3116Sema::OwningExprResult
3117Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3118 SourceLocation Loc) {
3119 assert(Arg.getKind() == TemplateArgument::Integral &&
3120 "Operation is only value for integral template arguments");
3121 QualType T = Arg.getIntegralType();
3122 if (T->isCharType() || T->isWideCharType())
3123 return Owned(new (Context) CharacterLiteral(
3124 Arg.getAsIntegral()->getZExtValue(),
3125 T->isWideCharType(),
3126 T,
3127 Loc));
3128 if (T->isBooleanType())
3129 return Owned(new (Context) CXXBoolLiteralExpr(
3130 Arg.getAsIntegral()->getBoolValue(),
3131 T,
3132 Loc));
3133
3134 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3135}
3136
3137
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003138/// \brief Determine whether the given template parameter lists are
3139/// equivalent.
3140///
Mike Stump11289f42009-09-09 15:08:12 +00003141/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003142/// source code as part of a new template declaration.
3143///
3144/// \param Old The old template parameter list, typically found via
3145/// name lookup of the template declared with this template parameter
3146/// list.
3147///
3148/// \param Complain If true, this routine will produce a diagnostic if
3149/// the template parameter lists are not equivalent.
3150///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003151/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003152///
3153/// \param TemplateArgLoc If this source location is valid, then we
3154/// are actually checking the template parameter list of a template
3155/// argument (New) against the template parameter list of its
3156/// corresponding template template parameter (Old). We produce
3157/// slightly different diagnostics in this scenario.
3158///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003159/// \returns True if the template parameter lists are equal, false
3160/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003161bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003162Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3163 TemplateParameterList *Old,
3164 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003165 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003166 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003167 if (Old->size() != New->size()) {
3168 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003169 unsigned NextDiag = diag::err_template_param_list_different_arity;
3170 if (TemplateArgLoc.isValid()) {
3171 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3172 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003173 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003174 Diag(New->getTemplateLoc(), NextDiag)
3175 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003176 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003177 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003178 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003179 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003180 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3181 }
3182
3183 return false;
3184 }
3185
3186 for (TemplateParameterList::iterator OldParm = Old->begin(),
3187 OldParmEnd = Old->end(), NewParm = New->begin();
3188 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3189 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003190 if (Complain) {
3191 unsigned NextDiag = diag::err_template_param_different_kind;
3192 if (TemplateArgLoc.isValid()) {
3193 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3194 NextDiag = diag::note_template_param_different_kind;
3195 }
3196 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003197 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003198 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003199 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003200 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003201 return false;
3202 }
3203
Douglas Gregor2e87ca22010-06-04 08:34:32 +00003204 if (TemplateTypeParmDecl *OldTTP
3205 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3206 // Template type parameters are equivalent if either both are template
3207 // type parameter packs or neither are (since we know we're at the same
3208 // index).
3209 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3210 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3211 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3212 // allow one to match a template parameter pack in the template
3213 // parameter list of a template template parameter to one or more
3214 // template parameters in the template parameter list of the
3215 // corresponding template template argument.
3216 if (Complain) {
3217 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3218 if (TemplateArgLoc.isValid()) {
3219 Diag(TemplateArgLoc,
3220 diag::err_template_arg_template_params_mismatch);
3221 NextDiag = diag::note_template_parameter_pack_non_pack;
3222 }
3223 Diag(NewTTP->getLocation(), NextDiag)
3224 << 0 << NewTTP->isParameterPack();
3225 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3226 << 0 << OldTTP->isParameterPack();
3227 }
3228 return false;
3229 }
Mike Stump11289f42009-09-09 15:08:12 +00003230 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003231 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3232 // The types of non-type template parameters must agree.
3233 NonTypeTemplateParmDecl *NewNTTP
3234 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003235
3236 // If we are matching a template template argument to a template
3237 // template parameter and one of the non-type template parameter types
3238 // is dependent, then we must wait until template instantiation time
3239 // to actually compare the arguments.
3240 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3241 (OldNTTP->getType()->isDependentType() ||
3242 NewNTTP->getType()->isDependentType()))
3243 continue;
3244
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003245 if (Context.getCanonicalType(OldNTTP->getType()) !=
3246 Context.getCanonicalType(NewNTTP->getType())) {
3247 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003248 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3249 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003250 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003251 diag::err_template_arg_template_params_mismatch);
3252 NextDiag = diag::note_template_nontype_parm_different_type;
3253 }
3254 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003255 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003256 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003257 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003258 diag::note_template_nontype_parm_prev_declaration)
3259 << OldNTTP->getType();
3260 }
3261 return false;
3262 }
3263 } else {
3264 // The template parameter lists of template template
3265 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003266 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003267 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003268 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003269 = cast<TemplateTemplateParmDecl>(*OldParm);
3270 TemplateTemplateParmDecl *NewTTP
3271 = cast<TemplateTemplateParmDecl>(*NewParm);
3272 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3273 OldTTP->getTemplateParameters(),
3274 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003275 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003276 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003277 return false;
3278 }
3279 }
3280
3281 return true;
3282}
3283
3284/// \brief Check whether a template can be declared within this scope.
3285///
3286/// If the template declaration is valid in this scope, returns
3287/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003288bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003289Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003290 // Find the nearest enclosing declaration scope.
3291 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3292 (S->getFlags() & Scope::TemplateParamScope) != 0)
3293 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003294
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003295 // C++ [temp]p2:
3296 // A template-declaration can appear only as a namespace scope or
3297 // class scope declaration.
3298 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003299 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3300 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003301 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003302 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003303
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003304 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003305 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003306
3307 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3308 return false;
3309
Mike Stump11289f42009-09-09 15:08:12 +00003310 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003311 diag::err_template_outside_namespace_or_class_scope)
3312 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003313}
Douglas Gregor67a65642009-02-17 23:15:12 +00003314
Douglas Gregor54888652009-10-07 00:13:32 +00003315/// \brief Determine what kind of template specialization the given declaration
3316/// is.
3317static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3318 if (!D)
3319 return TSK_Undeclared;
3320
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003321 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3322 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003323 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3324 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003325 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3326 return Var->getTemplateSpecializationKind();
3327
Douglas Gregor54888652009-10-07 00:13:32 +00003328 return TSK_Undeclared;
3329}
3330
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003331/// \brief Check whether a specialization is well-formed in the current
3332/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003333///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003334/// This routine determines whether a template specialization can be declared
3335/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003336///
3337/// \param S the semantic analysis object for which this check is being
3338/// performed.
3339///
3340/// \param Specialized the entity being specialized or instantiated, which
3341/// may be a kind of template (class template, function template, etc.) or
3342/// a member of a class template (member function, static data member,
3343/// member class).
3344///
3345/// \param PrevDecl the previous declaration of this entity, if any.
3346///
3347/// \param Loc the location of the explicit specialization or instantiation of
3348/// this entity.
3349///
3350/// \param IsPartialSpecialization whether this is a partial specialization of
3351/// a class template.
3352///
Douglas Gregor54888652009-10-07 00:13:32 +00003353/// \returns true if there was an error that we cannot recover from, false
3354/// otherwise.
3355static bool CheckTemplateSpecializationScope(Sema &S,
3356 NamedDecl *Specialized,
3357 NamedDecl *PrevDecl,
3358 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003359 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003360 // Keep these "kind" numbers in sync with the %select statements in the
3361 // various diagnostics emitted by this routine.
3362 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003363 bool isTemplateSpecialization = false;
3364 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003365 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003366 isTemplateSpecialization = true;
3367 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003368 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003369 isTemplateSpecialization = true;
3370 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003371 EntityKind = 3;
3372 else if (isa<VarDecl>(Specialized))
3373 EntityKind = 4;
3374 else if (isa<RecordDecl>(Specialized))
3375 EntityKind = 5;
3376 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003377 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3378 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003379 return true;
3380 }
3381
Douglas Gregorf47b9112009-02-25 22:02:03 +00003382 // C++ [temp.expl.spec]p2:
3383 // An explicit specialization shall be declared in the namespace
3384 // of which the template is a member, or, for member templates, in
3385 // the namespace of which the enclosing class or enclosing class
3386 // template is a member. An explicit specialization of a member
3387 // function, member class or static data member of a class
3388 // template shall be declared in the namespace of which the class
3389 // template is a member. Such a declaration may also be a
3390 // definition. If the declaration is not a definition, the
3391 // specialization may be defined later in the name- space in which
3392 // the explicit specialization was declared, or in a namespace
3393 // that encloses the one in which the explicit specialization was
3394 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003395 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3396 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003397 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003398 return true;
3399 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003400
Douglas Gregor40fb7442009-10-07 17:30:37 +00003401 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3402 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003403 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003404 return true;
3405 }
3406
Douglas Gregore4b05162009-10-07 17:21:34 +00003407 // C++ [temp.class.spec]p6:
3408 // A class template partial specialization may be declared or redeclared
3409 // in any namespace scope in which its definition may be defined (14.5.1
3410 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003411 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003412 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003413 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003414 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003415 if ((!PrevDecl ||
3416 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3417 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3418 // There is no prior declaration of this entity, so this
3419 // specialization must be in the same context as the template
3420 // itself.
3421 if (!DC->Equals(SpecializedContext)) {
3422 if (isa<TranslationUnitDecl>(SpecializedContext))
3423 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3424 << EntityKind << Specialized;
3425 else if (isa<NamespaceDecl>(SpecializedContext))
3426 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3427 << EntityKind << Specialized
3428 << cast<NamedDecl>(SpecializedContext);
3429
3430 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3431 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003432 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003433 }
Douglas Gregor54888652009-10-07 00:13:32 +00003434
3435 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003436 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003437 // Note that HandleDeclarator() performs this check for explicit
3438 // specializations of function templates, static data members, and member
3439 // functions, so we skip the check here for those kinds of entities.
3440 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003441 // Should we refactor that check, so that it occurs later?
3442 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003443 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3444 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003445 if (isa<TranslationUnitDecl>(SpecializedContext))
3446 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3447 << EntityKind << Specialized;
3448 else if (isa<NamespaceDecl>(SpecializedContext))
3449 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3450 << EntityKind << Specialized
3451 << cast<NamedDecl>(SpecializedContext);
3452
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003453 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003454 }
Douglas Gregor54888652009-10-07 00:13:32 +00003455
3456 // FIXME: check for specialization-after-instantiation errors and such.
3457
Douglas Gregorf47b9112009-02-25 22:02:03 +00003458 return false;
3459}
Douglas Gregor54888652009-10-07 00:13:32 +00003460
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003461/// \brief Check the non-type template arguments of a class template
3462/// partial specialization according to C++ [temp.class.spec]p9.
3463///
Douglas Gregor09a30232009-06-12 22:08:06 +00003464/// \param TemplateParams the template parameters of the primary class
3465/// template.
3466///
3467/// \param TemplateArg the template arguments of the class template
3468/// partial specialization.
3469///
3470/// \param MirrorsPrimaryTemplate will be set true if the class
3471/// template partial specialization arguments are identical to the
3472/// implicit template arguments of the primary template. This is not
3473/// necessarily an error (C++0x), and it is left to the caller to diagnose
3474/// this condition when it is an error.
3475///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003476/// \returns true if there was an error, false otherwise.
3477bool Sema::CheckClassTemplatePartialSpecializationArgs(
3478 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003479 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003480 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003481 // FIXME: the interface to this function will have to change to
3482 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003483 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003484
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003485 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003486
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003487 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003488 // Determine whether the template argument list of the partial
3489 // specialization is identical to the implicit argument list of
3490 // the primary template. The caller may need to diagnostic this as
3491 // an error per C++ [temp.class.spec]p9b3.
3492 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003493 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003494 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3495 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003496 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003497 MirrorsPrimaryTemplate = false;
3498 } else if (TemplateTemplateParmDecl *TTP
3499 = dyn_cast<TemplateTemplateParmDecl>(
3500 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003501 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003502 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003503 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003504 if (!ArgDecl ||
3505 ArgDecl->getIndex() != TTP->getIndex() ||
3506 ArgDecl->getDepth() != TTP->getDepth())
3507 MirrorsPrimaryTemplate = false;
3508 }
3509 }
3510
Mike Stump11289f42009-09-09 15:08:12 +00003511 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003512 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003513 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003514 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003515 }
3516
Anders Carlsson40c1d492009-06-13 18:20:51 +00003517 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003518 if (!ArgExpr) {
3519 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003520 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003521 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003522
3523 // C++ [temp.class.spec]p8:
3524 // A non-type argument is non-specialized if it is the name of a
3525 // non-type parameter. All other non-type arguments are
3526 // specialized.
3527 //
3528 // Below, we check the two conditions that only apply to
3529 // specialized non-type arguments, so skip any non-specialized
3530 // arguments.
3531 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003532 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003533 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003534 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003535 (Param->getIndex() != NTTP->getIndex() ||
3536 Param->getDepth() != NTTP->getDepth()))
3537 MirrorsPrimaryTemplate = false;
3538
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003539 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003540 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003541
3542 // C++ [temp.class.spec]p9:
3543 // Within the argument list of a class template partial
3544 // specialization, the following restrictions apply:
3545 // -- A partially specialized non-type argument expression
3546 // shall not involve a template parameter of the partial
3547 // specialization except when the argument expression is a
3548 // simple identifier.
3549 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003550 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003551 diag::err_dependent_non_type_arg_in_partial_spec)
3552 << ArgExpr->getSourceRange();
3553 return true;
3554 }
3555
3556 // -- The type of a template parameter corresponding to a
3557 // specialized non-type argument shall not be dependent on a
3558 // parameter of the specialization.
3559 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003560 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003561 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3562 << Param->getType()
3563 << ArgExpr->getSourceRange();
3564 Diag(Param->getLocation(), diag::note_template_param_here);
3565 return true;
3566 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003567
3568 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003569 }
3570
3571 return false;
3572}
3573
Douglas Gregorc854c662010-02-26 06:03:23 +00003574/// \brief Retrieve the previous declaration of the given declaration.
3575static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3576 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3577 return VD->getPreviousDeclaration();
3578 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3579 return FD->getPreviousDeclaration();
3580 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3581 return TD->getPreviousDeclaration();
3582 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3583 return TD->getPreviousDeclaration();
3584 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3585 return FTD->getPreviousDeclaration();
3586 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3587 return CTD->getPreviousDeclaration();
3588 return 0;
3589}
3590
Douglas Gregorc08f4892009-03-25 00:13:59 +00003591Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003592Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3593 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003594 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003595 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003596 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003597 SourceLocation TemplateNameLoc,
3598 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003599 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003600 SourceLocation RAngleLoc,
3601 AttributeList *Attr,
3602 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003603 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003604
Douglas Gregor67a65642009-02-17 23:15:12 +00003605 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003606 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003607 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003608 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3609
3610 if (!ClassTemplate) {
3611 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3612 << (Name.getAsTemplateDecl() &&
3613 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3614 return true;
3615 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003616
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003617 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003618 bool isPartialSpecialization = false;
3619
Douglas Gregorf47b9112009-02-25 22:02:03 +00003620 // Check the validity of the template headers that introduce this
3621 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003622 // FIXME: We probably shouldn't complain about these headers for
3623 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003624 bool Invalid = false;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003625 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003626 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3627 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003628 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003629 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003630 isExplicitSpecialization,
3631 Invalid);
3632 if (Invalid)
3633 return true;
3634
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003635 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3636 if (TemplateParams)
3637 --NumMatchedTemplateParamLists;
3638
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003639 if (TemplateParams && TemplateParams->size() > 0) {
3640 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003641
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003642 // C++ [temp.class.spec]p10:
3643 // The template parameter list of a specialization shall not
3644 // contain default template argument values.
3645 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3646 Decl *Param = TemplateParams->getParam(I);
3647 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3648 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003649 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003650 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003651 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003652 }
3653 } else if (NonTypeTemplateParmDecl *NTTP
3654 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3655 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003656 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003657 diag::err_default_arg_in_partial_spec)
3658 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003659 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003660 }
3661 } else {
3662 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003663 if (TTP->hasDefaultArgument()) {
3664 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003665 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003666 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003667 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00003668 }
3669 }
3670 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003671 } else if (TemplateParams) {
3672 if (TUK == TUK_Friend)
3673 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003674 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003675 SourceRange(TemplateParams->getTemplateLoc(),
3676 TemplateParams->getRAngleLoc()))
3677 << SourceRange(LAngleLoc, RAngleLoc);
3678 else
3679 isExplicitSpecialization = true;
3680 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003681 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003682 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003683 isExplicitSpecialization = true;
3684 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003685
Douglas Gregor67a65642009-02-17 23:15:12 +00003686 // Check that the specialization uses the same tag kind as the
3687 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003688 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3689 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00003690 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003691 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003692 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003693 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003694 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003695 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003696 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003697 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003698 diag::note_previous_use);
3699 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3700 }
3701
Douglas Gregorc40290e2009-03-09 23:48:35 +00003702 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003703 TemplateArgumentListInfo TemplateArgs;
3704 TemplateArgs.setLAngleLoc(LAngleLoc);
3705 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003706 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003707
Douglas Gregor67a65642009-02-17 23:15:12 +00003708 // Check that the template argument list is well-formed for this
3709 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003710 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3711 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003712 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3713 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003714 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003715
Mike Stump11289f42009-09-09 15:08:12 +00003716 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003717 ClassTemplate->getTemplateParameters()->size()) &&
3718 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003719
Douglas Gregor2373c592009-05-31 09:31:02 +00003720 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003721 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00003722 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003723 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003724 if (CheckClassTemplatePartialSpecializationArgs(
3725 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003726 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003727 return true;
3728
Douglas Gregor09a30232009-06-12 22:08:06 +00003729 if (MirrorsPrimaryTemplate) {
3730 // C++ [temp.class.spec]p9b3:
3731 //
Mike Stump11289f42009-09-09 15:08:12 +00003732 // -- The argument list of the specialization shall not be identical
3733 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003734 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003735 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003736 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003737 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003738 ClassTemplate->getIdentifier(),
3739 TemplateNameLoc,
3740 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003741 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003742 AS_none);
3743 }
3744
Douglas Gregor2208a292009-09-26 20:57:03 +00003745 // FIXME: Diagnose friend partial specializations
3746
Douglas Gregor92354b62010-02-09 00:37:32 +00003747 if (!Name.isDependent() &&
3748 !TemplateSpecializationType::anyDependentTemplateArguments(
3749 TemplateArgs.getArgumentArray(),
3750 TemplateArgs.size())) {
3751 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3752 << ClassTemplate->getDeclName();
3753 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00003754 }
3755 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003756
Douglas Gregor67a65642009-02-17 23:15:12 +00003757 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003758 ClassTemplateSpecializationDecl *PrevDecl = 0;
3759
3760 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003761 // FIXME: Template parameter list matters, too
Douglas Gregor2373c592009-05-31 09:31:02 +00003762 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003763 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
3764 Converted.flatSize(),
3765 InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00003766 else
3767 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003768 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
3769 Converted.flatSize(), InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003770
3771 ClassTemplateSpecializationDecl *Specialization = 0;
3772
Douglas Gregorf47b9112009-02-25 22:02:03 +00003773 // Check whether we can declare a class template specialization in
3774 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003775 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003776 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003777 TemplateNameLoc,
3778 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003779 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003780
Douglas Gregor15301382009-07-30 17:40:51 +00003781 // The canonical type
3782 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003783 if (PrevDecl &&
3784 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003785 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003786 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003787 // arguments was referenced but not declared, or we're only
3788 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003789 // declaration node as our own, updating its source location to
3790 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003791 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003792 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003793 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003794 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003795 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003796 // Build the canonical type that describes the converted template
3797 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003798 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3799 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003800 Converted.getFlatArguments(),
3801 Converted.flatSize());
3802
Douglas Gregor2373c592009-05-31 09:31:02 +00003803 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003804 ClassTemplatePartialSpecializationDecl *PrevPartial
3805 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00003806 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003807 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump11289f42009-09-09 15:08:12 +00003808 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00003809 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00003810 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003811 TemplateNameLoc,
3812 TemplateParams,
3813 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003814 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003815 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003816 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00003817 PrevPartial,
3818 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00003819 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00003820 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003821 Partial->setTemplateParameterListsInfo(Context,
3822 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003823 (TemplateParameterList**) TemplateParameterLists.release());
3824 }
Douglas Gregor2373c592009-05-31 09:31:02 +00003825
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003826 if (!PrevPartial)
3827 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00003828 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003829
Douglas Gregor21610382009-10-29 00:04:11 +00003830 // If we are providing an explicit specialization of a member class
3831 // template specialization, make a note of that.
3832 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3833 PrevPartial->setMemberSpecialization();
3834
Douglas Gregor91772d12009-06-13 00:26:55 +00003835 // Check that all of the template parameters of the class template
3836 // partial specialization are deducible from the template
3837 // arguments. If not, this class template partial specialization
3838 // will never be used.
3839 llvm::SmallVector<bool, 8> DeducibleParams;
3840 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003841 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003842 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003843 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003844 unsigned NumNonDeducible = 0;
3845 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3846 if (!DeducibleParams[I])
3847 ++NumNonDeducible;
3848
3849 if (NumNonDeducible) {
3850 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3851 << (NumNonDeducible > 1)
3852 << SourceRange(TemplateNameLoc, RAngleLoc);
3853 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3854 if (!DeducibleParams[I]) {
3855 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3856 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003857 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003858 diag::note_partial_spec_unused_parameter)
3859 << Param->getDeclName();
3860 else
Mike Stump11289f42009-09-09 15:08:12 +00003861 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003862 diag::note_partial_spec_unused_parameter)
3863 << std::string("<anonymous>");
3864 }
3865 }
3866 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003867 } else {
3868 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003869 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003870 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00003871 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00003872 ClassTemplate->getDeclContext(),
3873 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003874 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003875 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003876 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00003877 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00003878 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003879 Specialization->setTemplateParameterListsInfo(Context,
3880 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003881 (TemplateParameterList**) TemplateParameterLists.release());
3882 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003883
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003884 if (!PrevDecl)
3885 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00003886
3887 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003888 }
3889
Douglas Gregor06db9f52009-10-12 20:18:28 +00003890 // C++ [temp.expl.spec]p6:
3891 // If a template, a member template or the member of a class template is
3892 // explicitly specialized then that specialization shall be declared
3893 // before the first use of that specialization that would cause an implicit
3894 // instantiation to take place, in every translation unit in which such a
3895 // use occurs; no diagnostic is required.
3896 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003897 bool Okay = false;
3898 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3899 // Is there any previous explicit specialization declaration?
3900 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3901 Okay = true;
3902 break;
3903 }
3904 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003905
Douglas Gregorc854c662010-02-26 06:03:23 +00003906 if (!Okay) {
3907 SourceRange Range(TemplateNameLoc, RAngleLoc);
3908 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3909 << Context.getTypeDeclType(Specialization) << Range;
3910
3911 Diag(PrevDecl->getPointOfInstantiation(),
3912 diag::note_instantiation_required_here)
3913 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003914 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003915 return true;
3916 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003917 }
3918
Douglas Gregor2208a292009-09-26 20:57:03 +00003919 // If this is not a friend, note that this is an explicit specialization.
3920 if (TUK != TUK_Friend)
3921 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003922
3923 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003924 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003925 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003926 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003927 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003928 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003929 Diag(Def->getLocation(), diag::note_previous_definition);
3930 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003931 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003932 }
3933 }
3934
Douglas Gregord56a91e2009-02-26 22:19:44 +00003935 // Build the fully-sugared type for this class template
3936 // specialization as the user wrote in the specialization
3937 // itself. This means that we'll pretty-print the type retrieved
3938 // from the specialization's declaration the way that the user
3939 // actually wrote the specialization, rather than formatting the
3940 // name based on the "canonical" representation used to store the
3941 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003942 TypeSourceInfo *WrittenTy
3943 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3944 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00003945 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003946 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregord890b732010-07-06 18:33:12 +00003947 if (TemplateParams)
3948 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnara8075c852010-06-12 07:44:57 +00003949 }
Douglas Gregorc40290e2009-03-09 23:48:35 +00003950 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003951
Douglas Gregor1e249f82009-02-25 22:18:32 +00003952 // C++ [temp.expl.spec]p9:
3953 // A template explicit specialization is in the scope of the
3954 // namespace in which the template was defined.
3955 //
3956 // We actually implement this paragraph where we set the semantic
3957 // context (in the creation of the ClassTemplateSpecializationDecl),
3958 // but we also maintain the lexical context where the actual
3959 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003960 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003961
Douglas Gregor67a65642009-02-17 23:15:12 +00003962 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003963 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003964 Specialization->startDefinition();
3965
Douglas Gregor2208a292009-09-26 20:57:03 +00003966 if (TUK == TUK_Friend) {
3967 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3968 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00003969 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00003970 /*FIXME:*/KWLoc);
3971 Friend->setAccess(AS_public);
3972 CurContext->addDecl(Friend);
3973 } else {
3974 // Add the specialization into its lexical context, so that it can
3975 // be seen when iterating through the list of declarations in that
3976 // context. However, specializations are not found by name lookup.
3977 CurContext->addDecl(Specialization);
3978 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003979 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003980}
Douglas Gregor333489b2009-03-27 23:10:48 +00003981
Mike Stump11289f42009-09-09 15:08:12 +00003982Sema::DeclPtrTy
3983Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003984 MultiTemplateParamsArg TemplateParameterLists,
3985 Declarator &D) {
3986 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3987}
3988
Mike Stump11289f42009-09-09 15:08:12 +00003989Sema::DeclPtrTy
3990Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003991 MultiTemplateParamsArg TemplateParameterLists,
3992 Declarator &D) {
3993 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3994 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3995 "Not a function declarator!");
3996 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003997
Douglas Gregor17a7c122009-06-24 00:54:41 +00003998 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003999 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004000 }
Mike Stump11289f42009-09-09 15:08:12 +00004001
Douglas Gregor17a7c122009-06-24 00:54:41 +00004002 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004003
4004 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004005 move(TemplateParameterLists),
4006 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004007 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00004008 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00004009 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004010 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00004011 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
4012 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004013 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00004014}
4015
John McCall4f7ced62010-02-11 01:33:53 +00004016/// \brief Strips various properties off an implicit instantiation
4017/// that has just been explicitly specialized.
4018static void StripImplicitInstantiation(NamedDecl *D) {
4019 D->invalidateAttrs();
4020
4021 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4022 FD->setInlineSpecified(false);
4023 }
4024}
4025
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004026/// \brief Diagnose cases where we have an explicit template specialization
4027/// before/after an explicit template instantiation, producing diagnostics
4028/// for those cases where they are required and determining whether the
4029/// new specialization/instantiation will have any effect.
4030///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004031/// \param NewLoc the location of the new explicit specialization or
4032/// instantiation.
4033///
4034/// \param NewTSK the kind of the new explicit specialization or instantiation.
4035///
4036/// \param PrevDecl the previous declaration of the entity.
4037///
4038/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4039///
4040/// \param PrevPointOfInstantiation if valid, indicates where the previus
4041/// declaration was instantiated (either implicitly or explicitly).
4042///
Abramo Bagnara8075c852010-06-12 07:44:57 +00004043/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004044/// specialization or instantiation has no effect and should be ignored.
4045///
4046/// \returns true if there was an error that should prevent the introduction of
4047/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004048bool
4049Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4050 TemplateSpecializationKind NewTSK,
4051 NamedDecl *PrevDecl,
4052 TemplateSpecializationKind PrevTSK,
4053 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004054 bool &HasNoEffect) {
4055 HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004056
4057 switch (NewTSK) {
4058 case TSK_Undeclared:
4059 case TSK_ImplicitInstantiation:
4060 assert(false && "Don't check implicit instantiations here");
4061 return false;
4062
4063 case TSK_ExplicitSpecialization:
4064 switch (PrevTSK) {
4065 case TSK_Undeclared:
4066 case TSK_ExplicitSpecialization:
4067 // Okay, we're just specializing something that is either already
4068 // explicitly specialized or has merely been mentioned without any
4069 // instantiation.
4070 return false;
4071
4072 case TSK_ImplicitInstantiation:
4073 if (PrevPointOfInstantiation.isInvalid()) {
4074 // The declaration itself has not actually been instantiated, so it is
4075 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004076 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004077 return false;
4078 }
4079 // Fall through
4080
4081 case TSK_ExplicitInstantiationDeclaration:
4082 case TSK_ExplicitInstantiationDefinition:
4083 assert((PrevTSK == TSK_ImplicitInstantiation ||
4084 PrevPointOfInstantiation.isValid()) &&
4085 "Explicit instantiation without point of instantiation?");
4086
4087 // C++ [temp.expl.spec]p6:
4088 // If a template, a member template or the member of a class template
4089 // is explicitly specialized then that specialization shall be declared
4090 // before the first use of that specialization that would cause an
4091 // implicit instantiation to take place, in every translation unit in
4092 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004093 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4094 // Is there any previous explicit specialization declaration?
4095 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4096 return false;
4097 }
4098
Douglas Gregor1d957a32009-10-27 18:42:08 +00004099 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004100 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004101 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004102 << (PrevTSK != TSK_ImplicitInstantiation);
4103
4104 return true;
4105 }
4106 break;
4107
4108 case TSK_ExplicitInstantiationDeclaration:
4109 switch (PrevTSK) {
4110 case TSK_ExplicitInstantiationDeclaration:
4111 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00004112 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004113 return false;
4114
4115 case TSK_Undeclared:
4116 case TSK_ImplicitInstantiation:
4117 // We're explicitly instantiating something that may have already been
4118 // implicitly instantiated; that's fine.
4119 return false;
4120
4121 case TSK_ExplicitSpecialization:
4122 // C++0x [temp.explicit]p4:
4123 // For a given set of template parameters, if an explicit instantiation
4124 // of a template appears after a declaration of an explicit
4125 // specialization for that template, the explicit instantiation has no
4126 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00004127 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004128 return false;
4129
4130 case TSK_ExplicitInstantiationDefinition:
4131 // C++0x [temp.explicit]p10:
4132 // If an entity is the subject of both an explicit instantiation
4133 // declaration and an explicit instantiation definition in the same
4134 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004135 Diag(NewLoc,
4136 diag::err_explicit_instantiation_declaration_after_definition);
4137 Diag(PrevPointOfInstantiation,
4138 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004139 assert(PrevPointOfInstantiation.isValid() &&
4140 "Explicit instantiation without point of instantiation?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00004141 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004142 return false;
4143 }
4144 break;
4145
4146 case TSK_ExplicitInstantiationDefinition:
4147 switch (PrevTSK) {
4148 case TSK_Undeclared:
4149 case TSK_ImplicitInstantiation:
4150 // We're explicitly instantiating something that may have already been
4151 // implicitly instantiated; that's fine.
4152 return false;
4153
4154 case TSK_ExplicitSpecialization:
4155 // C++ DR 259, C++0x [temp.explicit]p4:
4156 // For a given set of template parameters, if an explicit
4157 // instantiation of a template appears after a declaration of
4158 // an explicit specialization for that template, the explicit
4159 // instantiation has no effect.
4160 //
4161 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004162 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004163 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004164 if (!getLangOptions().CPlusPlus0x) {
4165 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004166 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004167 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004168 diag::note_previous_template_specialization);
4169 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004170 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004171 return false;
4172
4173 case TSK_ExplicitInstantiationDeclaration:
4174 // We're explicity instantiating a definition for something for which we
4175 // were previously asked to suppress instantiations. That's fine.
4176 return false;
4177
4178 case TSK_ExplicitInstantiationDefinition:
4179 // C++0x [temp.spec]p5:
4180 // For a given template and a given set of template-arguments,
4181 // - an explicit instantiation definition shall appear at most once
4182 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004183 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004184 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004185 Diag(PrevPointOfInstantiation,
4186 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004187 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004188 return false;
4189 }
4190 break;
4191 }
4192
4193 assert(false && "Missing specialization/instantiation case?");
4194
4195 return false;
4196}
4197
John McCallb9c78482010-04-08 09:05:18 +00004198/// \brief Perform semantic analysis for the given dependent function
4199/// template specialization. The only possible way to get a dependent
4200/// function template specialization is with a friend declaration,
4201/// like so:
4202///
4203/// template <class T> void foo(T);
4204/// template <class T> class A {
4205/// friend void foo<>(T);
4206/// };
4207///
4208/// There really isn't any useful analysis we can do here, so we
4209/// just store the information.
4210bool
4211Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4212 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4213 LookupResult &Previous) {
4214 // Remove anything from Previous that isn't a function template in
4215 // the correct context.
4216 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4217 LookupResult::Filter F = Previous.makeFilter();
4218 while (F.hasNext()) {
4219 NamedDecl *D = F.next()->getUnderlyingDecl();
4220 if (!isa<FunctionTemplateDecl>(D) ||
4221 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4222 F.erase();
4223 }
4224 F.done();
4225
4226 // Should this be diagnosed here?
4227 if (Previous.empty()) return true;
4228
4229 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4230 ExplicitTemplateArgs);
4231 return false;
4232}
4233
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004234/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004235/// specialization.
4236///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004237/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004238/// explicit function template specialization. On successful completion,
4239/// the function declaration \p FD will become a function template
4240/// specialization.
4241///
4242/// \param FD the function declaration, which will be updated to become a
4243/// function template specialization.
4244///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004245/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4246/// if any. Note that this may be valid info even when 0 arguments are
4247/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4248/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004249///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004250/// \param PrevDecl the set of declarations that may be specialized by
4251/// this function specialization.
4252bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004253Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004254 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004255 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004256 // The set of function template specializations that could match this
4257 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004258 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004259
4260 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00004261 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4262 I != E; ++I) {
4263 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4264 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004265 // Only consider templates found within the same semantic lookup scope as
4266 // FD.
4267 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4268 continue;
4269
4270 // C++ [temp.expl.spec]p11:
4271 // A trailing template-argument can be left unspecified in the
4272 // template-id naming an explicit function template specialization
4273 // provided it can be deduced from the function argument type.
4274 // Perform template argument deduction to determine whether we may be
4275 // specializing this template.
4276 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004277 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004278 FunctionDecl *Specialization = 0;
4279 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004280 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004281 FD->getType(),
4282 Specialization,
4283 Info)) {
4284 // FIXME: Template argument deduction failed; record why it failed, so
4285 // that we can provide nifty diagnostics.
4286 (void)TDK;
4287 continue;
4288 }
4289
4290 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004291 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004292 }
4293 }
4294
Douglas Gregor5de279c2009-09-26 03:41:46 +00004295 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004296 UnresolvedSetIterator Result
4297 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4298 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004299 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004300 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004301 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004302 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004303 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004304 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004305 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004306
4307 // Ignore access information; it doesn't figure into redeclaration checking.
4308 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004309 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004310
4311 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004312 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004313
4314 // If this is a friend declaration, then we're not really declaring
4315 // an explicit specialization.
4316 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004317
Douglas Gregor54888652009-10-07 00:13:32 +00004318 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004319 if (!isFriend &&
4320 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004321 Specialization->getPrimaryTemplate(),
4322 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004323 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004324 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004325
4326 // C++ [temp.expl.spec]p6:
4327 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004328 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004329 // before the first use of that specialization that would cause an implicit
4330 // instantiation to take place, in every translation unit in which such a
4331 // use occurs; no diagnostic is required.
4332 FunctionTemplateSpecializationInfo *SpecInfo
4333 = Specialization->getTemplateSpecializationInfo();
4334 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004335
Abramo Bagnara8075c852010-06-12 07:44:57 +00004336 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00004337 if (!isFriend &&
4338 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004339 TSK_ExplicitSpecialization,
4340 Specialization,
4341 SpecInfo->getTemplateSpecializationKind(),
4342 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004343 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004344 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004345
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004346 // Mark the prior declaration as an explicit specialization, so that later
4347 // clients know that this is an explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004348 if (!isFriend)
4349 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004350
4351 // Turn the given function declaration into a function template
4352 // specialization, with the template arguments from the previous
4353 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004354 // Take copies of (semantic and syntactic) template argument lists.
4355 const TemplateArgumentList* TemplArgs = new (Context)
4356 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4357 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4358 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004359 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004360 TemplArgs, /*InsertPos=*/0,
4361 SpecInfo->getTemplateSpecializationKind(),
4362 TemplArgsAsWritten);
4363
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004364 // The "previous declaration" for this function template specialization is
4365 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004366 Previous.clear();
4367 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004368 return false;
4369}
4370
Douglas Gregor86d142a2009-10-08 07:24:58 +00004371/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004372/// specialization.
4373///
4374/// This routine performs all of the semantic analysis required for an
4375/// explicit member function specialization. On successful completion,
4376/// the function declaration \p FD will become a member function
4377/// specialization.
4378///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004379/// \param Member the member declaration, which will be updated to become a
4380/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004381///
John McCall1f82f242009-11-18 22:49:29 +00004382/// \param Previous the set of declarations, one of which may be specialized
4383/// by this function specialization; the set will be modified to contain the
4384/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004385bool
John McCall1f82f242009-11-18 22:49:29 +00004386Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004387 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004388
Douglas Gregor86d142a2009-10-08 07:24:58 +00004389 // Try to find the member we are instantiating.
4390 NamedDecl *Instantiation = 0;
4391 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004392 MemberSpecializationInfo *MSInfo = 0;
4393
John McCall1f82f242009-11-18 22:49:29 +00004394 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004395 // Nowhere to look anyway.
4396 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004397 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4398 I != E; ++I) {
4399 NamedDecl *D = (*I)->getUnderlyingDecl();
4400 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004401 if (Context.hasSameType(Function->getType(), Method->getType())) {
4402 Instantiation = Method;
4403 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004404 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004405 break;
4406 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004407 }
4408 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004409 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004410 VarDecl *PrevVar;
4411 if (Previous.isSingleResult() &&
4412 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004413 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004414 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004415 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004416 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004417 }
4418 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004419 CXXRecordDecl *PrevRecord;
4420 if (Previous.isSingleResult() &&
4421 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4422 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004423 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004424 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004425 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004426 }
4427
4428 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004429 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004430 // specializations are always out-of-line, the caller will complain about
4431 // this mismatch later.
4432 return false;
4433 }
John McCalle820e5e2010-04-13 20:37:33 +00004434
4435 // If this is a friend, just bail out here before we start turning
4436 // things into explicit specializations.
4437 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4438 // Preserve instantiation information.
4439 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4440 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4441 cast<CXXMethodDecl>(InstantiatedFrom),
4442 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4443 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4444 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4445 cast<CXXRecordDecl>(InstantiatedFrom),
4446 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4447 }
4448
4449 Previous.clear();
4450 Previous.addDecl(Instantiation);
4451 return false;
4452 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004453
Douglas Gregor86d142a2009-10-08 07:24:58 +00004454 // Make sure that this is a specialization of a member.
4455 if (!InstantiatedFrom) {
4456 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4457 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004458 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4459 return true;
4460 }
4461
Douglas Gregor06db9f52009-10-12 20:18:28 +00004462 // C++ [temp.expl.spec]p6:
4463 // If a template, a member template or the member of a class template is
4464 // explicitly specialized then that spe- cialization shall be declared
4465 // before the first use of that specialization that would cause an implicit
4466 // instantiation to take place, in every translation unit in which such a
4467 // use occurs; no diagnostic is required.
4468 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004469
Abramo Bagnara8075c852010-06-12 07:44:57 +00004470 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00004471 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4472 TSK_ExplicitSpecialization,
4473 Instantiation,
4474 MSInfo->getTemplateSpecializationKind(),
4475 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004476 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004477 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004478
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004479 // Check the scope of this explicit specialization.
4480 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004481 InstantiatedFrom,
4482 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004483 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004484 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004485
Douglas Gregor86d142a2009-10-08 07:24:58 +00004486 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004487 // the original declaration to note that it is an explicit specialization
4488 // (if it was previously an implicit instantiation). This latter step
4489 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004490 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004491 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4492 if (InstantiationFunction->getTemplateSpecializationKind() ==
4493 TSK_ImplicitInstantiation) {
4494 InstantiationFunction->setTemplateSpecializationKind(
4495 TSK_ExplicitSpecialization);
4496 InstantiationFunction->setLocation(Member->getLocation());
4497 }
4498
Douglas Gregor86d142a2009-10-08 07:24:58 +00004499 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4500 cast<CXXMethodDecl>(InstantiatedFrom),
4501 TSK_ExplicitSpecialization);
4502 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004503 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4504 if (InstantiationVar->getTemplateSpecializationKind() ==
4505 TSK_ImplicitInstantiation) {
4506 InstantiationVar->setTemplateSpecializationKind(
4507 TSK_ExplicitSpecialization);
4508 InstantiationVar->setLocation(Member->getLocation());
4509 }
4510
Douglas Gregor86d142a2009-10-08 07:24:58 +00004511 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4512 cast<VarDecl>(InstantiatedFrom),
4513 TSK_ExplicitSpecialization);
4514 } else {
4515 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004516 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4517 if (InstantiationClass->getTemplateSpecializationKind() ==
4518 TSK_ImplicitInstantiation) {
4519 InstantiationClass->setTemplateSpecializationKind(
4520 TSK_ExplicitSpecialization);
4521 InstantiationClass->setLocation(Member->getLocation());
4522 }
4523
Douglas Gregor86d142a2009-10-08 07:24:58 +00004524 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004525 cast<CXXRecordDecl>(InstantiatedFrom),
4526 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004527 }
4528
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004529 // Save the caller the trouble of having to figure out which declaration
4530 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004531 Previous.clear();
4532 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004533 return false;
4534}
4535
Douglas Gregore47f5a72009-10-14 23:41:34 +00004536/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004537///
4538/// \returns true if a serious error occurs, false otherwise.
4539static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00004540 SourceLocation InstLoc,
4541 bool WasQualifiedName) {
4542 DeclContext *ExpectedContext
4543 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4544 DeclContext *CurContext = S.CurContext->getLookupContext();
4545
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004546 if (CurContext->isRecord()) {
4547 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4548 << D;
4549 return true;
4550 }
4551
Douglas Gregore47f5a72009-10-14 23:41:34 +00004552 // C++0x [temp.explicit]p2:
4553 // An explicit instantiation shall appear in an enclosing namespace of its
4554 // template.
4555 //
4556 // This is DR275, which we do not retroactively apply to C++98/03.
4557 if (S.getLangOptions().CPlusPlus0x &&
4558 !CurContext->Encloses(ExpectedContext)) {
4559 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004560 S.Diag(InstLoc,
4561 S.getLangOptions().CPlusPlus0x?
4562 diag::err_explicit_instantiation_out_of_scope
4563 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004564 << D << NS;
4565 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004566 S.Diag(InstLoc,
4567 S.getLangOptions().CPlusPlus0x?
4568 diag::err_explicit_instantiation_must_be_global
4569 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004570 << D;
4571 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004572 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004573 }
4574
4575 // C++0x [temp.explicit]p2:
4576 // If the name declared in the explicit instantiation is an unqualified
4577 // name, the explicit instantiation shall appear in the namespace where
4578 // its template is declared or, if that namespace is inline (7.3.1), any
4579 // namespace from its enclosing namespace set.
4580 if (WasQualifiedName)
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004581 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004582
4583 if (CurContext->Equals(ExpectedContext))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004584 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004585
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004586 S.Diag(InstLoc,
4587 S.getLangOptions().CPlusPlus0x?
4588 diag::err_explicit_instantiation_unqualified_wrong_namespace
4589 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004590 << D << ExpectedContext;
4591 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004592 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004593}
4594
4595/// \brief Determine whether the given scope specifier has a template-id in it.
4596static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4597 if (!SS.isSet())
4598 return false;
4599
4600 // C++0x [temp.explicit]p2:
4601 // If the explicit instantiation is for a member function, a member class
4602 // or a static data member of a class template specialization, the name of
4603 // the class template specialization in the qualified-id for the member
4604 // name shall be a simple-template-id.
4605 //
4606 // C++98 has the same restriction, just worded differently.
4607 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4608 NNS; NNS = NNS->getPrefix())
4609 if (Type *T = NNS->getAsType())
4610 if (isa<TemplateSpecializationType>(T))
4611 return true;
4612
4613 return false;
4614}
4615
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004616// Explicit instantiation of a class template specialization
Douglas Gregora1f49972009-05-13 00:25:59 +00004617Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004618Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004619 SourceLocation ExternLoc,
4620 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004621 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004622 SourceLocation KWLoc,
4623 const CXXScopeSpec &SS,
4624 TemplateTy TemplateD,
4625 SourceLocation TemplateNameLoc,
4626 SourceLocation LAngleLoc,
4627 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004628 SourceLocation RAngleLoc,
4629 AttributeList *Attr) {
4630 // Find the class template we're specializing
4631 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004632 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004633 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4634
4635 // Check that the specialization uses the same tag kind as the
4636 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004637 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4638 assert(Kind != TTK_Enum &&
4639 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004640 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004641 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004642 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004643 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004644 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004645 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004646 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004647 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004648 diag::note_previous_use);
4649 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4650 }
4651
Douglas Gregore47f5a72009-10-14 23:41:34 +00004652 // C++0x [temp.explicit]p2:
4653 // There are two forms of explicit instantiation: an explicit instantiation
4654 // definition and an explicit instantiation declaration. An explicit
4655 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004656 TemplateSpecializationKind TSK
4657 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4658 : TSK_ExplicitInstantiationDeclaration;
4659
Douglas Gregora1f49972009-05-13 00:25:59 +00004660 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004661 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004662 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004663
4664 // Check that the template argument list is well-formed for this
4665 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004666 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4667 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004668 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4669 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004670 return true;
4671
Mike Stump11289f42009-09-09 15:08:12 +00004672 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004673 ClassTemplate->getTemplateParameters()->size()) &&
4674 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004675
Douglas Gregora1f49972009-05-13 00:25:59 +00004676 // Find the class template specialization declaration that
4677 // corresponds to these arguments.
Douglas Gregora1f49972009-05-13 00:25:59 +00004678 void *InsertPos = 0;
4679 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004680 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4681 Converted.flatSize(), InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004682
Abramo Bagnara8075c852010-06-12 07:44:57 +00004683 TemplateSpecializationKind PrevDecl_TSK
4684 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4685
Douglas Gregor54888652009-10-07 00:13:32 +00004686 // C++0x [temp.explicit]p2:
4687 // [...] An explicit instantiation shall appear in an enclosing
4688 // namespace of its template. [...]
4689 //
4690 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004691 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4692 SS.isSet()))
4693 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004694
Douglas Gregora1f49972009-05-13 00:25:59 +00004695 ClassTemplateSpecializationDecl *Specialization = 0;
4696
Douglas Gregor0681a352009-11-25 06:01:46 +00004697 bool ReusedDecl = false;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004698 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004699 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00004700 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004701 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004702 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004703 HasNoEffect))
Douglas Gregora1f49972009-05-13 00:25:59 +00004704 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004705
Abramo Bagnara8075c852010-06-12 07:44:57 +00004706 // Even though HasNoEffect == true means that this explicit instantiation
4707 // has no effect on semantics, we go on to put its syntax in the AST.
4708
4709 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4710 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004711 // Since the only prior class template specialization with these
4712 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00004713 // declaration node as our own, updating the source location
4714 // for the template name to reflect our new declaration.
4715 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004716 Specialization = PrevDecl;
4717 Specialization->setLocation(TemplateNameLoc);
4718 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004719 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004720 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004721 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004722
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004723 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004724 // Create a new class template specialization declaration node for
4725 // this explicit specialization.
4726 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004727 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00004728 ClassTemplate->getDeclContext(),
4729 TemplateNameLoc,
4730 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004731 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004732 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004733
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004734 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00004735 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004736 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004737 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004738 }
4739
4740 // Build the fully-sugared type for this explicit instantiation as
4741 // the user wrote in the explicit instantiation itself. This means
4742 // that we'll pretty-print the type retrieved from the
4743 // specialization's declaration the way that the user actually wrote
4744 // the explicit instantiation, rather than formatting the name based
4745 // on the "canonical" representation used to store the template
4746 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004747 TypeSourceInfo *WrittenTy
4748 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4749 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004750 Context.getTypeDeclType(Specialization));
4751 Specialization->setTypeAsWritten(WrittenTy);
4752 TemplateArgsIn.release();
4753
Abramo Bagnara8075c852010-06-12 07:44:57 +00004754 // Set source locations for keywords.
4755 Specialization->setExternLoc(ExternLoc);
4756 Specialization->setTemplateKeywordLoc(TemplateLoc);
4757
4758 // Add the explicit instantiation into its lexical context. However,
4759 // since explicit instantiations are never found by name lookup, we
4760 // just put it into the declaration context directly.
4761 Specialization->setLexicalDeclContext(CurContext);
4762 CurContext->addDecl(Specialization);
4763
4764 // Syntax is now OK, so return if it has no other effect on semantics.
4765 if (HasNoEffect) {
4766 // Set the template specialization kind.
4767 Specialization->setTemplateSpecializationKind(TSK);
4768 return DeclPtrTy::make(Specialization);
Douglas Gregor0681a352009-11-25 06:01:46 +00004769 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004770
4771 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004772 // A definition of a class template or class member template
4773 // shall be in scope at the point of the explicit instantiation of
4774 // the class template or class member template.
4775 //
4776 // This check comes when we actually try to perform the
4777 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004778 ClassTemplateSpecializationDecl *Def
4779 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004780 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004781 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004782 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004783 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00004784 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004785 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
4786 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004787
Douglas Gregor1d957a32009-10-27 18:42:08 +00004788 // Instantiate the members of this class template specialization.
4789 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004790 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004791 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004792 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4793
4794 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4795 // TSK_ExplicitInstantiationDefinition
4796 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4797 TSK == TSK_ExplicitInstantiationDefinition)
4798 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004799
Douglas Gregor12e49d32009-10-15 22:53:21 +00004800 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004801 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004802
Abramo Bagnara8075c852010-06-12 07:44:57 +00004803 // Set the template specialization kind.
4804 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00004805 return DeclPtrTy::make(Specialization);
4806}
4807
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004808// Explicit instantiation of a member class of a class template.
4809Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004810Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004811 SourceLocation ExternLoc,
4812 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004813 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004814 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004815 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004816 IdentifierInfo *Name,
4817 SourceLocation NameLoc,
4818 AttributeList *Attr) {
4819
Douglas Gregord6ab8742009-05-28 23:31:59 +00004820 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004821 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004822 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004823 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004824 MultiTemplateParamsArg(*this, 0, 0),
4825 Owned, IsDependent);
4826 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4827
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004828 if (!TagD)
4829 return true;
4830
4831 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4832 if (Tag->isEnum()) {
4833 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4834 << Context.getTypeDeclType(Tag);
4835 return true;
4836 }
4837
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004838 if (Tag->isInvalidDecl())
4839 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004840
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004841 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4842 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4843 if (!Pattern) {
4844 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4845 << Context.getTypeDeclType(Record);
4846 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4847 return true;
4848 }
4849
Douglas Gregore47f5a72009-10-14 23:41:34 +00004850 // C++0x [temp.explicit]p2:
4851 // If the explicit instantiation is for a class or member class, the
4852 // elaborated-type-specifier in the declaration shall include a
4853 // simple-template-id.
4854 //
4855 // C++98 has the same restriction, just worded differently.
4856 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00004857 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004858 << Record << SS.getRange();
4859
4860 // C++0x [temp.explicit]p2:
4861 // There are two forms of explicit instantiation: an explicit instantiation
4862 // definition and an explicit instantiation declaration. An explicit
4863 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004864 TemplateSpecializationKind TSK
4865 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4866 : TSK_ExplicitInstantiationDeclaration;
4867
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004868 // C++0x [temp.explicit]p2:
4869 // [...] An explicit instantiation shall appear in an enclosing
4870 // namespace of its template. [...]
4871 //
4872 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004873 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004874
4875 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004876 CXXRecordDecl *PrevDecl
4877 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004878 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004879 PrevDecl = Record;
4880 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004881 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00004882 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004883 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004884 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004885 PrevDecl,
4886 MSInfo->getTemplateSpecializationKind(),
4887 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004888 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004889 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004890 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004891 return TagD;
4892 }
4893
Douglas Gregor12e49d32009-10-15 22:53:21 +00004894 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004895 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004896 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004897 // C++ [temp.explicit]p3:
4898 // A definition of a member class of a class template shall be in scope
4899 // at the point of an explicit instantiation of the member class.
4900 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004901 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004902 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004903 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4904 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004905 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4906 << Pattern;
4907 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004908 } else {
4909 if (InstantiateClass(NameLoc, Record, Def,
4910 getTemplateInstantiationArgs(Record),
4911 TSK))
4912 return true;
4913
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004914 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004915 if (!RecordDef)
4916 return true;
4917 }
4918 }
4919
4920 // Instantiate all of the members of the class.
4921 InstantiateClassMembers(NameLoc, RecordDef,
4922 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004923
Douglas Gregor88d292c2010-05-13 16:44:06 +00004924 if (TSK == TSK_ExplicitInstantiationDefinition)
4925 MarkVTableUsed(NameLoc, RecordDef, true);
4926
Mike Stump87c57ac2009-05-16 07:39:55 +00004927 // FIXME: We don't have any representation for explicit instantiations of
4928 // member classes. Such a representation is not needed for compilation, but it
4929 // should be available for clients that want to see all of the declarations in
4930 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004931 return TagD;
4932}
4933
Douglas Gregor450f00842009-09-25 18:43:00 +00004934Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4935 SourceLocation ExternLoc,
4936 SourceLocation TemplateLoc,
4937 Declarator &D) {
4938 // Explicit instantiations always require a name.
4939 DeclarationName Name = GetNameForDeclarator(D);
4940 if (!Name) {
4941 if (!D.isInvalidType())
4942 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4943 diag::err_explicit_instantiation_requires_name)
4944 << D.getDeclSpec().getSourceRange()
4945 << D.getSourceRange();
4946
4947 return true;
4948 }
4949
4950 // The scope passed in may not be a decl scope. Zip up the scope tree until
4951 // we find one that is.
4952 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4953 (S->getFlags() & Scope::TemplateParamScope) != 0)
4954 S = S->getParent();
4955
4956 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00004957 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
4958 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00004959 if (R.isNull())
4960 return true;
4961
4962 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4963 // Cannot explicitly instantiate a typedef.
4964 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4965 << Name;
4966 return true;
4967 }
4968
Douglas Gregor3c74d412009-10-14 20:14:33 +00004969 // C++0x [temp.explicit]p1:
4970 // [...] An explicit instantiation of a function template shall not use the
4971 // inline or constexpr specifiers.
4972 // Presumably, this also applies to member functions of class templates as
4973 // well.
4974 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4975 Diag(D.getDeclSpec().getInlineSpecLoc(),
4976 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00004977 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004978
4979 // FIXME: check for constexpr specifier.
4980
Douglas Gregore47f5a72009-10-14 23:41:34 +00004981 // C++0x [temp.explicit]p2:
4982 // There are two forms of explicit instantiation: an explicit instantiation
4983 // definition and an explicit instantiation declaration. An explicit
4984 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004985 TemplateSpecializationKind TSK
4986 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4987 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004988
John McCall27b18f82009-11-17 02:14:36 +00004989 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4990 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004991
4992 if (!R->isFunctionType()) {
4993 // C++ [temp.explicit]p1:
4994 // A [...] static data member of a class template can be explicitly
4995 // instantiated from the member definition associated with its class
4996 // template.
John McCall27b18f82009-11-17 02:14:36 +00004997 if (Previous.isAmbiguous())
4998 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00004999
John McCall67c00872009-12-02 08:25:40 +00005000 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005001 if (!Prev || !Prev->isStaticDataMember()) {
5002 // We expect to see a data data member here.
5003 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5004 << Name;
5005 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5006 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005007 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005008 return true;
5009 }
5010
5011 if (!Prev->getInstantiatedFromStaticDataMember()) {
5012 // FIXME: Check for explicit specialization?
5013 Diag(D.getIdentifierLoc(),
5014 diag::err_explicit_instantiation_data_member_not_instantiated)
5015 << Prev;
5016 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5017 // FIXME: Can we provide a note showing where this was declared?
5018 return true;
5019 }
5020
Douglas Gregore47f5a72009-10-14 23:41:34 +00005021 // C++0x [temp.explicit]p2:
5022 // If the explicit instantiation is for a member function, a member class
5023 // or a static data member of a class template specialization, the name of
5024 // the class template specialization in the qualified-id for the member
5025 // name shall be a simple-template-id.
5026 //
5027 // C++98 has the same restriction, just worded differently.
5028 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5029 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005030 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005031 << Prev << D.getCXXScopeSpec().getRange();
5032
5033 // Check the scope of this explicit instantiation.
5034 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5035
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005036 // Verify that it is okay to explicitly instantiate here.
5037 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5038 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00005039 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005040 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005041 MSInfo->getTemplateSpecializationKind(),
5042 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005043 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005044 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005045 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005046 return DeclPtrTy();
5047
Douglas Gregor450f00842009-09-25 18:43:00 +00005048 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005049 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005050 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00005051 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
5052 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00005053
5054 // FIXME: Create an ExplicitInstantiation node?
5055 return DeclPtrTy();
5056 }
5057
Douglas Gregor0e876e02009-09-25 23:53:26 +00005058 // If the declarator is a template-id, translate the parser's template
5059 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005060 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005061 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005062 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5063 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005064 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5065 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005066 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5067 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005068 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005069 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005070 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005071 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005072 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005073
Douglas Gregor450f00842009-09-25 18:43:00 +00005074 // C++ [temp.explicit]p1:
5075 // A [...] function [...] can be explicitly instantiated from its template.
5076 // A member function [...] of a class template can be explicitly
5077 // instantiated from the member definition associated with its class
5078 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005079 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005080 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5081 P != PEnd; ++P) {
5082 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005083 if (!HasExplicitTemplateArgs) {
5084 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5085 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5086 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005087
John McCall58cc69d2010-01-27 01:50:18 +00005088 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005089 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5090 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005091 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005092 }
5093 }
5094
5095 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5096 if (!FunTmpl)
5097 continue;
5098
John McCallbc077cf2010-02-08 23:07:23 +00005099 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005100 FunctionDecl *Specialization = 0;
5101 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005102 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005103 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005104 R, Specialization, Info)) {
5105 // FIXME: Keep track of almost-matches?
5106 (void)TDK;
5107 continue;
5108 }
5109
John McCall58cc69d2010-01-27 01:50:18 +00005110 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005111 }
5112
5113 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005114 UnresolvedSetIterator Result
5115 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005116 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005117 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5118 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5119 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005120
John McCall58cc69d2010-01-27 01:50:18 +00005121 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005122 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005123
5124 // Ignore access control bits, we don't need them for redeclaration checking.
5125 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005126
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005127 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005128 Diag(D.getIdentifierLoc(),
5129 diag::err_explicit_instantiation_member_function_not_instantiated)
5130 << Specialization
5131 << (Specialization->getTemplateSpecializationKind() ==
5132 TSK_ExplicitSpecialization);
5133 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5134 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005135 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005136
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005137 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005138 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5139 PrevDecl = Specialization;
5140
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005141 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005142 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005143 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005144 PrevDecl,
5145 PrevDecl->getTemplateSpecializationKind(),
5146 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005147 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005148 return true;
5149
5150 // FIXME: We may still want to build some representation of this
5151 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00005152 if (HasNoEffect)
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005153 return DeclPtrTy();
5154 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005155
5156 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005157
5158 if (TSK == TSK_ExplicitInstantiationDefinition)
5159 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5160 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005161
Douglas Gregore47f5a72009-10-14 23:41:34 +00005162 // C++0x [temp.explicit]p2:
5163 // If the explicit instantiation is for a member function, a member class
5164 // or a static data member of a class template specialization, the name of
5165 // the class template specialization in the qualified-id for the member
5166 // name shall be a simple-template-id.
5167 //
5168 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005169 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005170 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005171 D.getCXXScopeSpec().isSet() &&
5172 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5173 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005174 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005175 << Specialization << D.getCXXScopeSpec().getRange();
5176
5177 CheckExplicitInstantiationScope(*this,
5178 FunTmpl? (NamedDecl *)FunTmpl
5179 : Specialization->getInstantiatedFromMemberFunction(),
5180 D.getIdentifierLoc(),
5181 D.getCXXScopeSpec().isSet());
5182
Douglas Gregor450f00842009-09-25 18:43:00 +00005183 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5184 return DeclPtrTy();
5185}
5186
Douglas Gregor333489b2009-03-27 23:10:48 +00005187Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005188Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5189 const CXXScopeSpec &SS, IdentifierInfo *Name,
5190 SourceLocation TagLoc, SourceLocation NameLoc) {
5191 // This has to hold, because SS is expected to be defined.
5192 assert(Name && "Expected a name in a dependent tag");
5193
5194 NestedNameSpecifier *NNS
5195 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5196 if (!NNS)
5197 return true;
5198
Abramo Bagnara6150c882010-05-11 21:36:43 +00005199 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005200
Douglas Gregorba41d012010-04-24 16:38:41 +00005201 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5202 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005203 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005204 return true;
5205 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005206
5207 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5208 return Context.getDependentNameType(Kwd, NNS, Name).getAsOpaquePtr();
John McCall7f41d982009-09-11 04:59:25 +00005209}
5210
5211Sema::TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005212Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5213 const CXXScopeSpec &SS, const IdentifierInfo &II,
5214 SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005215 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005216 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5217 if (!NNS)
5218 return true;
5219
Douglas Gregorf7d77712010-06-16 22:31:08 +00005220 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5221 !getLangOptions().CPlusPlus0x)
5222 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5223 << FixItHint::CreateRemoval(TypenameLoc);
5224
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005225 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005226 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005227 if (T.isNull())
5228 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005229
5230 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5231 if (isa<DependentNameType>(T)) {
5232 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005233 TL.setKeywordLoc(TypenameLoc);
5234 TL.setQualifierRange(SS.getRange());
5235 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005236 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005237 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005238 TL.setKeywordLoc(TypenameLoc);
5239 TL.setQualifierRange(SS.getRange());
5240 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005241 }
5242
5243 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor333489b2009-03-27 23:10:48 +00005244}
5245
Douglas Gregordce2b622009-04-01 00:28:59 +00005246Sema::TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005247Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5248 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
5249 TypeTy *Ty) {
5250 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5251 !getLangOptions().CPlusPlus0x)
5252 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5253 << FixItHint::CreateRemoval(TypenameLoc);
5254
John McCallf7bcc812010-05-28 23:32:21 +00005255 TypeSourceInfo *InnerTSI = 0;
5256 QualType T = GetTypeFromParser(Ty, &InnerTSI);
Mike Stump11289f42009-09-09 15:08:12 +00005257 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00005258 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
John McCallf7bcc812010-05-28 23:32:21 +00005259
5260 assert(isa<TemplateSpecializationType>(T) &&
5261 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005262
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005263 if (computeDeclContext(SS, false)) {
5264 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005265 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005266 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005267
5268 // Push the inner type, preserving its source locations if possible.
5269 TypeLocBuilder Builder;
5270 if (InnerTSI)
5271 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5272 else
5273 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5274
Abramo Bagnara6150c882010-05-11 21:36:43 +00005275 T = Context.getElaboratedType(ETK_Typename, NNS, T);
John McCallf7bcc812010-05-28 23:32:21 +00005276 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5277 TL.setKeywordLoc(TypenameLoc);
5278 TL.setQualifierRange(SS.getRange());
5279
5280 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCall99b2fe52010-04-29 23:50:39 +00005281 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005282 }
Mike Stump11289f42009-09-09 15:08:12 +00005283
John McCallc392f372010-06-11 00:33:02 +00005284 // TODO: it's really silly that we make a template specialization
5285 // type earlier only to drop it again here.
5286 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5287 DependentTemplateName *DTN =
5288 TST->getTemplateName().getAsDependentTemplateName();
5289 assert(DTN && "dependent template has non-dependent name?");
5290 T = Context.getDependentTemplateSpecializationType(ETK_Typename, NNS,
5291 DTN->getIdentifier(),
5292 TST->getNumArgs(),
5293 TST->getArgs());
John McCall99b2fe52010-04-29 23:50:39 +00005294 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCallc392f372010-06-11 00:33:02 +00005295 DependentTemplateSpecializationTypeLoc TL =
5296 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5297 if (InnerTSI) {
5298 TemplateSpecializationTypeLoc TSTL =
5299 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5300 TL.setLAngleLoc(TSTL.getLAngleLoc());
5301 TL.setRAngleLoc(TSTL.getRAngleLoc());
5302 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5303 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5304 } else {
5305 TL.initializeLocal(SourceLocation());
5306 }
John McCallf7bcc812010-05-28 23:32:21 +00005307 TL.setKeywordLoc(TypenameLoc);
5308 TL.setQualifierRange(SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005309 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00005310}
5311
Douglas Gregor333489b2009-03-27 23:10:48 +00005312/// \brief Build the type that describes a C++ typename specifier,
5313/// e.g., "typename T::type".
5314QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005315Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5316 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005317 SourceLocation KeywordLoc, SourceRange NNSRange,
5318 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005319 CXXScopeSpec SS;
5320 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005321 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005322
John McCall0b66eb32010-05-01 00:40:08 +00005323 DeclContext *Ctx = computeDeclContext(SS);
5324 if (!Ctx) {
5325 // If the nested-name-specifier is dependent and couldn't be
5326 // resolved to a type, build a typename type.
5327 assert(NNS->isDependent());
5328 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005329 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005330
John McCall0b66eb32010-05-01 00:40:08 +00005331 // If the nested-name-specifier refers to the current instantiation,
5332 // the "typename" keyword itself is superfluous. In C++03, the
5333 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5334 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00005335 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005336
John McCall0b66eb32010-05-01 00:40:08 +00005337 if (RequireCompleteDeclContext(SS, Ctx))
5338 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005339
5340 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005341 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005342 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005343 unsigned DiagID = 0;
5344 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005345 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005346 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005347 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005348 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005349
5350 case LookupResult::NotFoundInCurrentInstantiation:
5351 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005352 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005353
5354 case LookupResult::Found:
Douglas Gregorf7d77712010-06-16 22:31:08 +00005355 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005356 // We found a type. Build an ElaboratedType, since the
5357 // typename-specifier was just sugar.
5358 return Context.getElaboratedType(ETK_Typename, NNS,
5359 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005360 }
5361
5362 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005363 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005364 break;
5365
John McCalle61f2ba2009-11-18 02:36:19 +00005366 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005367 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005368 return QualType();
5369
Douglas Gregor333489b2009-03-27 23:10:48 +00005370 case LookupResult::FoundOverloaded:
5371 DiagID = diag::err_typename_nested_not_type;
5372 Referenced = *Result.begin();
5373 break;
5374
John McCall6538c932009-10-10 05:48:19 +00005375 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005376 return QualType();
5377 }
5378
5379 // If we get here, it's because name lookup did not find a
5380 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005381 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5382 IILoc);
5383 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005384 if (Referenced)
5385 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5386 << Name;
5387 return QualType();
5388}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005389
5390namespace {
5391 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005392 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005393 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005394 SourceLocation Loc;
5395 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005396
Douglas Gregor15acfb92009-08-06 16:20:37 +00005397 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005398 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5399
Mike Stump11289f42009-09-09 15:08:12 +00005400 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005401 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005402 DeclarationName Entity)
5403 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005404 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005405
5406 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005407 /// transformed.
5408 ///
5409 /// For the purposes of type reconstruction, a type has already been
5410 /// transformed if it is NULL or if it is not dependent.
5411 bool AlreadyTransformed(QualType T) {
5412 return T.isNull() || !T->isDependentType();
5413 }
Mike Stump11289f42009-09-09 15:08:12 +00005414
5415 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005416 /// rebuilt.
5417 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005418
Douglas Gregor15acfb92009-08-06 16:20:37 +00005419 /// \brief Returns the name of the entity whose type is being rebuilt.
5420 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005421
Douglas Gregoref6ab412009-10-27 06:26:26 +00005422 /// \brief Sets the "base" location and entity when that
5423 /// information is known based on another transformation.
5424 void setBase(SourceLocation Loc, DeclarationName Entity) {
5425 this->Loc = Loc;
5426 this->Entity = Entity;
5427 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00005428 };
5429}
5430
Douglas Gregor15acfb92009-08-06 16:20:37 +00005431/// \brief Rebuilds a type within the context of the current instantiation.
5432///
Mike Stump11289f42009-09-09 15:08:12 +00005433/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005434/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005435/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005436/// partial specialization thereof). This routine will rebuild that type now
5437/// that we have entered the declarator's scope, which may produce different
5438/// canonical types, e.g.,
5439///
5440/// \code
5441/// template<typename T>
5442/// struct X {
5443/// typedef T* pointer;
5444/// pointer data();
5445/// };
5446///
5447/// template<typename T>
5448/// typename X<T>::pointer X<T>::data() { ... }
5449/// \endcode
5450///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005451/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005452/// since we do not know that we can look into X<T> when we parsed the type.
5453/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005454/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005455/// as the canonical type of T*, allowing the return types of the out-of-line
5456/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005457TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5458 SourceLocation Loc,
5459 DeclarationName Name) {
5460 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005461 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005462
Douglas Gregor15acfb92009-08-06 16:20:37 +00005463 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5464 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005465}
Douglas Gregorbe999392009-09-15 16:23:51 +00005466
John McCall99b2fe52010-04-29 23:50:39 +00005467bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5468 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005469
5470 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5471 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5472 DeclarationName());
5473 NestedNameSpecifier *Rebuilt =
5474 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005475 if (!Rebuilt) return true;
5476
5477 SS.setScopeRep(Rebuilt);
5478 return false;
John McCall2408e322010-04-27 00:57:59 +00005479}
5480
Douglas Gregorbe999392009-09-15 16:23:51 +00005481/// \brief Produces a formatted string that describes the binding of
5482/// template parameters to template arguments.
5483std::string
5484Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5485 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005486 // FIXME: For variadic templates, we'll need to get the structured list.
5487 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5488 Args.flat_size());
5489}
5490
5491std::string
5492Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5493 const TemplateArgument *Args,
5494 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005495 std::string Result;
5496
Douglas Gregore62e6a02009-11-11 19:13:48 +00005497 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005498 return Result;
5499
5500 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005501 if (I >= NumArgs)
5502 break;
5503
Douglas Gregorbe999392009-09-15 16:23:51 +00005504 if (I == 0)
5505 Result += "[with ";
5506 else
5507 Result += ", ";
5508
5509 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5510 Result += Id->getName();
5511 } else {
5512 Result += '$';
5513 Result += llvm::utostr(I);
5514 }
5515
5516 Result += " = ";
5517
5518 switch (Args[I].getKind()) {
5519 case TemplateArgument::Null:
5520 Result += "<no value>";
5521 break;
5522
5523 case TemplateArgument::Type: {
5524 std::string TypeStr;
5525 Args[I].getAsType().getAsStringInternal(TypeStr,
5526 Context.PrintingPolicy);
5527 Result += TypeStr;
5528 break;
5529 }
5530
5531 case TemplateArgument::Declaration: {
5532 bool Unnamed = true;
5533 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5534 if (ND->getDeclName()) {
5535 Unnamed = false;
5536 Result += ND->getNameAsString();
5537 }
5538 }
5539
5540 if (Unnamed) {
5541 Result += "<anonymous>";
5542 }
5543 break;
5544 }
5545
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005546 case TemplateArgument::Template: {
5547 std::string Str;
5548 llvm::raw_string_ostream OS(Str);
5549 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5550 Result += OS.str();
5551 break;
5552 }
5553
Douglas Gregorbe999392009-09-15 16:23:51 +00005554 case TemplateArgument::Integral: {
5555 Result += Args[I].getAsIntegral()->toString(10);
5556 break;
5557 }
5558
5559 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005560 // FIXME: This is non-optimal, since we're regurgitating the
5561 // expression we were given.
5562 std::string Str;
5563 {
5564 llvm::raw_string_ostream OS(Str);
5565 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5566 Context.PrintingPolicy);
5567 }
5568 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005569 break;
5570 }
5571
5572 case TemplateArgument::Pack:
5573 // FIXME: Format template argument packs
5574 Result += "<template argument pack>";
5575 break;
5576 }
5577 }
5578
5579 Result += ']';
5580 return Result;
5581}