blob: 5cfacf78b577cc863309aa4b1fc605fe64b2672f [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000012#include "clang/Sema/Sema.h"
13#include "clang/Sema/Lookup.h"
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 }
John McCallbd8062d2010-08-13 07:02:08 +000091
92 // FIXME: we promote access to public here as a workaround to
93 // the fact that LookupResult doesn't let us remember that we
94 // found this template through a particular injected class name,
95 // which means we end up doing nasty things to the invariants.
96 // Pretending that access is public is *much* safer.
97 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +000098 }
John McCalle66edc12009-11-24 19:00:30 +000099 }
100 filter.done();
101}
102
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000103TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000104 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000105 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000106 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000107 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000108 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000109 TemplateTy &TemplateResult,
110 bool &MemberOfUnknownSpecialization) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000111 assert(getLangOptions().CPlusPlus && "No template names in C!");
112
Douglas Gregor3cf81312009-11-03 23:16:33 +0000113 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000114 MemberOfUnknownSpecialization = false;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000115
116 switch (Name.getKind()) {
117 case UnqualifiedId::IK_Identifier:
118 TName = DeclarationName(Name.Identifier);
119 break;
120
121 case UnqualifiedId::IK_OperatorFunctionId:
122 TName = Context.DeclarationNames.getCXXOperatorName(
123 Name.OperatorFunctionId.Operator);
124 break;
125
Alexis Hunted0530f2009-11-28 08:58:14 +0000126 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000127 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
128 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000129
Douglas Gregor3cf81312009-11-03 23:16:33 +0000130 default:
131 return TNK_Non_template;
132 }
Mike Stump11289f42009-09-09 15:08:12 +0000133
John McCalle66edc12009-11-24 19:00:30 +0000134 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump11289f42009-09-09 15:08:12 +0000135
Douglas Gregorff18cc12009-12-31 08:11:17 +0000136 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
137 LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000138 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
139 MemberOfUnknownSpecialization);
John McCalldcc71402010-08-13 02:23:42 +0000140 if (R.empty() || R.isAmbiguous()) {
141 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000142 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000143 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000144
John McCalld28ae272009-12-02 08:04:21 +0000145 TemplateName Template;
146 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000147
John McCalld28ae272009-12-02 08:04:21 +0000148 unsigned ResultCount = R.end() - R.begin();
149 if (ResultCount > 1) {
150 // We assume that we'll preserve the qualifier from a function
151 // template name in other ways.
152 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
153 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000154
155 // We'll do this lookup again later.
156 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000157 } else {
John McCalld28ae272009-12-02 08:04:21 +0000158 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
159
160 if (SS.isSet() && !SS.isInvalid()) {
161 NestedNameSpecifier *Qualifier
162 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000163 Template = Context.getQualifiedTemplateName(Qualifier,
164 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000165 } else {
166 Template = TemplateName(TD);
167 }
168
John McCalldcc71402010-08-13 02:23:42 +0000169 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000170 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000171
172 // We'll do this lookup again later.
173 R.suppressDiagnostics();
174 } else {
John McCalld28ae272009-12-02 08:04:21 +0000175 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
176 TemplateKind = TNK_Type_template;
177 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000178 }
Mike Stump11289f42009-09-09 15:08:12 +0000179
John McCalld28ae272009-12-02 08:04:21 +0000180 TemplateResult = TemplateTy::make(Template);
181 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000182}
183
Douglas Gregor18473f32010-01-12 21:28:44 +0000184bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
185 SourceLocation IILoc,
186 Scope *S,
187 const CXXScopeSpec *SS,
188 TemplateTy &SuggestedTemplate,
189 TemplateNameKind &SuggestedKind) {
190 // We can't recover unless there's a dependent scope specifier preceding the
191 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000192 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000193 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
194 computeDeclContext(*SS))
195 return false;
196
197 // The code is missing a 'template' keyword prior to the dependent template
198 // name.
199 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
200 Diag(IILoc, diag::err_template_kw_missing)
201 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000202 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor18473f32010-01-12 21:28:44 +0000203 SuggestedTemplate
204 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
205 SuggestedKind = TNK_Dependent_template_name;
206 return true;
207}
208
John McCalle66edc12009-11-24 19:00:30 +0000209void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000210 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000211 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000212 bool EnteringContext,
213 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000214 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000215 MemberOfUnknownSpecialization = false;
John McCalle66edc12009-11-24 19:00:30 +0000216 DeclContext *LookupCtx = 0;
217 bool isDependent = false;
218 if (!ObjectType.isNull()) {
219 // This nested-name-specifier occurs in a member access expression, e.g.,
220 // x->B::f, and we are looking into the type of the object.
221 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
222 LookupCtx = computeDeclContext(ObjectType);
223 isDependent = ObjectType->isDependentType();
224 assert((isDependent || !ObjectType->isIncompleteType()) &&
225 "Caller should have completed object type");
226 } else if (SS.isSet()) {
227 // This nested-name-specifier occurs after another nested-name-specifier,
228 // so long into the context associated with the prior nested-name-specifier.
229 LookupCtx = computeDeclContext(SS, EnteringContext);
230 isDependent = isDependentScopeSpecifier(SS);
231
232 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000233 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000234 return;
235 }
236
237 bool ObjectTypeSearchedInScope = false;
238 if (LookupCtx) {
239 // Perform "qualified" name lookup into the declaration context we
240 // computed, which is either the type of the base of a member access
241 // expression or the declaration context associated with a prior
242 // nested-name-specifier.
243 LookupQualifiedName(Found, LookupCtx);
244
245 if (!ObjectType.isNull() && Found.empty()) {
246 // C++ [basic.lookup.classref]p1:
247 // In a class member access expression (5.2.5), if the . or -> token is
248 // immediately followed by an identifier followed by a <, the
249 // identifier must be looked up to determine whether the < is the
250 // beginning of a template argument list (14.2) or a less-than operator.
251 // The identifier is first looked up in the class of the object
252 // expression. If the identifier is not found, it is then looked up in
253 // the context of the entire postfix-expression and shall name a class
254 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000255 if (S) LookupName(Found, S);
256 ObjectTypeSearchedInScope = true;
257 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000258 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000259 // We cannot look into a dependent object type or nested nme
260 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000261 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000262 return;
263 } else {
264 // Perform unqualified name lookup in the current scope.
265 LookupName(Found, S);
266 }
267
Douglas Gregorc119dd52010-01-12 17:06:20 +0000268 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000269 // If we did not find any names, attempt to correct any typos.
270 DeclarationName Name = Found.getLookupName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000271 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregorc048c522010-06-29 19:27:42 +0000272 false, CTC_CXXCasts)) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000273 FilterAcceptableTemplateNames(Context, Found);
John McCalle9cccd82010-06-16 08:42:20 +0000274 if (!Found.empty()) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000275 if (LookupCtx)
276 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
277 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000278 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000279 Found.getLookupName().getAsString());
280 else
281 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
282 << Name << Found.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +0000283 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000284 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000285 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
286 Diag(Template->getLocation(), diag::note_previous_decl)
287 << Template->getDeclName();
John McCalle9cccd82010-06-16 08:42:20 +0000288 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000289 } else {
290 Found.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +0000291 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000292 }
293 }
294
John McCalle66edc12009-11-24 19:00:30 +0000295 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000296 if (Found.empty()) {
297 if (isDependent)
298 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000299 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000300 }
John McCalle66edc12009-11-24 19:00:30 +0000301
302 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
303 // C++ [basic.lookup.classref]p1:
304 // [...] If the lookup in the class of the object expression finds a
305 // template, the name is also looked up in the context of the entire
306 // postfix-expression and [...]
307 //
308 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
309 LookupOrdinaryName);
310 LookupName(FoundOuter, S);
311 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor41f90302010-04-12 20:54:26 +0000312
John McCalle66edc12009-11-24 19:00:30 +0000313 if (FoundOuter.empty()) {
314 // - if the name is not found, the name found in the class of the
315 // object expression is used, otherwise
316 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
317 // - if the name is found in the context of the entire
318 // postfix-expression and does not name a class template, the name
319 // found in the class of the object expression is used, otherwise
John McCalle9cccd82010-06-16 08:42:20 +0000320 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000321 // - if the name found is a class template, it must refer to the same
322 // entity as the one found in the class of the object expression,
323 // otherwise the program is ill-formed.
324 if (!Found.isSingleResult() ||
325 Found.getFoundDecl()->getCanonicalDecl()
326 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
327 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000328 diag::ext_nested_name_member_ref_lookup_ambiguous)
329 << Found.getLookupName()
330 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000331 Diag(Found.getRepresentativeDecl()->getLocation(),
332 diag::note_ambig_member_ref_object_type)
333 << ObjectType;
334 Diag(FoundOuter.getFoundDecl()->getLocation(),
335 diag::note_ambig_member_ref_scope);
336
337 // Recover by taking the template that we found in the object
338 // expression's type.
339 }
340 }
341 }
342}
343
John McCallcd4b4772009-12-02 03:53:29 +0000344/// ActOnDependentIdExpression - Handle a dependent id-expression that
345/// was just parsed. This is only possible with an explicit scope
346/// specifier naming a dependent type.
John McCalle66edc12009-11-24 19:00:30 +0000347Sema::OwningExprResult
348Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000349 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000350 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000351 const TemplateArgumentListInfo *TemplateArgs) {
352 NestedNameSpecifier *Qualifier
353 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall87fe5d52010-05-20 01:18:31 +0000354
355 DeclContext *DC = getFunctionLevelDeclContext();
John McCalle66edc12009-11-24 19:00:30 +0000356
John McCallcd4b4772009-12-02 03:53:29 +0000357 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000358 isa<CXXMethodDecl>(DC) &&
359 cast<CXXMethodDecl>(DC)->isInstance()) {
360 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCallcd4b4772009-12-02 03:53:29 +0000361
John McCalle66edc12009-11-24 19:00:30 +0000362 // Since the 'this' expression is synthesized, we don't need to
363 // perform the double-lookup check.
364 NamedDecl *FirstQualifierInScope = 0;
365
John McCall2d74de92009-12-01 22:10:20 +0000366 return Owned(CXXDependentScopeMemberExpr::Create(Context,
367 /*This*/ 0, ThisType,
368 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000369 /*Op*/ SourceLocation(),
370 Qualifier, SS.getRange(),
371 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000372 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000373 TemplateArgs));
374 }
375
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000376 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000377}
378
379Sema::OwningExprResult
380Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000381 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000382 const TemplateArgumentListInfo *TemplateArgs) {
383 return Owned(DependentScopeDeclRefExpr::Create(Context,
384 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
385 SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000386 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000387 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000388}
389
Douglas Gregor5101c242008-12-05 18:15:24 +0000390/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
391/// that the template parameter 'PrevDecl' is being shadowed by a new
392/// declaration at location Loc. Returns true to indicate that this is
393/// an error, and false otherwise.
394bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000395 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000396
397 // Microsoft Visual C++ permits template parameters to be shadowed.
398 if (getLangOptions().Microsoft)
399 return false;
400
401 // C++ [temp.local]p4:
402 // A template-parameter shall not be redeclared within its
403 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000404 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000405 << cast<NamedDecl>(PrevDecl)->getDeclName();
406 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
407 return true;
408}
409
Douglas Gregor463421d2009-03-03 04:44:36 +0000410/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000411/// the parameter D to reference the templated declaration and return a pointer
412/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000413TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000414 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000415 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000416 return Temp;
417 }
418 return 0;
419}
420
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000421static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
422 const ParsedTemplateArgument &Arg) {
423
424 switch (Arg.getKind()) {
425 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000426 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000427 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
428 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000429 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000430 return TemplateArgumentLoc(TemplateArgument(T), DI);
431 }
432
433 case ParsedTemplateArgument::NonType: {
434 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
435 return TemplateArgumentLoc(TemplateArgument(E), E);
436 }
437
438 case ParsedTemplateArgument::Template: {
439 TemplateName Template
440 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
441 return TemplateArgumentLoc(TemplateArgument(Template),
442 Arg.getScopeSpec().getRange(),
443 Arg.getLocation());
444 }
445 }
446
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000447 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000448 return TemplateArgumentLoc();
449}
450
451/// \brief Translates template arguments as provided by the parser
452/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000453void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
454 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000455 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000456 TemplateArgs.addArgument(translateTemplateArgument(*this,
457 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000458}
459
Douglas Gregor5101c242008-12-05 18:15:24 +0000460/// ActOnTypeParameter - Called when a C++ template type parameter
461/// (e.g., "typename T") has been parsed. Typename specifies whether
462/// the keyword "typename" was used to declare the type parameter
463/// (otherwise, "class" was used), and KeyLoc is the location of the
464/// "class" or "typename" keyword. ParamName is the name of the
465/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregor2ebcae12010-06-16 15:23:05 +0000466/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000467/// If the type parameter has a default argument, it will be added
468/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000469Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000470 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000471 SourceLocation KeyLoc,
472 IdentifierInfo *ParamName,
473 SourceLocation ParamNameLoc,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000474 unsigned Depth, unsigned Position,
475 SourceLocation EqualLoc,
476 TypeTy *DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000477 assert(S->isTemplateParamScope() &&
478 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000479 bool Invalid = false;
480
481 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000482 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000483 LookupOrdinaryName,
484 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000485 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000486 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000487 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000488 }
489
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000490 SourceLocation Loc = ParamNameLoc;
491 if (!ParamName)
492 Loc = KeyLoc;
493
Douglas Gregor5101c242008-12-05 18:15:24 +0000494 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000495 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
496 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000497 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000498 if (Invalid)
499 Param->setInvalidDecl();
500
501 if (ParamName) {
502 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000503 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000504 IdResolver.AddDecl(Param);
505 }
506
Douglas Gregordc13ded2010-07-01 00:00:45 +0000507 // Handle the default argument, if provided.
508 if (DefaultArg) {
509 TypeSourceInfo *DefaultTInfo;
510 GetTypeFromParser(DefaultArg, &DefaultTInfo);
511
512 assert(DefaultTInfo && "expected source information for type");
513
514 // C++0x [temp.param]p9:
515 // A default template-argument may be specified for any kind of
516 // template-parameter that is not a template parameter pack.
517 if (Ellipsis) {
518 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
519 return DeclPtrTy::make(Param);
520 }
521
522 // Check the template argument itself.
523 if (CheckTemplateArgument(Param, DefaultTInfo)) {
524 Param->setInvalidDecl();
525 return DeclPtrTy::make(Param);;
526 }
527
528 Param->setDefaultArgument(DefaultTInfo, false);
529 }
530
Chris Lattner83f095c2009-03-28 19:18:32 +0000531 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000532}
533
Douglas Gregor463421d2009-03-03 04:44:36 +0000534/// \brief Check that the type of a non-type template parameter is
535/// well-formed.
536///
537/// \returns the (possibly-promoted) parameter type if valid;
538/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000539QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000540Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000541 // We don't allow variably-modified types as the type of non-type template
542 // parameters.
543 if (T->isVariablyModifiedType()) {
544 Diag(Loc, diag::err_variably_modified_nontype_template_param)
545 << T;
546 return QualType();
547 }
548
Douglas Gregor463421d2009-03-03 04:44:36 +0000549 // C++ [temp.param]p4:
550 //
551 // A non-type template-parameter shall have one of the following
552 // (optionally cv-qualified) types:
553 //
554 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000555 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000556 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000557 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000558 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000559 T->isReferenceType() ||
560 // -- pointer to member.
561 T->isMemberPointerType() ||
562 // If T is a dependent type, we can't do the check now, so we
563 // assume that it is well-formed.
564 T->isDependentType())
565 return T;
566 // C++ [temp.param]p8:
567 //
568 // A non-type template-parameter of type "array of T" or
569 // "function returning T" is adjusted to be of type "pointer to
570 // T" or "pointer to function returning T", respectively.
571 else if (T->isArrayType())
572 // FIXME: Keep the type prior to promotion?
573 return Context.getArrayDecayedType(T);
574 else if (T->isFunctionType())
575 // FIXME: Keep the type prior to promotion?
576 return Context.getPointerType(T);
Douglas Gregor959d5a02010-05-22 16:17:30 +0000577
Douglas Gregor463421d2009-03-03 04:44:36 +0000578 Diag(Loc, diag::err_template_nontype_parm_bad_type)
579 << T;
580
581 return QualType();
582}
583
Chris Lattner83f095c2009-03-28 19:18:32 +0000584Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000585 unsigned Depth,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000586 unsigned Position,
587 SourceLocation EqualLoc,
588 ExprArg DefaultArg) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000589 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
590 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000591
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000592 assert(S->isTemplateParamScope() &&
593 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000594 bool Invalid = false;
595
596 IdentifierInfo *ParamName = D.getIdentifier();
597 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000598 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000599 LookupOrdinaryName,
600 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000601 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000602 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000603 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000604 }
605
Douglas Gregor463421d2009-03-03 04:44:36 +0000606 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000607 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000608 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000609 Invalid = true;
610 }
Douglas Gregor81338792009-02-10 17:43:50 +0000611
Douglas Gregor5101c242008-12-05 18:15:24 +0000612 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000613 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
614 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000615 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000616 if (Invalid)
617 Param->setInvalidDecl();
618
619 if (D.getIdentifier()) {
620 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000621 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000622 IdResolver.AddDecl(Param);
623 }
Douglas Gregordc13ded2010-07-01 00:00:45 +0000624
625 // Check the well-formedness of the default template argument, if provided.
626 if (Expr *Default = static_cast<Expr *>(DefaultArg.get())) {
627 TemplateArgument Converted;
628 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
629 Param->setInvalidDecl();
630 return DeclPtrTy::make(Param);;
631 }
632
633 Param->setDefaultArgument(DefaultArg.takeAs<Expr>(), false);
634 }
635
Chris Lattner83f095c2009-03-28 19:18:32 +0000636 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000637}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000638
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000639/// ActOnTemplateTemplateParameter - Called when a C++ template template
640/// parameter (e.g. T in template <template <typename> class T> class array)
641/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000642Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
643 SourceLocation TmpLoc,
644 TemplateParamsTy *Params,
645 IdentifierInfo *Name,
646 SourceLocation NameLoc,
647 unsigned Depth,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000648 unsigned Position,
649 SourceLocation EqualLoc,
650 const ParsedTemplateArgument &Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000651 assert(S->isTemplateParamScope() &&
652 "Template template parameter not in template parameter scope!");
653
654 // Construct the parameter object.
655 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000656 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
657 TmpLoc, Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000658 (TemplateParameterList*)Params);
659
Douglas Gregordc13ded2010-07-01 00:00:45 +0000660 // If the template template parameter has a name, then link the identifier
661 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000662 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000663 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000664 IdResolver.AddDecl(Param);
665 }
666
Douglas Gregordc13ded2010-07-01 00:00:45 +0000667 if (!Default.isInvalid()) {
668 // Check only that we have a template template argument. We don't want to
669 // try to check well-formedness now, because our template template parameter
670 // might have dependent types in its template parameters, which we wouldn't
671 // be able to match now.
672 //
673 // If none of the template template parameter's template arguments mention
674 // other template parameters, we could actually perform more checking here.
675 // However, it isn't worth doing.
676 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
677 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
678 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
679 << DefaultArg.getSourceRange();
680 return DeclPtrTy::make(Param);
681 }
682
683 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000684 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000685
Douglas Gregordc13ded2010-07-01 00:00:45 +0000686 return DeclPtrTy::make(Param);
Douglas Gregordba32632009-02-10 19:49:53 +0000687}
688
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000689/// ActOnTemplateParameterList - Builds a TemplateParameterList that
690/// contains the template parameters in Params/NumParams.
691Sema::TemplateParamsTy *
692Sema::ActOnTemplateParameterList(unsigned Depth,
693 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000694 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000695 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000696 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000697 SourceLocation RAngleLoc) {
698 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000699 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000700
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000701 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000702 (NamedDecl**)Params, NumParams,
703 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000704}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000705
John McCall3e11ebe2010-03-15 10:12:16 +0000706static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
707 if (SS.isSet())
708 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
709 SS.getRange());
710}
711
Douglas Gregorc08f4892009-03-25 00:13:59 +0000712Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000713Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000714 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000715 IdentifierInfo *Name, SourceLocation NameLoc,
716 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000717 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000718 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000719 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000720 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000721 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000722 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000723
724 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000725 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000726 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000727
Abramo Bagnara6150c882010-05-11 21:36:43 +0000728 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
729 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000730
731 // There is no such thing as an unnamed class template.
732 if (!Name) {
733 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000734 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000735 }
736
737 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000738 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000739 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000740 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000741 if (SS.isNotEmpty() && !SS.isInvalid()) {
742 SemanticContext = computeDeclContext(SS, true);
743 if (!SemanticContext) {
744 // FIXME: Produce a reasonable diagnostic here
745 return true;
746 }
Mike Stump11289f42009-09-09 15:08:12 +0000747
John McCall0b66eb32010-05-01 00:40:08 +0000748 if (RequireCompleteDeclContext(SS, SemanticContext))
749 return true;
750
John McCall27b18f82009-11-17 02:14:36 +0000751 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000752 } else {
753 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000754 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000755 }
Mike Stump11289f42009-09-09 15:08:12 +0000756
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000757 if (Previous.isAmbiguous())
758 return true;
759
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000760 NamedDecl *PrevDecl = 0;
761 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000762 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000763
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000764 // If there is a previous declaration with the same name, check
765 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000766 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000767 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000768
769 // We may have found the injected-class-name of a class template,
770 // class template partial specialization, or class template specialization.
771 // In these cases, grab the template that is being defined or specialized.
772 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
773 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
774 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
775 PrevClassTemplate
776 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
777 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
778 PrevClassTemplate
779 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
780 ->getSpecializedTemplate();
781 }
782 }
783
John McCalld43784f2009-12-18 11:25:59 +0000784 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000785 // C++ [namespace.memdef]p3:
786 // [...] When looking for a prior declaration of a class or a function
787 // declared as a friend, and when the name of the friend class or
788 // function is neither a qualified name nor a template-id, scopes outside
789 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000790 if (!SS.isSet()) {
791 DeclContext *OutermostContext = CurContext;
792 while (!OutermostContext->isFileContext())
793 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000794
Douglas Gregorb74b1032010-04-18 17:37:40 +0000795 if (PrevDecl &&
796 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
797 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
798 SemanticContext = PrevDecl->getDeclContext();
799 } else {
800 // Declarations in outer scopes don't matter. However, the outermost
801 // context we computed is the semantic context for our new
802 // declaration.
803 PrevDecl = PrevClassTemplate = 0;
804 SemanticContext = OutermostContext;
805 }
John McCall90d3bb92009-12-17 23:21:11 +0000806 }
Douglas Gregorb74b1032010-04-18 17:37:40 +0000807
John McCall90d3bb92009-12-17 23:21:11 +0000808 if (CurContext->isDependentContext()) {
809 // If this is a dependent context, we don't want to link the friend
810 // class template to the template in scope, because that would perform
811 // checking of the template parameter lists that can't be performed
812 // until the outer context is instantiated.
813 PrevDecl = PrevClassTemplate = 0;
814 }
815 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
816 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000817
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000818 if (PrevClassTemplate) {
819 // Ensure that the template parameter lists are compatible.
820 if (!TemplateParameterListsAreEqual(TemplateParams,
821 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000822 /*Complain=*/true,
823 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000824 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000825
826 // C++ [temp.class]p4:
827 // In a redeclaration, partial specialization, explicit
828 // specialization or explicit instantiation of a class template,
829 // the class-key shall agree in kind with the original class
830 // template declaration (7.1.5.3).
831 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000832 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000833 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000834 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000835 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000836 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000837 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000838 }
839
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000840 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000841 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000842 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000843 Diag(NameLoc, diag::err_redefinition) << Name;
844 Diag(Def->getLocation(), diag::note_previous_definition);
845 // FIXME: Would it make sense to try to "forget" the previous
846 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000847 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000848 }
849 }
850 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
851 // Maybe we will complain about the shadowed template parameter.
852 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
853 // Just pretend that we didn't see the previous declaration.
854 PrevDecl = 0;
855 } else if (PrevDecl) {
856 // C++ [temp]p5:
857 // A class template shall not have the same name as any other
858 // template, class, function, object, enumeration, enumerator,
859 // namespace, or type in the same scope (3.3), except as specified
860 // in (14.5.4).
861 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
862 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000863 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000864 }
865
Douglas Gregordba32632009-02-10 19:49:53 +0000866 // Check the template parameter list of this declaration, possibly
867 // merging in the template parameter list from the previous class
868 // template declaration.
869 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000870 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
871 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000872 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000873
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000874 if (SS.isSet()) {
875 // If the name of the template was qualified, we must be defining the
876 // template out-of-line.
877 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
878 !(TUK == TUK_Friend && CurContext->isDependentContext()))
879 Diag(NameLoc, diag::err_member_def_does_not_match)
880 << Name << SemanticContext << SS.getRange();
881 }
882
Mike Stump11289f42009-09-09 15:08:12 +0000883 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000884 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000885 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000886 PrevClassTemplate->getTemplatedDecl() : 0,
887 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000888 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000889
890 ClassTemplateDecl *NewTemplate
891 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
892 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000893 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000894 NewClass->setDescribedClassTemplate(NewTemplate);
895
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000896 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000897 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +0000898 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000899 assert(T->isDependentType() && "Class template type is not dependent?");
900 (void)T;
901
Douglas Gregorcf915552009-10-13 16:30:37 +0000902 // If we are providing an explicit specialization of a member that is a
903 // class template, make a note of that.
904 if (PrevClassTemplate &&
905 PrevClassTemplate->getInstantiatedFromMemberTemplate())
906 PrevClassTemplate->setMemberSpecialization();
907
Anders Carlsson137108d2009-03-26 01:24:28 +0000908 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000909 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000910 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000911
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000912 // Set the lexical context of these templates
913 NewClass->setLexicalDeclContext(CurContext);
914 NewTemplate->setLexicalDeclContext(CurContext);
915
John McCall9bb74a52009-07-31 02:45:11 +0000916 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000917 NewClass->startDefinition();
918
919 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000920 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000921
John McCall27b5c252009-09-14 21:59:20 +0000922 if (TUK != TUK_Friend)
923 PushOnScopeChains(NewTemplate, S);
924 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000925 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000926 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000927 NewClass->setAccess(PrevClassTemplate->getAccess());
928 }
John McCall27b5c252009-09-14 21:59:20 +0000929
Douglas Gregor3dad8422009-09-26 06:47:28 +0000930 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
931 PrevClassTemplate != NULL);
932
John McCall27b5c252009-09-14 21:59:20 +0000933 // Friend templates are visible in fairly strange ways.
934 if (!CurContext->isDependentContext()) {
935 DeclContext *DC = SemanticContext->getLookupContext();
936 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
937 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
938 PushOnScopeChains(NewTemplate, EnclosingScope,
939 /* AddToContext = */ false);
940 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000941
942 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
943 NewClass->getLocation(),
944 NewTemplate,
945 /*FIXME:*/NewClass->getLocation());
946 Friend->setAccess(AS_public);
947 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000948 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000949
Douglas Gregordba32632009-02-10 19:49:53 +0000950 if (Invalid) {
951 NewTemplate->setInvalidDecl();
952 NewClass->setInvalidDecl();
953 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000954 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000955}
956
Douglas Gregored5731f2009-11-25 17:50:39 +0000957/// \brief Diagnose the presence of a default template argument on a
958/// template parameter, which is ill-formed in certain contexts.
959///
960/// \returns true if the default template argument should be dropped.
961static bool DiagnoseDefaultTemplateArgument(Sema &S,
962 Sema::TemplateParamListContext TPC,
963 SourceLocation ParamLoc,
964 SourceRange DefArgRange) {
965 switch (TPC) {
966 case Sema::TPC_ClassTemplate:
967 return false;
968
969 case Sema::TPC_FunctionTemplate:
970 // C++ [temp.param]p9:
971 // A default template-argument shall not be specified in a
972 // function template declaration or a function template
973 // definition [...]
974 // (This sentence is not in C++0x, per DR226).
975 if (!S.getLangOptions().CPlusPlus0x)
976 S.Diag(ParamLoc,
977 diag::err_template_parameter_default_in_function_template)
978 << DefArgRange;
979 return false;
980
981 case Sema::TPC_ClassTemplateMember:
982 // C++0x [temp.param]p9:
983 // A default template-argument shall not be specified in the
984 // template-parameter-lists of the definition of a member of a
985 // class template that appears outside of the member's class.
986 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
987 << DefArgRange;
988 return true;
989
990 case Sema::TPC_FriendFunctionTemplate:
991 // C++ [temp.param]p9:
992 // A default template-argument shall not be specified in a
993 // friend template declaration.
994 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
995 << DefArgRange;
996 return true;
997
998 // FIXME: C++0x [temp.param]p9 allows default template-arguments
999 // for friend function templates if there is only a single
1000 // declaration (and it is a definition). Strange!
1001 }
1002
1003 return false;
1004}
1005
Douglas Gregordba32632009-02-10 19:49:53 +00001006/// \brief Checks the validity of a template parameter list, possibly
1007/// considering the template parameter list from a previous
1008/// declaration.
1009///
1010/// If an "old" template parameter list is provided, it must be
1011/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1012/// template parameter list.
1013///
1014/// \param NewParams Template parameter list for a new template
1015/// declaration. This template parameter list will be updated with any
1016/// default arguments that are carried through from the previous
1017/// template parameter list.
1018///
1019/// \param OldParams If provided, template parameter list from a
1020/// previous declaration of the same template. Default template
1021/// arguments will be merged from the old template parameter list to
1022/// the new template parameter list.
1023///
Douglas Gregored5731f2009-11-25 17:50:39 +00001024/// \param TPC Describes the context in which we are checking the given
1025/// template parameter list.
1026///
Douglas Gregordba32632009-02-10 19:49:53 +00001027/// \returns true if an error occurred, false otherwise.
1028bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001029 TemplateParameterList *OldParams,
1030 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001031 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001032
Douglas Gregordba32632009-02-10 19:49:53 +00001033 // C++ [temp.param]p10:
1034 // The set of default template-arguments available for use with a
1035 // template declaration or definition is obtained by merging the
1036 // default arguments from the definition (if in scope) and all
1037 // declarations in scope in the same way default function
1038 // arguments are (8.3.6).
1039 bool SawDefaultArgument = false;
1040 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001041
Anders Carlsson327865d2009-06-12 23:20:15 +00001042 bool SawParameterPack = false;
1043 SourceLocation ParameterPackLoc;
1044
Mike Stumpc89c8e32009-02-11 23:03:27 +00001045 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001046 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001047 if (OldParams)
1048 OldParam = OldParams->begin();
1049
1050 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1051 NewParamEnd = NewParams->end();
1052 NewParam != NewParamEnd; ++NewParam) {
1053 // Variables used to diagnose redundant default arguments
1054 bool RedundantDefaultArg = false;
1055 SourceLocation OldDefaultLoc;
1056 SourceLocation NewDefaultLoc;
1057
1058 // Variables used to diagnose missing default arguments
1059 bool MissingDefaultArg = false;
1060
Anders Carlsson327865d2009-06-12 23:20:15 +00001061 // C++0x [temp.param]p11:
1062 // If a template parameter of a class template is a template parameter pack,
1063 // it must be the last template parameter.
1064 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001065 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001066 diag::err_template_param_pack_must_be_last_template_parameter);
1067 Invalid = true;
1068 }
1069
Douglas Gregordba32632009-02-10 19:49:53 +00001070 if (TemplateTypeParmDecl *NewTypeParm
1071 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001072 // Check the presence of a default argument here.
1073 if (NewTypeParm->hasDefaultArgument() &&
1074 DiagnoseDefaultTemplateArgument(*this, TPC,
1075 NewTypeParm->getLocation(),
1076 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001077 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001078 NewTypeParm->removeDefaultArgument();
1079
1080 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001081 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001082 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001083
Anders Carlsson327865d2009-06-12 23:20:15 +00001084 if (NewTypeParm->isParameterPack()) {
1085 assert(!NewTypeParm->hasDefaultArgument() &&
1086 "Parameter packs can't have a default argument!");
1087 SawParameterPack = true;
1088 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001089 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001090 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001091 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1092 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1093 SawDefaultArgument = true;
1094 RedundantDefaultArg = true;
1095 PreviousDefaultArgLoc = NewDefaultLoc;
1096 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1097 // Merge the default argument from the old declaration to the
1098 // new declaration.
1099 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001100 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001101 true);
1102 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1103 } else if (NewTypeParm->hasDefaultArgument()) {
1104 SawDefaultArgument = true;
1105 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1106 } else if (SawDefaultArgument)
1107 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001108 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001109 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001110 // Check the presence of a default argument here.
1111 if (NewNonTypeParm->hasDefaultArgument() &&
1112 DiagnoseDefaultTemplateArgument(*this, TPC,
1113 NewNonTypeParm->getLocation(),
1114 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001115 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001116 }
1117
Mike Stump12b8ce12009-08-04 21:02:39 +00001118 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001119 NonTypeTemplateParmDecl *OldNonTypeParm
1120 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001121 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001122 NewNonTypeParm->hasDefaultArgument()) {
1123 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1124 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1125 SawDefaultArgument = true;
1126 RedundantDefaultArg = true;
1127 PreviousDefaultArgLoc = NewDefaultLoc;
1128 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1129 // Merge the default argument from the old declaration to the
1130 // new declaration.
1131 SawDefaultArgument = true;
1132 // FIXME: We need to create a new kind of "default argument"
1133 // expression that points to a previous template template
1134 // parameter.
1135 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001136 OldNonTypeParm->getDefaultArgument(),
1137 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001138 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1139 } else if (NewNonTypeParm->hasDefaultArgument()) {
1140 SawDefaultArgument = true;
1141 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1142 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001143 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001144 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001145 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001146 TemplateTemplateParmDecl *NewTemplateParm
1147 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001148 if (NewTemplateParm->hasDefaultArgument() &&
1149 DiagnoseDefaultTemplateArgument(*this, TPC,
1150 NewTemplateParm->getLocation(),
1151 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001152 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001153
1154 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001155 TemplateTemplateParmDecl *OldTemplateParm
1156 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001157 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001158 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001159 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1160 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001161 SawDefaultArgument = true;
1162 RedundantDefaultArg = true;
1163 PreviousDefaultArgLoc = NewDefaultLoc;
1164 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1165 // Merge the default argument from the old declaration to the
1166 // new declaration.
1167 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001168 // FIXME: We need to create a new kind of "default argument" expression
1169 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001170 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001171 OldTemplateParm->getDefaultArgument(),
1172 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001173 PreviousDefaultArgLoc
1174 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001175 } else if (NewTemplateParm->hasDefaultArgument()) {
1176 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001177 PreviousDefaultArgLoc
1178 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001179 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001180 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001181 }
1182
1183 if (RedundantDefaultArg) {
1184 // C++ [temp.param]p12:
1185 // A template-parameter shall not be given default arguments
1186 // by two different declarations in the same scope.
1187 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1188 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1189 Invalid = true;
1190 } else if (MissingDefaultArg) {
1191 // C++ [temp.param]p11:
1192 // If a template-parameter has a default template-argument,
1193 // all subsequent template-parameters shall have a default
1194 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001195 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001196 diag::err_template_param_default_arg_missing);
1197 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1198 Invalid = true;
1199 }
1200
1201 // If we have an old template parameter list that we're merging
1202 // in, move on to the next parameter.
1203 if (OldParams)
1204 ++OldParam;
1205 }
1206
1207 return Invalid;
1208}
Douglas Gregord32e0282009-02-09 23:23:08 +00001209
Mike Stump11289f42009-09-09 15:08:12 +00001210/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001211/// specifier, returning the template parameter list that applies to the
1212/// name.
1213///
1214/// \param DeclStartLoc the start of the declaration that has a scope
1215/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001216///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001217/// \param SS the scope specifier that will be matched to the given template
1218/// parameter lists. This scope specifier precedes a qualified name that is
1219/// being declared.
1220///
1221/// \param ParamLists the template parameter lists, from the outermost to the
1222/// innermost template parameter lists.
1223///
1224/// \param NumParamLists the number of template parameter lists in ParamLists.
1225///
John McCalle820e5e2010-04-13 20:37:33 +00001226/// \param IsFriend Whether to apply the slightly different rules for
1227/// matching template parameters to scope specifiers in friend
1228/// declarations.
1229///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001230/// \param IsExplicitSpecialization will be set true if the entity being
1231/// declared is an explicit specialization, false otherwise.
1232///
Mike Stump11289f42009-09-09 15:08:12 +00001233/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001234/// name that is preceded by the scope specifier @p SS. This template
1235/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001236/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001237/// template specialization), or may be NULL (if we were's declaring isn't
1238/// itself a template).
1239TemplateParameterList *
1240Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1241 const CXXScopeSpec &SS,
1242 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001243 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001244 bool IsFriend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001245 bool &IsExplicitSpecialization,
1246 bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001247 IsExplicitSpecialization = false;
1248
Douglas Gregord8d297c2009-07-21 23:53:31 +00001249 // Find the template-ids that occur within the nested-name-specifier. These
1250 // template-ids will match up with the template parameter lists.
1251 llvm::SmallVector<const TemplateSpecializationType *, 4>
1252 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001253 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1254 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001255 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1256 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001257 const Type *T = NNS->getAsType();
1258 if (!T) break;
1259
1260 // C++0x [temp.expl.spec]p17:
1261 // A member or a member template may be nested within many
1262 // enclosing class templates. In an explicit specialization for
1263 // such a member, the member declaration shall be preceded by a
1264 // template<> for each enclosing class template that is
1265 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001266 //
1267 // Following the existing practice of GNU and EDG, we allow a typedef of a
1268 // template specialization type.
1269 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1270 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001271
Mike Stump11289f42009-09-09 15:08:12 +00001272 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001273 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001274 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1275 if (!Template)
1276 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001277
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001278 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001279 ClassTemplateSpecializationDecl *SpecDecl
1280 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1281 // If the nested name specifier refers to an explicit specialization,
1282 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001283 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1284 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001285 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001286 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001287 }
Mike Stump11289f42009-09-09 15:08:12 +00001288
Douglas Gregord8d297c2009-07-21 23:53:31 +00001289 TemplateIdsInSpecifier.push_back(SpecType);
1290 }
1291 }
Mike Stump11289f42009-09-09 15:08:12 +00001292
Douglas Gregord8d297c2009-07-21 23:53:31 +00001293 // Reverse the list of template-ids in the scope specifier, so that we can
1294 // more easily match up the template-ids and the template parameter lists.
1295 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001296
Douglas Gregord8d297c2009-07-21 23:53:31 +00001297 SourceLocation FirstTemplateLoc = DeclStartLoc;
1298 if (NumParamLists)
1299 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001300
Douglas Gregord8d297c2009-07-21 23:53:31 +00001301 // Match the template-ids found in the specifier to the template parameter
1302 // lists.
1303 unsigned Idx = 0;
1304 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1305 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001306 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1307 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001308 if (Idx >= NumParamLists) {
1309 // We have a template-id without a corresponding template parameter
1310 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001311
1312 // ...which is fine if this is a friend declaration.
1313 if (IsFriend) {
1314 IsExplicitSpecialization = true;
1315 break;
1316 }
1317
Douglas Gregord8d297c2009-07-21 23:53:31 +00001318 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001319 // FIXME: the location information here isn't great.
1320 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001321 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001322 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001323 << SS.getRange();
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001324 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001325 } else {
1326 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1327 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001328 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001329 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001330 }
1331 return 0;
1332 }
Mike Stump11289f42009-09-09 15:08:12 +00001333
Douglas Gregord8d297c2009-07-21 23:53:31 +00001334 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001335 if (DependentTemplateId) {
John McCall2408e322010-04-27 00:57:59 +00001336 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00001337
John McCall2408e322010-04-27 00:57:59 +00001338 // Are there cases in (e.g.) friends where this won't match?
1339 if (const InjectedClassNameType *Injected
1340 = TemplateId->getAs<InjectedClassNameType>()) {
1341 CXXRecordDecl *Record = Injected->getDecl();
1342 if (ClassTemplatePartialSpecializationDecl *Partial =
1343 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1344 ExpectedTemplateParams = Partial->getTemplateParameters();
1345 else
1346 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1347 ->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001348 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001349
John McCall2408e322010-04-27 00:57:59 +00001350 if (ExpectedTemplateParams)
1351 TemplateParameterListsAreEqual(ParamLists[Idx],
1352 ExpectedTemplateParams,
1353 true, TPL_TemplateMatch);
1354
Douglas Gregored5731f2009-11-25 17:50:39 +00001355 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001356 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001357 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001358 diag::err_template_param_list_matches_nontemplate)
1359 << TemplateId
1360 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001361 else
1362 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001363 }
Mike Stump11289f42009-09-09 15:08:12 +00001364
Douglas Gregord8d297c2009-07-21 23:53:31 +00001365 // If there were at least as many template-ids as there were template
1366 // parameter lists, then there are no template parameter lists remaining for
1367 // the declaration itself.
1368 if (Idx >= NumParamLists)
1369 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001370
Douglas Gregord8d297c2009-07-21 23:53:31 +00001371 // If there were too many template parameter lists, complain about that now.
1372 if (Idx != NumParamLists - 1) {
1373 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001374 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001375 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001376 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1377 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001378 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1379 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001380
1381 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1382 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1383 diag::note_explicit_template_spec_does_not_need_header)
1384 << ExplicitSpecializationsInSpecifier.back();
1385 ExplicitSpecializationsInSpecifier.pop_back();
1386 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001387
1388 // We have a template parameter list with no corresponding scope, which
1389 // means that the resulting template declaration can't be instantiated
1390 // properly (we'll end up with dependent nodes when we shouldn't).
1391 if (!isExplicitSpecHeader)
1392 Invalid = true;
1393
Douglas Gregord8d297c2009-07-21 23:53:31 +00001394 ++Idx;
1395 }
1396 }
Mike Stump11289f42009-09-09 15:08:12 +00001397
Douglas Gregord8d297c2009-07-21 23:53:31 +00001398 // Return the last template parameter list, which corresponds to the
1399 // entity being declared.
1400 return ParamLists[NumParamLists - 1];
1401}
1402
Douglas Gregordc572a32009-03-30 22:58:21 +00001403QualType Sema::CheckTemplateIdType(TemplateName Name,
1404 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001405 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001406 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001407 if (!Template) {
1408 // The template name does not resolve to a template, so we just
1409 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001410 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001411 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001412
Douglas Gregorc40290e2009-03-09 23:48:35 +00001413 // Check that the template argument list is well-formed for this
1414 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001415 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001416 TemplateArgs.size());
1417 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001418 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001419 return QualType();
1420
Mike Stump11289f42009-09-09 15:08:12 +00001421 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001422 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001423 "Converted template argument list is too short!");
1424
1425 QualType CanonType;
1426
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001427 if (Name.isDependent() ||
1428 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001429 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001430 // This class template specialization is a dependent
1431 // type. Therefore, its canonical type is another class template
1432 // specialization type that contains all of the converted
1433 // arguments in canonical form. This ensures that, e.g., A<T> and
1434 // A<T, T> have identical types when A is declared as:
1435 //
1436 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001437 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001438 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001439 Converted.getFlatArguments(),
1440 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001441
Douglas Gregora8e02e72009-07-28 23:00:59 +00001442 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001443 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001444 // In the future, we need to teach getTemplateSpecializationType to only
1445 // build the canonical type and return that to us.
1446 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001447
1448 // This might work out to be a current instantiation, in which
1449 // case the canonical type needs to be the InjectedClassNameType.
1450 //
1451 // TODO: in theory this could be a simple hashtable lookup; most
1452 // changes to CurContext don't change the set of current
1453 // instantiations.
1454 if (isa<ClassTemplateDecl>(Template)) {
1455 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1456 // If we get out to a namespace, we're done.
1457 if (Ctx->isFileContext()) break;
1458
1459 // If this isn't a record, keep looking.
1460 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1461 if (!Record) continue;
1462
1463 // Look for one of the two cases with InjectedClassNameTypes
1464 // and check whether it's the same template.
1465 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1466 !Record->getDescribedClassTemplate())
1467 continue;
1468
1469 // Fetch the injected class name type and check whether its
1470 // injected type is equal to the type we just built.
1471 QualType ICNT = Context.getTypeDeclType(Record);
1472 QualType Injected = cast<InjectedClassNameType>(ICNT)
1473 ->getInjectedSpecializationType();
1474
1475 if (CanonType != Injected->getCanonicalTypeInternal())
1476 continue;
1477
1478 // If so, the canonical type of this TST is the injected
1479 // class name type of the record we just found.
1480 assert(ICNT.isCanonical());
1481 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00001482 break;
1483 }
1484 }
Mike Stump11289f42009-09-09 15:08:12 +00001485 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001486 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001487 // Find the class template specialization declaration that
1488 // corresponds to these arguments.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001489 void *InsertPos = 0;
1490 ClassTemplateSpecializationDecl *Decl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001491 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
1492 Converted.flatSize(), InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001493 if (!Decl) {
1494 // This is the first time we have referenced this class template
1495 // specialization. Create the canonical declaration and add it to
1496 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001497 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001498 ClassTemplate->getTemplatedDecl()->getTagKind(),
1499 ClassTemplate->getDeclContext(),
1500 ClassTemplate->getLocation(),
1501 ClassTemplate,
1502 Converted, 0);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001503 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001504 Decl->setLexicalDeclContext(CurContext);
1505 }
1506
1507 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001508 assert(isa<RecordType>(CanonType) &&
1509 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001510 }
Mike Stump11289f42009-09-09 15:08:12 +00001511
Douglas Gregorc40290e2009-03-09 23:48:35 +00001512 // Build the fully-sugared type for this class template
1513 // specialization, which refers back to the class template
1514 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00001515 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001516}
1517
Douglas Gregor67a65642009-02-17 23:15:12 +00001518Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001519Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001520 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001521 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001522 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001523 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001524
Douglas Gregorc40290e2009-03-09 23:48:35 +00001525 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001526 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001527 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001528
John McCall6b51f282009-11-23 01:53:49 +00001529 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001530 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001531
1532 if (Result.isNull())
1533 return true;
1534
John McCallbcd03502009-12-07 02:54:59 +00001535 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001536 TemplateSpecializationTypeLoc TL
1537 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1538 TL.setTemplateNameLoc(TemplateLoc);
1539 TL.setLAngleLoc(LAngleLoc);
1540 TL.setRAngleLoc(RAngleLoc);
1541 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1542 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1543
1544 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001545}
John McCall06f6fe8d2009-09-04 01:14:41 +00001546
John McCalld8fe9af2009-09-08 17:47:29 +00001547Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1548 TagUseKind TUK,
1549 DeclSpec::TST TagSpec,
1550 SourceLocation TagLoc) {
1551 if (TypeResult.isInvalid())
1552 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001553
John McCall0ad16662009-10-29 08:12:44 +00001554 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001555 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001556 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001557
John McCalld8fe9af2009-09-08 17:47:29 +00001558 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001559 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001560
John McCalld8fe9af2009-09-08 17:47:29 +00001561 if (const RecordType *RT = Type->getAs<RecordType>()) {
1562 RecordDecl *D = RT->getDecl();
1563
1564 IdentifierInfo *Id = D->getIdentifier();
1565 assert(Id && "templated class must have an identifier");
1566
1567 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1568 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001569 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001570 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001571 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001572 }
1573 }
1574
Abramo Bagnara6150c882010-05-11 21:36:43 +00001575 ElaboratedTypeKeyword Keyword
1576 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1577 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001578
1579 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001580}
1581
John McCalle66edc12009-11-24 19:00:30 +00001582Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1583 LookupResult &R,
1584 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001585 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001586 // FIXME: Can we do any checking at this point? I guess we could check the
1587 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001588 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001589 // though.
John McCalle66edc12009-11-24 19:00:30 +00001590
1591 // These should be filtered out by our callers.
1592 assert(!R.empty() && "empty lookup results when building templateid");
1593 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1594
1595 NestedNameSpecifier *Qualifier = 0;
1596 SourceRange QualifierRange;
1597 if (SS.isSet()) {
1598 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1599 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001600 }
John McCall58cc69d2010-01-27 01:50:18 +00001601
1602 // We don't want lookup warnings at this point.
1603 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001604
John McCalle66edc12009-11-24 19:00:30 +00001605 bool Dependent
1606 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1607 &TemplateArgs);
1608 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001609 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001610 Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001611 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001612 RequiresADL, TemplateArgs,
1613 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001614
1615 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001616}
1617
John McCalle66edc12009-11-24 19:00:30 +00001618// We actually only call this from template instantiation.
1619Sema::OwningExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001620Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001621 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +00001622 const TemplateArgumentListInfo &TemplateArgs) {
1623 DeclContext *DC;
1624 if (!(DC = computeDeclContext(SS, false)) ||
1625 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001626 RequireCompleteDeclContext(SS, DC))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001627 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001628
Douglas Gregor786123d2010-05-21 23:18:07 +00001629 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001630 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00001631 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1632 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00001633
John McCalle66edc12009-11-24 19:00:30 +00001634 if (R.isAmbiguous())
1635 return ExprError();
1636
1637 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001638 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1639 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001640 return ExprError();
1641 }
1642
1643 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001644 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1645 << (NestedNameSpecifier*) SS.getScopeRep()
1646 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001647 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1648 return ExprError();
1649 }
1650
1651 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001652}
1653
Douglas Gregorb67535d2009-03-31 00:43:58 +00001654/// \brief Form a dependent template name.
1655///
1656/// This action forms a dependent template name given the template
1657/// name and its (presumably dependent) scope specifier. For
1658/// example, given "MetaFun::template apply", the scope specifier \p
1659/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1660/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregorbb119652010-06-16 23:00:59 +00001661TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1662 SourceLocation TemplateKWLoc,
1663 CXXScopeSpec &SS,
1664 UnqualifiedId &Name,
1665 TypeTy *ObjectType,
1666 bool EnteringContext,
1667 TemplateTy &Result) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00001668 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1669 !getLangOptions().CPlusPlus0x)
1670 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1671 << FixItHint::CreateRemoval(TemplateKWLoc);
1672
Douglas Gregor9abe2372010-01-19 16:01:07 +00001673 DeclContext *LookupCtx = 0;
1674 if (SS.isSet())
1675 LookupCtx = computeDeclContext(SS, EnteringContext);
1676 if (!LookupCtx && ObjectType)
1677 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1678 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001679 // C++0x [temp.names]p5:
1680 // If a name prefixed by the keyword template is not the name of
1681 // a template, the program is ill-formed. [Note: the keyword
1682 // template may not be applied to non-template members of class
1683 // templates. -end note ] [ Note: as is the case with the
1684 // typename prefix, the template prefix is allowed in cases
1685 // where it is not strictly necessary; i.e., when the
1686 // nested-name-specifier or the expression on the left of the ->
1687 // or . is not dependent on a template-parameter, or the use
1688 // does not appear in the scope of a template. -end note]
1689 //
1690 // Note: C++03 was more strict here, because it banned the use of
1691 // the "template" keyword prior to a template-name that was not a
1692 // dependent name. C++ DR468 relaxed this requirement (the
1693 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00001694 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00001695 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001696 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1697 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00001698 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001699 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1700 isa<CXXRecordDecl>(LookupCtx) &&
1701 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregorbb119652010-06-16 23:00:59 +00001702 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00001703 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001704 Diag(Name.getSourceRange().getBegin(),
1705 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001706 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001707 << Name.getSourceRange()
1708 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001709 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00001710 } else {
1711 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00001712 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001713 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001714 }
1715
Mike Stump11289f42009-09-09 15:08:12 +00001716 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001717 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001718
1719 switch (Name.getKind()) {
1720 case UnqualifiedId::IK_Identifier:
Douglas Gregorbb119652010-06-16 23:00:59 +00001721 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1722 Name.Identifier));
1723 return TNK_Dependent_template_name;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001724
Douglas Gregor71395fa2009-11-04 00:56:37 +00001725 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00001726 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00001727 Name.OperatorFunctionId.Operator));
Douglas Gregorbb119652010-06-16 23:00:59 +00001728 return TNK_Dependent_template_name;
Alexis Hunted0530f2009-11-28 08:58:14 +00001729
1730 case UnqualifiedId::IK_LiteralOperatorId:
1731 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1732
Douglas Gregor3cf81312009-11-03 23:16:33 +00001733 default:
1734 break;
1735 }
1736
1737 Diag(Name.getSourceRange().getBegin(),
1738 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001739 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001740 << Name.getSourceRange()
1741 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001742 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001743}
1744
Mike Stump11289f42009-09-09 15:08:12 +00001745bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001746 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001747 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001748 const TemplateArgument &Arg = AL.getArgument();
1749
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001750 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001751 switch(Arg.getKind()) {
1752 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001753 // C++ [temp.arg.type]p1:
1754 // A template-argument for a template-parameter which is a
1755 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001756 break;
1757 case TemplateArgument::Template: {
1758 // We have a template type parameter but the template argument
1759 // is a template without any arguments.
1760 SourceRange SR = AL.getSourceRange();
1761 TemplateName Name = Arg.getAsTemplate();
1762 Diag(SR.getBegin(), diag::err_template_missing_args)
1763 << Name << SR;
1764 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1765 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001766
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001767 return true;
1768 }
1769 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001770 // We have a template type parameter but the template argument
1771 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001772 SourceRange SR = AL.getSourceRange();
1773 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001774 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001775
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001776 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001777 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001778 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001779
John McCallbcd03502009-12-07 02:54:59 +00001780 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001781 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001782
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001783 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001784 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001785 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001786 return false;
1787}
1788
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001789/// \brief Substitute template arguments into the default template argument for
1790/// the given template type parameter.
1791///
1792/// \param SemaRef the semantic analysis object for which we are performing
1793/// the substitution.
1794///
1795/// \param Template the template that we are synthesizing template arguments
1796/// for.
1797///
1798/// \param TemplateLoc the location of the template name that started the
1799/// template-id we are checking.
1800///
1801/// \param RAngleLoc the location of the right angle bracket ('>') that
1802/// terminates the template-id.
1803///
1804/// \param Param the template template parameter whose default we are
1805/// substituting into.
1806///
1807/// \param Converted the list of template arguments provided for template
1808/// parameters that precede \p Param in the template parameter list.
1809///
1810/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001811static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001812SubstDefaultTemplateArgument(Sema &SemaRef,
1813 TemplateDecl *Template,
1814 SourceLocation TemplateLoc,
1815 SourceLocation RAngleLoc,
1816 TemplateTypeParmDecl *Param,
1817 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001818 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001819
1820 // If the argument type is dependent, instantiate it now based
1821 // on the previously-computed template arguments.
1822 if (ArgType->getType()->isDependentType()) {
1823 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1824 /*TakeArgs=*/false);
1825
1826 MultiLevelTemplateArgumentList AllTemplateArgs
1827 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1828
1829 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1830 Template, Converted.getFlatArguments(),
1831 Converted.flatSize(),
1832 SourceRange(TemplateLoc, RAngleLoc));
1833
1834 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1835 Param->getDefaultArgumentLoc(),
1836 Param->getDeclName());
1837 }
1838
1839 return ArgType;
1840}
1841
1842/// \brief Substitute template arguments into the default template argument for
1843/// the given non-type template parameter.
1844///
1845/// \param SemaRef the semantic analysis object for which we are performing
1846/// the substitution.
1847///
1848/// \param Template the template that we are synthesizing template arguments
1849/// for.
1850///
1851/// \param TemplateLoc the location of the template name that started the
1852/// template-id we are checking.
1853///
1854/// \param RAngleLoc the location of the right angle bracket ('>') that
1855/// terminates the template-id.
1856///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001857/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001858/// substituting into.
1859///
1860/// \param Converted the list of template arguments provided for template
1861/// parameters that precede \p Param in the template parameter list.
1862///
1863/// \returns the substituted template argument, or NULL if an error occurred.
1864static Sema::OwningExprResult
1865SubstDefaultTemplateArgument(Sema &SemaRef,
1866 TemplateDecl *Template,
1867 SourceLocation TemplateLoc,
1868 SourceLocation RAngleLoc,
1869 NonTypeTemplateParmDecl *Param,
1870 TemplateArgumentListBuilder &Converted) {
1871 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1872 /*TakeArgs=*/false);
1873
1874 MultiLevelTemplateArgumentList AllTemplateArgs
1875 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1876
1877 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1878 Template, Converted.getFlatArguments(),
1879 Converted.flatSize(),
1880 SourceRange(TemplateLoc, RAngleLoc));
1881
1882 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1883}
1884
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001885/// \brief Substitute template arguments into the default template argument for
1886/// the given template template parameter.
1887///
1888/// \param SemaRef the semantic analysis object for which we are performing
1889/// the substitution.
1890///
1891/// \param Template the template that we are synthesizing template arguments
1892/// for.
1893///
1894/// \param TemplateLoc the location of the template name that started the
1895/// template-id we are checking.
1896///
1897/// \param RAngleLoc the location of the right angle bracket ('>') that
1898/// terminates the template-id.
1899///
1900/// \param Param the template template parameter whose default we are
1901/// substituting into.
1902///
1903/// \param Converted the list of template arguments provided for template
1904/// parameters that precede \p Param in the template parameter list.
1905///
1906/// \returns the substituted template argument, or NULL if an error occurred.
1907static TemplateName
1908SubstDefaultTemplateArgument(Sema &SemaRef,
1909 TemplateDecl *Template,
1910 SourceLocation TemplateLoc,
1911 SourceLocation RAngleLoc,
1912 TemplateTemplateParmDecl *Param,
1913 TemplateArgumentListBuilder &Converted) {
1914 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1915 /*TakeArgs=*/false);
1916
1917 MultiLevelTemplateArgumentList AllTemplateArgs
1918 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1919
1920 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1921 Template, Converted.getFlatArguments(),
1922 Converted.flatSize(),
1923 SourceRange(TemplateLoc, RAngleLoc));
1924
1925 return SemaRef.SubstTemplateName(
1926 Param->getDefaultArgument().getArgument().getAsTemplate(),
1927 Param->getDefaultArgument().getTemplateNameLoc(),
1928 AllTemplateArgs);
1929}
1930
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001931/// \brief If the given template parameter has a default template
1932/// argument, substitute into that default template argument and
1933/// return the corresponding template argument.
1934TemplateArgumentLoc
1935Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1936 SourceLocation TemplateLoc,
1937 SourceLocation RAngleLoc,
1938 Decl *Param,
1939 TemplateArgumentListBuilder &Converted) {
1940 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1941 if (!TypeParm->hasDefaultArgument())
1942 return TemplateArgumentLoc();
1943
John McCallbcd03502009-12-07 02:54:59 +00001944 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001945 TemplateLoc,
1946 RAngleLoc,
1947 TypeParm,
1948 Converted);
1949 if (DI)
1950 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1951
1952 return TemplateArgumentLoc();
1953 }
1954
1955 if (NonTypeTemplateParmDecl *NonTypeParm
1956 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1957 if (!NonTypeParm->hasDefaultArgument())
1958 return TemplateArgumentLoc();
1959
1960 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1961 TemplateLoc,
1962 RAngleLoc,
1963 NonTypeParm,
1964 Converted);
1965 if (Arg.isInvalid())
1966 return TemplateArgumentLoc();
1967
1968 Expr *ArgE = Arg.takeAs<Expr>();
1969 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1970 }
1971
1972 TemplateTemplateParmDecl *TempTempParm
1973 = cast<TemplateTemplateParmDecl>(Param);
1974 if (!TempTempParm->hasDefaultArgument())
1975 return TemplateArgumentLoc();
1976
1977 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1978 TemplateLoc,
1979 RAngleLoc,
1980 TempTempParm,
1981 Converted);
1982 if (TName.isNull())
1983 return TemplateArgumentLoc();
1984
1985 return TemplateArgumentLoc(TemplateArgument(TName),
1986 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1987 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1988}
1989
Douglas Gregorda0fb532009-11-11 19:31:23 +00001990/// \brief Check that the given template argument corresponds to the given
1991/// template parameter.
1992bool Sema::CheckTemplateArgument(NamedDecl *Param,
1993 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001994 TemplateDecl *Template,
1995 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001996 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001997 TemplateArgumentListBuilder &Converted,
1998 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001999 // Check template type parameters.
2000 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002001 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002002
Douglas Gregoreebed722009-11-11 19:41:09 +00002003 // Check non-type template parameters.
2004 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00002005 // Do substitution on the type of the non-type template parameter
2006 // with the template arguments we've seen thus far.
2007 QualType NTTPType = NTTP->getType();
2008 if (NTTPType->isDependentType()) {
2009 // Do substitution on the type of the non-type template parameter.
2010 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2011 NTTP, Converted.getFlatArguments(),
2012 Converted.flatSize(),
2013 SourceRange(TemplateLoc, RAngleLoc));
2014
2015 TemplateArgumentList TemplateArgs(Context, Converted,
2016 /*TakeArgs=*/false);
2017 NTTPType = SubstType(NTTPType,
2018 MultiLevelTemplateArgumentList(TemplateArgs),
2019 NTTP->getLocation(),
2020 NTTP->getDeclName());
2021 // If that worked, check the non-type template parameter type
2022 // for validity.
2023 if (!NTTPType.isNull())
2024 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2025 NTTP->getLocation());
2026 if (NTTPType.isNull())
2027 return true;
2028 }
2029
2030 switch (Arg.getArgument().getKind()) {
2031 case TemplateArgument::Null:
2032 assert(false && "Should never see a NULL template argument here");
2033 return true;
2034
2035 case TemplateArgument::Expression: {
2036 Expr *E = Arg.getArgument().getAsExpr();
2037 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002038 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002039 return true;
2040
2041 Converted.Append(Result);
2042 break;
2043 }
2044
2045 case TemplateArgument::Declaration:
2046 case TemplateArgument::Integral:
2047 // We've already checked this template argument, so just copy
2048 // it to the list of converted arguments.
2049 Converted.Append(Arg.getArgument());
2050 break;
2051
2052 case TemplateArgument::Template:
2053 // We were given a template template argument. It may not be ill-formed;
2054 // see below.
2055 if (DependentTemplateName *DTN
2056 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2057 // We have a template argument such as \c T::template X, which we
2058 // parsed as a template template argument. However, since we now
2059 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002060 // template name into an expression.
2061
2062 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2063 Arg.getTemplateNameLoc());
2064
John McCalle66edc12009-11-24 19:00:30 +00002065 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2066 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002067 Arg.getTemplateQualifierRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002068 NameInfo);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002069
2070 TemplateArgument Result;
2071 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2072 return true;
2073
2074 Converted.Append(Result);
2075 break;
2076 }
2077
2078 // We have a template argument that actually does refer to a class
2079 // template, template alias, or template template parameter, and
2080 // therefore cannot be a non-type template argument.
2081 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2082 << Arg.getSourceRange();
2083
2084 Diag(Param->getLocation(), diag::note_template_param_here);
2085 return true;
2086
2087 case TemplateArgument::Type: {
2088 // We have a non-type template parameter but the template
2089 // argument is a type.
2090
2091 // C++ [temp.arg]p2:
2092 // In a template-argument, an ambiguity between a type-id and
2093 // an expression is resolved to a type-id, regardless of the
2094 // form of the corresponding template-parameter.
2095 //
2096 // We warn specifically about this case, since it can be rather
2097 // confusing for users.
2098 QualType T = Arg.getArgument().getAsType();
2099 SourceRange SR = Arg.getSourceRange();
2100 if (T->isFunctionType())
2101 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2102 else
2103 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2104 Diag(Param->getLocation(), diag::note_template_param_here);
2105 return true;
2106 }
2107
2108 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002109 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002110 break;
2111 }
2112
2113 return false;
2114 }
2115
2116
2117 // Check template template parameters.
2118 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2119
2120 // Substitute into the template parameter list of the template
2121 // template parameter, since previously-supplied template arguments
2122 // may appear within the template template parameter.
2123 {
2124 // Set up a template instantiation context.
2125 LocalInstantiationScope Scope(*this);
2126 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2127 TempParm, Converted.getFlatArguments(),
2128 Converted.flatSize(),
2129 SourceRange(TemplateLoc, RAngleLoc));
2130
2131 TemplateArgumentList TemplateArgs(Context, Converted,
2132 /*TakeArgs=*/false);
2133 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2134 SubstDecl(TempParm, CurContext,
2135 MultiLevelTemplateArgumentList(TemplateArgs)));
2136 if (!TempParm)
2137 return true;
2138
2139 // FIXME: TempParam is leaked.
2140 }
2141
2142 switch (Arg.getArgument().getKind()) {
2143 case TemplateArgument::Null:
2144 assert(false && "Should never see a NULL template argument here");
2145 return true;
2146
2147 case TemplateArgument::Template:
2148 if (CheckTemplateArgument(TempParm, Arg))
2149 return true;
2150
2151 Converted.Append(Arg.getArgument());
2152 break;
2153
2154 case TemplateArgument::Expression:
2155 case TemplateArgument::Type:
2156 // We have a template template parameter but the template
2157 // argument does not refer to a template.
2158 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2159 return true;
2160
2161 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002162 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002163 "Declaration argument with template template parameter");
2164 break;
2165 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002166 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002167 "Integral argument with template template parameter");
2168 break;
2169
2170 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002171 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002172 break;
2173 }
2174
2175 return false;
2176}
2177
Douglas Gregord32e0282009-02-09 23:23:08 +00002178/// \brief Check that the given template argument list is well-formed
2179/// for specializing the given template.
2180bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2181 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002182 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002183 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002184 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002185 TemplateParameterList *Params = Template->getTemplateParameters();
2186 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002187 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002188 bool Invalid = false;
2189
John McCall6b51f282009-11-23 01:53:49 +00002190 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2191
Mike Stump11289f42009-09-09 15:08:12 +00002192 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002193 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002194
Anders Carlsson15201f12009-06-13 02:08:00 +00002195 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002196 (NumArgs < Params->getMinRequiredArguments() &&
2197 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002198 // FIXME: point at either the first arg beyond what we can handle,
2199 // or the '>', depending on whether we have too many or too few
2200 // arguments.
2201 SourceRange Range;
2202 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002203 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002204 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2205 << (NumArgs > NumParams)
2206 << (isa<ClassTemplateDecl>(Template)? 0 :
2207 isa<FunctionTemplateDecl>(Template)? 1 :
2208 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2209 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002210 Diag(Template->getLocation(), diag::note_template_decl_here)
2211 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002212 Invalid = true;
2213 }
Mike Stump11289f42009-09-09 15:08:12 +00002214
2215 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002216 // [...] The type and form of each template-argument specified in
2217 // a template-id shall match the type and form specified for the
2218 // corresponding parameter declared by the template in its
2219 // template-parameter-list.
2220 unsigned ArgIdx = 0;
2221 for (TemplateParameterList::iterator Param = Params->begin(),
2222 ParamEnd = Params->end();
2223 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002224 if (ArgIdx > NumArgs && PartialTemplateArgs)
2225 break;
Mike Stump11289f42009-09-09 15:08:12 +00002226
Douglas Gregoreebed722009-11-11 19:41:09 +00002227 // If we have a template parameter pack, check every remaining template
2228 // argument against that template parameter pack.
2229 if ((*Param)->isTemplateParameterPack()) {
2230 Converted.BeginPack();
2231 for (; ArgIdx < NumArgs; ++ArgIdx) {
2232 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2233 TemplateLoc, RAngleLoc, Converted)) {
2234 Invalid = true;
2235 break;
2236 }
2237 }
2238 Converted.EndPack();
2239 continue;
2240 }
2241
Douglas Gregor84d49a22009-11-11 21:54:23 +00002242 if (ArgIdx < NumArgs) {
2243 // Check the template argument we were given.
2244 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2245 TemplateLoc, RAngleLoc, Converted))
2246 return true;
2247
2248 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002249 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002250
Douglas Gregor84d49a22009-11-11 21:54:23 +00002251 // We have a default template argument that we will use.
2252 TemplateArgumentLoc Arg;
2253
2254 // Retrieve the default template argument from the template
2255 // parameter. For each kind of template parameter, we substitute the
2256 // template arguments provided thus far and any "outer" template arguments
2257 // (when the template parameter was part of a nested template) into
2258 // the default argument.
2259 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2260 if (!TTP->hasDefaultArgument()) {
2261 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2262 break;
2263 }
2264
John McCallbcd03502009-12-07 02:54:59 +00002265 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002266 Template,
2267 TemplateLoc,
2268 RAngleLoc,
2269 TTP,
2270 Converted);
2271 if (!ArgType)
2272 return true;
2273
2274 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2275 ArgType);
2276 } else if (NonTypeTemplateParmDecl *NTTP
2277 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2278 if (!NTTP->hasDefaultArgument()) {
2279 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2280 break;
2281 }
2282
2283 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2284 TemplateLoc,
2285 RAngleLoc,
2286 NTTP,
2287 Converted);
2288 if (E.isInvalid())
2289 return true;
2290
2291 Expr *Ex = E.takeAs<Expr>();
2292 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2293 } else {
2294 TemplateTemplateParmDecl *TempParm
2295 = cast<TemplateTemplateParmDecl>(*Param);
2296
2297 if (!TempParm->hasDefaultArgument()) {
2298 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2299 break;
2300 }
2301
2302 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2303 TemplateLoc,
2304 RAngleLoc,
2305 TempParm,
2306 Converted);
2307 if (Name.isNull())
2308 return true;
2309
2310 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2311 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2312 TempParm->getDefaultArgument().getTemplateNameLoc());
2313 }
2314
2315 // Introduce an instantiation record that describes where we are using
2316 // the default template argument.
2317 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2318 Converted.getFlatArguments(),
2319 Converted.flatSize(),
2320 SourceRange(TemplateLoc, RAngleLoc));
2321
2322 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002323 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002324 RAngleLoc, Converted))
2325 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002326 }
2327
2328 return Invalid;
2329}
2330
2331/// \brief Check a template argument against its corresponding
2332/// template type parameter.
2333///
2334/// This routine implements the semantics of C++ [temp.arg.type]. It
2335/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002336bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002337 TypeSourceInfo *ArgInfo) {
2338 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002339 QualType Arg = ArgInfo->getType();
2340
Douglas Gregord32e0282009-02-09 23:23:08 +00002341 // C++ [temp.arg.type]p2:
2342 // A local type, a type with no linkage, an unnamed type or a type
2343 // compounded from any of these types shall not be used as a
2344 // template-argument for a template type-parameter.
2345 //
Douglas Gregor959d5a02010-05-22 16:17:30 +00002346 // FIXME: Perform the unnamed type check.
2347 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002348 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002349 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002350 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002351 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002352 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002353 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002354 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall0ad16662009-10-29 08:12:44 +00002355 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2356 << QualType(Tag, 0) << SR;
2357 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002358 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002359 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002360 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2361 return true;
Douglas Gregor959d5a02010-05-22 16:17:30 +00002362 } else if (Arg->isVariablyModifiedType()) {
2363 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2364 << Arg;
2365 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002366 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002367 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002368 }
2369
2370 return false;
2371}
2372
Douglas Gregorccb07762009-02-11 19:52:55 +00002373/// \brief Checks whether the given template argument is the address
2374/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002375static bool
2376CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2377 NonTypeTemplateParmDecl *Param,
2378 QualType ParamType,
2379 Expr *ArgIn,
2380 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002381 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002382 Expr *Arg = ArgIn;
2383 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002384
2385 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002386 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002387 Arg = Cast->getSubExpr();
2388
2389 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002390 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002391 // A template-argument for a non-type, non-template
2392 // template-parameter shall be one of: [...]
2393 //
2394 // -- the address of an object or function with external
2395 // linkage, including function templates and function
2396 // template-ids but excluding non-static class members,
2397 // expressed as & id-expression where the & is optional if
2398 // the name refers to a function or array, or if the
2399 // corresponding template-parameter is a reference; or
2400 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002401
Douglas Gregorccb07762009-02-11 19:52:55 +00002402 // Ignore (and complain about) any excess parentheses.
2403 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2404 if (!Invalid) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002405 S.Diag(Arg->getSourceRange().getBegin(),
2406 diag::err_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002407 << Arg->getSourceRange();
2408 Invalid = true;
2409 }
2410
2411 Arg = Parens->getSubExpr();
2412 }
2413
Douglas Gregorb242683d2010-04-01 18:32:35 +00002414 bool AddressTaken = false;
2415 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002416 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002417 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002418 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002419 AddressTaken = true;
2420 AddrOpLoc = UnOp->getOperatorLoc();
2421 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002422 } else
2423 DRE = dyn_cast<DeclRefExpr>(Arg);
2424
Douglas Gregorb242683d2010-04-01 18:32:35 +00002425 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002426 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2427 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002428 S.Diag(Param->getLocation(), diag::note_template_param_here);
2429 return true;
2430 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002431
2432 // Stop checking the precise nature of the argument if it is value dependent,
2433 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002434 if (Arg->isValueDependent()) {
2435 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002436 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002437 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002438
Douglas Gregorb242683d2010-04-01 18:32:35 +00002439 if (!isa<ValueDecl>(DRE->getDecl())) {
2440 S.Diag(Arg->getSourceRange().getBegin(),
2441 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002442 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002443 S.Diag(Param->getLocation(), diag::note_template_param_here);
2444 return true;
2445 }
2446
2447 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002448
2449 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002450 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2451 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002452 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002453 S.Diag(Param->getLocation(), diag::note_template_param_here);
2454 return true;
2455 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002456
2457 // Cannot refer to non-static member functions
2458 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002459 if (!Method->isStatic()) {
2460 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002461 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002462 S.Diag(Param->getLocation(), diag::note_template_param_here);
2463 return true;
2464 }
Mike Stump11289f42009-09-09 15:08:12 +00002465
Douglas Gregorccb07762009-02-11 19:52:55 +00002466 // Functions must have external linkage.
2467 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002468 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002469 S.Diag(Arg->getSourceRange().getBegin(),
2470 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002471 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002472 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002473 << true;
2474 return true;
2475 }
2476
2477 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002478 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002479
Douglas Gregorb242683d2010-04-01 18:32:35 +00002480 // If the template parameter has pointer type, the function decays.
2481 if (ParamType->isPointerType() && !AddressTaken)
2482 ArgType = S.Context.getPointerType(Func->getType());
2483 else if (AddressTaken && ParamType->isReferenceType()) {
2484 // If we originally had an address-of operator, but the
2485 // parameter has reference type, complain and (if things look
2486 // like they will work) drop the address-of operator.
2487 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2488 ParamType.getNonReferenceType())) {
2489 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2490 << ParamType;
2491 S.Diag(Param->getLocation(), diag::note_template_param_here);
2492 return true;
2493 }
2494
2495 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2496 << ParamType
2497 << FixItHint::CreateRemoval(AddrOpLoc);
2498 S.Diag(Param->getLocation(), diag::note_template_param_here);
2499
2500 ArgType = Func->getType();
2501 }
2502 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002503 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002504 S.Diag(Arg->getSourceRange().getBegin(),
2505 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002506 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002507 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002508 << true;
2509 return true;
2510 }
2511
Douglas Gregorb242683d2010-04-01 18:32:35 +00002512 // A value of reference type is not an object.
2513 if (Var->getType()->isReferenceType()) {
2514 S.Diag(Arg->getSourceRange().getBegin(),
2515 diag::err_template_arg_reference_var)
2516 << Var->getType() << Arg->getSourceRange();
2517 S.Diag(Param->getLocation(), diag::note_template_param_here);
2518 return true;
2519 }
2520
Douglas Gregorccb07762009-02-11 19:52:55 +00002521 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002522 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002523
2524 // If the template parameter has pointer type, we must have taken
2525 // the address of this object.
2526 if (ParamType->isReferenceType()) {
2527 if (AddressTaken) {
2528 // If we originally had an address-of operator, but the
2529 // parameter has reference type, complain and (if things look
2530 // like they will work) drop the address-of operator.
2531 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2532 ParamType.getNonReferenceType())) {
2533 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2534 << ParamType;
2535 S.Diag(Param->getLocation(), diag::note_template_param_here);
2536 return true;
2537 }
2538
2539 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2540 << ParamType
2541 << FixItHint::CreateRemoval(AddrOpLoc);
2542 S.Diag(Param->getLocation(), diag::note_template_param_here);
2543
2544 ArgType = Var->getType();
2545 }
2546 } else if (!AddressTaken && ParamType->isPointerType()) {
2547 if (Var->getType()->isArrayType()) {
2548 // Array-to-pointer decay.
2549 ArgType = S.Context.getArrayDecayedType(Var->getType());
2550 } else {
2551 // If the template parameter has pointer type but the address of
2552 // this object was not taken, complain and (possibly) recover by
2553 // taking the address of the entity.
2554 ArgType = S.Context.getPointerType(Var->getType());
2555 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2556 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2557 << ParamType;
2558 S.Diag(Param->getLocation(), diag::note_template_param_here);
2559 return true;
2560 }
2561
2562 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2563 << ParamType
2564 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2565
2566 S.Diag(Param->getLocation(), diag::note_template_param_here);
2567 }
2568 }
2569 } else {
2570 // We found something else, but we don't know specifically what it is.
2571 S.Diag(Arg->getSourceRange().getBegin(),
2572 diag::err_template_arg_not_object_or_func)
2573 << Arg->getSourceRange();
2574 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2575 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002576 }
Mike Stump11289f42009-09-09 15:08:12 +00002577
Douglas Gregorb242683d2010-04-01 18:32:35 +00002578 if (ParamType->isPointerType() &&
2579 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2580 S.IsQualificationConversion(ArgType, ParamType)) {
2581 // For pointer-to-object types, qualification conversions are
2582 // permitted.
2583 } else {
2584 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2585 if (!ParamRef->getPointeeType()->isFunctionType()) {
2586 // C++ [temp.arg.nontype]p5b3:
2587 // For a non-type template-parameter of type reference to
2588 // object, no conversions apply. The type referred to by the
2589 // reference may be more cv-qualified than the (otherwise
2590 // identical) type of the template- argument. The
2591 // template-parameter is bound directly to the
2592 // template-argument, which shall be an lvalue.
2593
2594 // FIXME: Other qualifiers?
2595 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2596 unsigned ArgQuals = ArgType.getCVRQualifiers();
2597
2598 if ((ParamQuals | ArgQuals) != ParamQuals) {
2599 S.Diag(Arg->getSourceRange().getBegin(),
2600 diag::err_template_arg_ref_bind_ignores_quals)
2601 << ParamType << Arg->getType()
2602 << Arg->getSourceRange();
2603 S.Diag(Param->getLocation(), diag::note_template_param_here);
2604 return true;
2605 }
2606 }
2607 }
2608
2609 // At this point, the template argument refers to an object or
2610 // function with external linkage. We now need to check whether the
2611 // argument and parameter types are compatible.
2612 if (!S.Context.hasSameUnqualifiedType(ArgType,
2613 ParamType.getNonReferenceType())) {
2614 // We can't perform this conversion or binding.
2615 if (ParamType->isReferenceType())
2616 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2617 << ParamType << Arg->getType() << Arg->getSourceRange();
2618 else
2619 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2620 << Arg->getType() << ParamType << Arg->getSourceRange();
2621 S.Diag(Param->getLocation(), diag::note_template_param_here);
2622 return true;
2623 }
2624 }
2625
2626 // Create the template argument.
2627 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002628 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002629 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002630}
2631
2632/// \brief Checks whether the given template argument is a pointer to
2633/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002634bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2635 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002636 bool Invalid = false;
2637
2638 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002639 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002640 Arg = Cast->getSubExpr();
2641
2642 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002643 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002644 // A template-argument for a non-type, non-template
2645 // template-parameter shall be one of: [...]
2646 //
2647 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002648 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002649
2650 // Ignore (and complain about) any excess parentheses.
2651 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2652 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002653 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002654 diag::err_template_arg_extra_parens)
2655 << Arg->getSourceRange();
2656 Invalid = true;
2657 }
2658
2659 Arg = Parens->getSubExpr();
2660 }
2661
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002662 // A pointer-to-member constant written &Class::member.
2663 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002664 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2665 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2666 if (DRE && !DRE->getQualifier())
2667 DRE = 0;
2668 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002669 }
2670 // A constant of pointer-to-member type.
2671 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2672 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2673 if (VD->getType()->isMemberPointerType()) {
2674 if (isa<NonTypeTemplateParmDecl>(VD) ||
2675 (isa<VarDecl>(VD) &&
2676 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2677 if (Arg->isTypeDependent() || Arg->isValueDependent())
2678 Converted = TemplateArgument(Arg->Retain());
2679 else
2680 Converted = TemplateArgument(VD->getCanonicalDecl());
2681 return Invalid;
2682 }
2683 }
2684 }
2685
2686 DRE = 0;
2687 }
2688
Douglas Gregorccb07762009-02-11 19:52:55 +00002689 if (!DRE)
2690 return Diag(Arg->getSourceRange().getBegin(),
2691 diag::err_template_arg_not_pointer_to_member_form)
2692 << Arg->getSourceRange();
2693
2694 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2695 assert((isa<FieldDecl>(DRE->getDecl()) ||
2696 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2697 "Only non-static member pointers can make it here");
2698
2699 // Okay: this is the address of a non-static member, and therefore
2700 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002701 if (Arg->isTypeDependent() || Arg->isValueDependent())
2702 Converted = TemplateArgument(Arg->Retain());
2703 else
2704 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002705 return Invalid;
2706 }
2707
2708 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002709 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002710 diag::err_template_arg_not_pointer_to_member_form)
2711 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002712 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002713 diag::note_template_arg_refers_here);
2714 return true;
2715}
2716
Douglas Gregord32e0282009-02-09 23:23:08 +00002717/// \brief Check a template argument against its corresponding
2718/// non-type template parameter.
2719///
Douglas Gregor463421d2009-03-03 04:44:36 +00002720/// This routine implements the semantics of C++ [temp.arg.nontype].
2721/// It returns true if an error occurred, and false otherwise. \p
2722/// InstantiatedParamType is the type of the non-type template
2723/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002724///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002725/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002726bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002727 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002728 TemplateArgument &Converted,
2729 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002730 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2731
Douglas Gregor86560402009-02-10 23:36:10 +00002732 // If either the parameter has a dependent type or the argument is
2733 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002734 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2735 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002736 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002737 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002738 }
Douglas Gregor86560402009-02-10 23:36:10 +00002739
2740 // C++ [temp.arg.nontype]p5:
2741 // The following conversions are performed on each expression used
2742 // as a non-type template-argument. If a non-type
2743 // template-argument cannot be converted to the type of the
2744 // corresponding template-parameter then the program is
2745 // ill-formed.
2746 //
2747 // -- for a non-type template-parameter of integral or
2748 // enumeration type, integral promotions (4.5) and integral
2749 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002750 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002751 QualType ArgType = Arg->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +00002752 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002753 // C++ [temp.arg.nontype]p1:
2754 // A template-argument for a non-type, non-template
2755 // template-parameter shall be one of:
2756 //
2757 // -- an integral constant-expression of integral or enumeration
2758 // type; or
2759 // -- the name of a non-type template-parameter; or
2760 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002761 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00002762 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002763 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002764 diag::err_template_arg_not_integral_or_enumeral)
2765 << ArgType << Arg->getSourceRange();
2766 Diag(Param->getLocation(), diag::note_template_param_here);
2767 return true;
2768 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002769 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002770 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2771 << ArgType << Arg->getSourceRange();
2772 return true;
2773 }
2774
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002775 // From here on out, all we care about are the unqualified forms
2776 // of the parameter and argument types.
2777 ParamType = ParamType.getUnqualifiedType();
2778 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00002779
2780 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002781 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002782 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002783 } else if (CTAK == CTAK_Deduced) {
2784 // C++ [temp.deduct.type]p17:
2785 // If, in the declaration of a function template with a non-type
2786 // template-parameter, the non-type template- parameter is used
2787 // in an expression in the function parameter-list and, if the
2788 // corresponding template-argument is deduced, the
2789 // template-argument type shall match the type of the
2790 // template-parameter exactly, except that a template-argument
2791 // deduced from an array bound may be of any integral type.
2792 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2793 << ArgType << ParamType;
2794 Diag(Param->getLocation(), diag::note_template_param_here);
2795 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00002796 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2797 !ParamType->isEnumeralType()) {
2798 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002799 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002800 } else {
2801 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002802 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002803 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002804 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002805 Diag(Param->getLocation(), diag::note_template_param_here);
2806 return true;
2807 }
2808
Douglas Gregor52aba872009-03-14 00:20:21 +00002809 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002810 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002811 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002812
2813 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002814 llvm::APSInt OldValue = Value;
2815
2816 // Coerce the template argument's value to the value it will have
2817 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002818 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002819 if (Value.getBitWidth() != AllowedBits)
2820 Value.extOrTrunc(AllowedBits);
2821 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002822
2823 // Complain if an unsigned parameter received a negative value.
2824 if (IntegerType->isUnsignedIntegerType()
2825 && (OldValue.isSigned() && OldValue.isNegative())) {
2826 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2827 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2828 << Arg->getSourceRange();
2829 Diag(Param->getLocation(), diag::note_template_param_here);
2830 }
2831
2832 // Complain if we overflowed the template parameter's type.
2833 unsigned RequiredBits;
2834 if (IntegerType->isUnsignedIntegerType())
2835 RequiredBits = OldValue.getActiveBits();
2836 else if (OldValue.isUnsigned())
2837 RequiredBits = OldValue.getActiveBits() + 1;
2838 else
2839 RequiredBits = OldValue.getMinSignedBits();
2840 if (RequiredBits > AllowedBits) {
2841 Diag(Arg->getSourceRange().getBegin(),
2842 diag::warn_template_arg_too_large)
2843 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2844 << Arg->getSourceRange();
2845 Diag(Param->getLocation(), diag::note_template_param_here);
2846 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002847 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002848
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002849 // Add the value of this argument to the list of converted
2850 // arguments. We use the bitwidth and signedness of the template
2851 // parameter.
2852 if (Arg->isValueDependent()) {
2853 // The argument is value-dependent. Create a new
2854 // TemplateArgument with the converted expression.
2855 Converted = TemplateArgument(Arg);
2856 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002857 }
2858
John McCall0ad16662009-10-29 08:12:44 +00002859 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002860 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002861 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002862 return false;
2863 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002864
John McCall16df1e52010-03-30 21:47:33 +00002865 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2866
Douglas Gregorb242683d2010-04-01 18:32:35 +00002867 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2868 // from a template argument of type std::nullptr_t to a non-type
2869 // template parameter of type pointer to object, pointer to
2870 // function, or pointer-to-member, respectively.
2871 if (ArgType->isNullPtrType() &&
2872 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2873 Converted = TemplateArgument((NamedDecl *)0);
2874 return false;
2875 }
2876
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002877 // Handle pointer-to-function, reference-to-function, and
2878 // pointer-to-member-function all in (roughly) the same way.
2879 if (// -- For a non-type template-parameter of type pointer to
2880 // function, only the function-to-pointer conversion (4.3) is
2881 // applied. If the template-argument represents a set of
2882 // overloaded functions (or a pointer to such), the matching
2883 // function is selected from the set (13.4).
2884 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002885 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002886 // -- For a non-type template-parameter of type reference to
2887 // function, no conversions apply. If the template-argument
2888 // represents a set of overloaded functions, the matching
2889 // function is selected from the set (13.4).
2890 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002891 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002892 // -- For a non-type template-parameter of type pointer to
2893 // member function, no conversions apply. If the
2894 // template-argument represents a set of overloaded member
2895 // functions, the matching member function is selected from
2896 // the set (13.4).
2897 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002898 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002899 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002900
Douglas Gregor064fdb22010-04-14 23:11:21 +00002901 if (Arg->getType() == Context.OverloadTy) {
2902 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2903 true,
2904 FoundResult)) {
2905 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2906 return true;
2907
2908 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2909 ArgType = Arg->getType();
2910 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00002911 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002912 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002913
Douglas Gregorb242683d2010-04-01 18:32:35 +00002914 if (!ParamType->isMemberPointerType())
2915 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2916 ParamType,
2917 Arg, Converted);
2918
2919 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002920 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp, CastCategory(Arg));
Douglas Gregorb242683d2010-04-01 18:32:35 +00002921 } else if (!Context.hasSameUnqualifiedType(ArgType,
2922 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002923 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002924 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002925 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002926 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002927 Diag(Param->getLocation(), diag::note_template_param_here);
2928 return true;
2929 }
Mike Stump11289f42009-09-09 15:08:12 +00002930
Douglas Gregorb242683d2010-04-01 18:32:35 +00002931 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002932 }
2933
Chris Lattner696197c2009-02-20 21:37:53 +00002934 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002935 // -- for a non-type template-parameter of type pointer to
2936 // object, qualification conversions (4.4) and the
2937 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002938 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00002939 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002940 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002941
Douglas Gregorb242683d2010-04-01 18:32:35 +00002942 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2943 ParamType,
2944 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00002945 }
Mike Stump11289f42009-09-09 15:08:12 +00002946
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002947 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002948 // -- For a non-type template-parameter of type reference to
2949 // object, no conversions apply. The type referred to by the
2950 // reference may be more cv-qualified than the (otherwise
2951 // identical) type of the template-argument. The
2952 // template-parameter is bound directly to the
2953 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00002954 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002955 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002956
Douglas Gregor064fdb22010-04-14 23:11:21 +00002957 if (Arg->getType() == Context.OverloadTy) {
2958 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2959 ParamRefType->getPointeeType(),
2960 true,
2961 FoundResult)) {
2962 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2963 return true;
2964
2965 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2966 ArgType = Arg->getType();
2967 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00002968 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002969 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002970
Douglas Gregorb242683d2010-04-01 18:32:35 +00002971 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2972 ParamType,
2973 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002974 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002975
2976 // -- For a non-type template-parameter of type pointer to data
2977 // member, qualification conversions (4.4) are applied.
2978 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2979
Douglas Gregor1515f762009-02-11 18:22:40 +00002980 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002981 // Types match exactly: nothing more to do here.
2982 } else if (IsQualificationConversion(ArgType, ParamType)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002983 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp, CastCategory(Arg));
Douglas Gregor0e558532009-02-11 16:16:59 +00002984 } else {
2985 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002986 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002987 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002988 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002989 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002990 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002991 }
2992
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002993 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002994}
2995
2996/// \brief Check a template argument against its corresponding
2997/// template template parameter.
2998///
2999/// This routine implements the semantics of C++ [temp.arg.template].
3000/// It returns true if an error occurred, and false otherwise.
3001bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003002 const TemplateArgumentLoc &Arg) {
3003 TemplateName Name = Arg.getArgument().getAsTemplate();
3004 TemplateDecl *Template = Name.getAsTemplateDecl();
3005 if (!Template) {
3006 // Any dependent template name is fine.
3007 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3008 return false;
3009 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003010
3011 // C++ [temp.arg.template]p1:
3012 // A template-argument for a template template-parameter shall be
3013 // the name of a class template, expressed as id-expression. Only
3014 // primary class templates are considered when matching the
3015 // template template argument with the corresponding parameter;
3016 // partial specializations are not considered even if their
3017 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003018 //
3019 // Note that we also allow template template parameters here, which
3020 // will happen when we are dealing with, e.g., class template
3021 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003022 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003023 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003024 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003025 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003026 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003027 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003028 << Template;
3029 }
3030
3031 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3032 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003033 true,
3034 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003035 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003036}
3037
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003038/// \brief Given a non-type template argument that refers to a
3039/// declaration and the type of its corresponding non-type template
3040/// parameter, produce an expression that properly refers to that
3041/// declaration.
3042Sema::OwningExprResult
3043Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3044 QualType ParamType,
3045 SourceLocation Loc) {
3046 assert(Arg.getKind() == TemplateArgument::Declaration &&
3047 "Only declaration template arguments permitted here");
3048 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3049
3050 if (VD->getDeclContext()->isRecord() &&
3051 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3052 // If the value is a class member, we might have a pointer-to-member.
3053 // Determine whether the non-type template template parameter is of
3054 // pointer-to-member type. If so, we need to build an appropriate
3055 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3056 // would refer to the member itself.
3057 if (ParamType->isMemberPointerType()) {
3058 QualType ClassType
3059 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3060 NestedNameSpecifier *Qualifier
3061 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
3062 CXXScopeSpec SS;
3063 SS.setScopeRep(Qualifier);
3064 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
3065 VD->getType().getNonReferenceType(),
3066 Loc,
3067 &SS);
3068 if (RefExpr.isInvalid())
3069 return ExprError();
3070
3071 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003072
3073 // We might need to perform a trailing qualification conversion, since
3074 // the element type on the parameter could be more qualified than the
3075 // element type in the expression we constructed.
3076 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3077 ParamType.getUnqualifiedType())) {
3078 Expr *RefE = RefExpr.takeAs<Expr>();
3079 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(),
3080 CastExpr::CK_NoOp);
3081 RefExpr = Owned(RefE);
3082 }
3083
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003084 assert(!RefExpr.isInvalid() &&
3085 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003086 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003087 return move(RefExpr);
3088 }
3089 }
3090
3091 QualType T = VD->getType().getNonReferenceType();
3092 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003093 // When the non-type template parameter is a pointer, take the
3094 // address of the declaration.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003095 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3096 if (RefExpr.isInvalid())
3097 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003098
3099 if (T->isFunctionType() || T->isArrayType()) {
3100 // Decay functions and arrays.
3101 Expr *RefE = (Expr *)RefExpr.get();
3102 DefaultFunctionArrayConversion(RefE);
3103 if (RefE != RefExpr.get()) {
3104 RefExpr.release();
3105 RefExpr = Owned(RefE);
3106 }
3107
3108 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003109 }
3110
Douglas Gregorb242683d2010-04-01 18:32:35 +00003111 // Take the address of everything else
3112 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003113 }
3114
3115 // If the non-type template parameter has reference type, qualify the
3116 // resulting declaration reference with the extra qualifiers on the
3117 // type that the reference refers to.
3118 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3119 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3120
3121 return BuildDeclRefExpr(VD, T, Loc);
3122}
3123
3124/// \brief Construct a new expression that refers to the given
3125/// integral template argument with the given source-location
3126/// information.
3127///
3128/// This routine takes care of the mapping from an integral template
3129/// argument (which may have any integral type) to the appropriate
3130/// literal value.
3131Sema::OwningExprResult
3132Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3133 SourceLocation Loc) {
3134 assert(Arg.getKind() == TemplateArgument::Integral &&
3135 "Operation is only value for integral template arguments");
3136 QualType T = Arg.getIntegralType();
3137 if (T->isCharType() || T->isWideCharType())
3138 return Owned(new (Context) CharacterLiteral(
3139 Arg.getAsIntegral()->getZExtValue(),
3140 T->isWideCharType(),
3141 T,
3142 Loc));
3143 if (T->isBooleanType())
3144 return Owned(new (Context) CXXBoolLiteralExpr(
3145 Arg.getAsIntegral()->getBoolValue(),
3146 T,
3147 Loc));
3148
3149 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3150}
3151
3152
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003153/// \brief Determine whether the given template parameter lists are
3154/// equivalent.
3155///
Mike Stump11289f42009-09-09 15:08:12 +00003156/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003157/// source code as part of a new template declaration.
3158///
3159/// \param Old The old template parameter list, typically found via
3160/// name lookup of the template declared with this template parameter
3161/// list.
3162///
3163/// \param Complain If true, this routine will produce a diagnostic if
3164/// the template parameter lists are not equivalent.
3165///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003166/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003167///
3168/// \param TemplateArgLoc If this source location is valid, then we
3169/// are actually checking the template parameter list of a template
3170/// argument (New) against the template parameter list of its
3171/// corresponding template template parameter (Old). We produce
3172/// slightly different diagnostics in this scenario.
3173///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003174/// \returns True if the template parameter lists are equal, false
3175/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003176bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003177Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3178 TemplateParameterList *Old,
3179 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003180 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003181 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003182 if (Old->size() != New->size()) {
3183 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003184 unsigned NextDiag = diag::err_template_param_list_different_arity;
3185 if (TemplateArgLoc.isValid()) {
3186 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3187 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003188 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003189 Diag(New->getTemplateLoc(), NextDiag)
3190 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003191 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003192 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003193 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003194 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003195 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3196 }
3197
3198 return false;
3199 }
3200
3201 for (TemplateParameterList::iterator OldParm = Old->begin(),
3202 OldParmEnd = Old->end(), NewParm = New->begin();
3203 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3204 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003205 if (Complain) {
3206 unsigned NextDiag = diag::err_template_param_different_kind;
3207 if (TemplateArgLoc.isValid()) {
3208 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3209 NextDiag = diag::note_template_param_different_kind;
3210 }
3211 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003212 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003213 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003214 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003215 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003216 return false;
3217 }
3218
Douglas Gregor2e87ca22010-06-04 08:34:32 +00003219 if (TemplateTypeParmDecl *OldTTP
3220 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3221 // Template type parameters are equivalent if either both are template
3222 // type parameter packs or neither are (since we know we're at the same
3223 // index).
3224 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3225 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3226 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3227 // allow one to match a template parameter pack in the template
3228 // parameter list of a template template parameter to one or more
3229 // template parameters in the template parameter list of the
3230 // corresponding template template argument.
3231 if (Complain) {
3232 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3233 if (TemplateArgLoc.isValid()) {
3234 Diag(TemplateArgLoc,
3235 diag::err_template_arg_template_params_mismatch);
3236 NextDiag = diag::note_template_parameter_pack_non_pack;
3237 }
3238 Diag(NewTTP->getLocation(), NextDiag)
3239 << 0 << NewTTP->isParameterPack();
3240 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3241 << 0 << OldTTP->isParameterPack();
3242 }
3243 return false;
3244 }
Mike Stump11289f42009-09-09 15:08:12 +00003245 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003246 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3247 // The types of non-type template parameters must agree.
3248 NonTypeTemplateParmDecl *NewNTTP
3249 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003250
3251 // If we are matching a template template argument to a template
3252 // template parameter and one of the non-type template parameter types
3253 // is dependent, then we must wait until template instantiation time
3254 // to actually compare the arguments.
3255 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3256 (OldNTTP->getType()->isDependentType() ||
3257 NewNTTP->getType()->isDependentType()))
3258 continue;
3259
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003260 if (Context.getCanonicalType(OldNTTP->getType()) !=
3261 Context.getCanonicalType(NewNTTP->getType())) {
3262 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003263 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3264 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003265 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003266 diag::err_template_arg_template_params_mismatch);
3267 NextDiag = diag::note_template_nontype_parm_different_type;
3268 }
3269 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003270 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003271 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003272 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003273 diag::note_template_nontype_parm_prev_declaration)
3274 << OldNTTP->getType();
3275 }
3276 return false;
3277 }
3278 } else {
3279 // The template parameter lists of template template
3280 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003281 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003282 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003283 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003284 = cast<TemplateTemplateParmDecl>(*OldParm);
3285 TemplateTemplateParmDecl *NewTTP
3286 = cast<TemplateTemplateParmDecl>(*NewParm);
3287 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3288 OldTTP->getTemplateParameters(),
3289 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003290 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003291 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003292 return false;
3293 }
3294 }
3295
3296 return true;
3297}
3298
3299/// \brief Check whether a template can be declared within this scope.
3300///
3301/// If the template declaration is valid in this scope, returns
3302/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003303bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003304Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003305 // Find the nearest enclosing declaration scope.
3306 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3307 (S->getFlags() & Scope::TemplateParamScope) != 0)
3308 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003309
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003310 // C++ [temp]p2:
3311 // A template-declaration can appear only as a namespace scope or
3312 // class scope declaration.
3313 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003314 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3315 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003316 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003317 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003318
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003319 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003320 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003321
3322 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3323 return false;
3324
Mike Stump11289f42009-09-09 15:08:12 +00003325 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003326 diag::err_template_outside_namespace_or_class_scope)
3327 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003328}
Douglas Gregor67a65642009-02-17 23:15:12 +00003329
Douglas Gregor54888652009-10-07 00:13:32 +00003330/// \brief Determine what kind of template specialization the given declaration
3331/// is.
3332static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3333 if (!D)
3334 return TSK_Undeclared;
3335
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003336 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3337 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003338 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3339 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003340 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3341 return Var->getTemplateSpecializationKind();
3342
Douglas Gregor54888652009-10-07 00:13:32 +00003343 return TSK_Undeclared;
3344}
3345
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003346/// \brief Check whether a specialization is well-formed in the current
3347/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003348///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003349/// This routine determines whether a template specialization can be declared
3350/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003351///
3352/// \param S the semantic analysis object for which this check is being
3353/// performed.
3354///
3355/// \param Specialized the entity being specialized or instantiated, which
3356/// may be a kind of template (class template, function template, etc.) or
3357/// a member of a class template (member function, static data member,
3358/// member class).
3359///
3360/// \param PrevDecl the previous declaration of this entity, if any.
3361///
3362/// \param Loc the location of the explicit specialization or instantiation of
3363/// this entity.
3364///
3365/// \param IsPartialSpecialization whether this is a partial specialization of
3366/// a class template.
3367///
Douglas Gregor54888652009-10-07 00:13:32 +00003368/// \returns true if there was an error that we cannot recover from, false
3369/// otherwise.
3370static bool CheckTemplateSpecializationScope(Sema &S,
3371 NamedDecl *Specialized,
3372 NamedDecl *PrevDecl,
3373 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003374 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003375 // Keep these "kind" numbers in sync with the %select statements in the
3376 // various diagnostics emitted by this routine.
3377 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003378 bool isTemplateSpecialization = false;
3379 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003380 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003381 isTemplateSpecialization = true;
3382 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003383 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003384 isTemplateSpecialization = true;
3385 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003386 EntityKind = 3;
3387 else if (isa<VarDecl>(Specialized))
3388 EntityKind = 4;
3389 else if (isa<RecordDecl>(Specialized))
3390 EntityKind = 5;
3391 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003392 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3393 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003394 return true;
3395 }
3396
Douglas Gregorf47b9112009-02-25 22:02:03 +00003397 // C++ [temp.expl.spec]p2:
3398 // An explicit specialization shall be declared in the namespace
3399 // of which the template is a member, or, for member templates, in
3400 // the namespace of which the enclosing class or enclosing class
3401 // template is a member. An explicit specialization of a member
3402 // function, member class or static data member of a class
3403 // template shall be declared in the namespace of which the class
3404 // template is a member. Such a declaration may also be a
3405 // definition. If the declaration is not a definition, the
3406 // specialization may be defined later in the name- space in which
3407 // the explicit specialization was declared, or in a namespace
3408 // that encloses the one in which the explicit specialization was
3409 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003410 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3411 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003412 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003413 return true;
3414 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003415
Douglas Gregor40fb7442009-10-07 17:30:37 +00003416 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3417 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003418 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003419 return true;
3420 }
3421
Douglas Gregore4b05162009-10-07 17:21:34 +00003422 // C++ [temp.class.spec]p6:
3423 // A class template partial specialization may be declared or redeclared
3424 // in any namespace scope in which its definition may be defined (14.5.1
3425 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003426 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003427 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003428 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003429 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003430 if ((!PrevDecl ||
3431 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3432 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3433 // There is no prior declaration of this entity, so this
3434 // specialization must be in the same context as the template
3435 // itself.
3436 if (!DC->Equals(SpecializedContext)) {
3437 if (isa<TranslationUnitDecl>(SpecializedContext))
3438 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3439 << EntityKind << Specialized;
3440 else if (isa<NamespaceDecl>(SpecializedContext))
3441 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3442 << EntityKind << Specialized
3443 << cast<NamedDecl>(SpecializedContext);
3444
3445 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3446 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003447 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003448 }
Douglas Gregor54888652009-10-07 00:13:32 +00003449
3450 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003451 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003452 // Note that HandleDeclarator() performs this check for explicit
3453 // specializations of function templates, static data members, and member
3454 // functions, so we skip the check here for those kinds of entities.
3455 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003456 // Should we refactor that check, so that it occurs later?
3457 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003458 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3459 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003460 if (isa<TranslationUnitDecl>(SpecializedContext))
3461 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3462 << EntityKind << Specialized;
3463 else if (isa<NamespaceDecl>(SpecializedContext))
3464 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3465 << EntityKind << Specialized
3466 << cast<NamedDecl>(SpecializedContext);
3467
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003468 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003469 }
Douglas Gregor54888652009-10-07 00:13:32 +00003470
3471 // FIXME: check for specialization-after-instantiation errors and such.
3472
Douglas Gregorf47b9112009-02-25 22:02:03 +00003473 return false;
3474}
Douglas Gregor54888652009-10-07 00:13:32 +00003475
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003476/// \brief Check the non-type template arguments of a class template
3477/// partial specialization according to C++ [temp.class.spec]p9.
3478///
Douglas Gregor09a30232009-06-12 22:08:06 +00003479/// \param TemplateParams the template parameters of the primary class
3480/// template.
3481///
3482/// \param TemplateArg the template arguments of the class template
3483/// partial specialization.
3484///
3485/// \param MirrorsPrimaryTemplate will be set true if the class
3486/// template partial specialization arguments are identical to the
3487/// implicit template arguments of the primary template. This is not
3488/// necessarily an error (C++0x), and it is left to the caller to diagnose
3489/// this condition when it is an error.
3490///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003491/// \returns true if there was an error, false otherwise.
3492bool Sema::CheckClassTemplatePartialSpecializationArgs(
3493 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003494 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003495 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003496 // FIXME: the interface to this function will have to change to
3497 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003498 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003499
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003500 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003501
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003502 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003503 // Determine whether the template argument list of the partial
3504 // specialization is identical to the implicit argument list of
3505 // the primary template. The caller may need to diagnostic this as
3506 // an error per C++ [temp.class.spec]p9b3.
3507 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003508 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003509 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3510 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003511 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003512 MirrorsPrimaryTemplate = false;
3513 } else if (TemplateTemplateParmDecl *TTP
3514 = dyn_cast<TemplateTemplateParmDecl>(
3515 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003516 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003517 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003518 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003519 if (!ArgDecl ||
3520 ArgDecl->getIndex() != TTP->getIndex() ||
3521 ArgDecl->getDepth() != TTP->getDepth())
3522 MirrorsPrimaryTemplate = false;
3523 }
3524 }
3525
Mike Stump11289f42009-09-09 15:08:12 +00003526 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003527 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003528 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003529 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003530 }
3531
Anders Carlsson40c1d492009-06-13 18:20:51 +00003532 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003533 if (!ArgExpr) {
3534 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003535 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003536 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003537
3538 // C++ [temp.class.spec]p8:
3539 // A non-type argument is non-specialized if it is the name of a
3540 // non-type parameter. All other non-type arguments are
3541 // specialized.
3542 //
3543 // Below, we check the two conditions that only apply to
3544 // specialized non-type arguments, so skip any non-specialized
3545 // arguments.
3546 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003547 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003548 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003549 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003550 (Param->getIndex() != NTTP->getIndex() ||
3551 Param->getDepth() != NTTP->getDepth()))
3552 MirrorsPrimaryTemplate = false;
3553
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003554 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003555 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003556
3557 // C++ [temp.class.spec]p9:
3558 // Within the argument list of a class template partial
3559 // specialization, the following restrictions apply:
3560 // -- A partially specialized non-type argument expression
3561 // shall not involve a template parameter of the partial
3562 // specialization except when the argument expression is a
3563 // simple identifier.
3564 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003565 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003566 diag::err_dependent_non_type_arg_in_partial_spec)
3567 << ArgExpr->getSourceRange();
3568 return true;
3569 }
3570
3571 // -- The type of a template parameter corresponding to a
3572 // specialized non-type argument shall not be dependent on a
3573 // parameter of the specialization.
3574 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003575 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003576 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3577 << Param->getType()
3578 << ArgExpr->getSourceRange();
3579 Diag(Param->getLocation(), diag::note_template_param_here);
3580 return true;
3581 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003582
3583 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003584 }
3585
3586 return false;
3587}
3588
Douglas Gregorc854c662010-02-26 06:03:23 +00003589/// \brief Retrieve the previous declaration of the given declaration.
3590static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3591 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3592 return VD->getPreviousDeclaration();
3593 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3594 return FD->getPreviousDeclaration();
3595 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3596 return TD->getPreviousDeclaration();
3597 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3598 return TD->getPreviousDeclaration();
3599 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3600 return FTD->getPreviousDeclaration();
3601 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3602 return CTD->getPreviousDeclaration();
3603 return 0;
3604}
3605
Douglas Gregorc08f4892009-03-25 00:13:59 +00003606Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003607Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3608 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003609 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003610 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003611 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003612 SourceLocation TemplateNameLoc,
3613 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003614 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003615 SourceLocation RAngleLoc,
3616 AttributeList *Attr,
3617 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003618 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003619
Douglas Gregor67a65642009-02-17 23:15:12 +00003620 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003621 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003622 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003623 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3624
3625 if (!ClassTemplate) {
3626 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3627 << (Name.getAsTemplateDecl() &&
3628 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3629 return true;
3630 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003631
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003632 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003633 bool isPartialSpecialization = false;
3634
Douglas Gregorf47b9112009-02-25 22:02:03 +00003635 // Check the validity of the template headers that introduce this
3636 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003637 // FIXME: We probably shouldn't complain about these headers for
3638 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003639 bool Invalid = false;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003640 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003641 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3642 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003643 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003644 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003645 isExplicitSpecialization,
3646 Invalid);
3647 if (Invalid)
3648 return true;
3649
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003650 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3651 if (TemplateParams)
3652 --NumMatchedTemplateParamLists;
3653
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003654 if (TemplateParams && TemplateParams->size() > 0) {
3655 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003656
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003657 // C++ [temp.class.spec]p10:
3658 // The template parameter list of a specialization shall not
3659 // contain default template argument values.
3660 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3661 Decl *Param = TemplateParams->getParam(I);
3662 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3663 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003664 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003665 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003666 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003667 }
3668 } else if (NonTypeTemplateParmDecl *NTTP
3669 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3670 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003671 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003672 diag::err_default_arg_in_partial_spec)
3673 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003674 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003675 }
3676 } else {
3677 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003678 if (TTP->hasDefaultArgument()) {
3679 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003680 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003681 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003682 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00003683 }
3684 }
3685 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003686 } else if (TemplateParams) {
3687 if (TUK == TUK_Friend)
3688 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003689 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003690 SourceRange(TemplateParams->getTemplateLoc(),
3691 TemplateParams->getRAngleLoc()))
3692 << SourceRange(LAngleLoc, RAngleLoc);
3693 else
3694 isExplicitSpecialization = true;
3695 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003696 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003697 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003698 isExplicitSpecialization = true;
3699 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003700
Douglas Gregor67a65642009-02-17 23:15:12 +00003701 // Check that the specialization uses the same tag kind as the
3702 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003703 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3704 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00003705 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003706 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003707 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003708 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003709 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003710 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003711 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003712 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003713 diag::note_previous_use);
3714 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3715 }
3716
Douglas Gregorc40290e2009-03-09 23:48:35 +00003717 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003718 TemplateArgumentListInfo TemplateArgs;
3719 TemplateArgs.setLAngleLoc(LAngleLoc);
3720 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003721 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003722
Douglas Gregor67a65642009-02-17 23:15:12 +00003723 // Check that the template argument list is well-formed for this
3724 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003725 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3726 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003727 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3728 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003729 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003730
Mike Stump11289f42009-09-09 15:08:12 +00003731 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003732 ClassTemplate->getTemplateParameters()->size()) &&
3733 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003734
Douglas Gregor2373c592009-05-31 09:31:02 +00003735 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003736 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00003737 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003738 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003739 if (CheckClassTemplatePartialSpecializationArgs(
3740 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003741 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003742 return true;
3743
Douglas Gregor09a30232009-06-12 22:08:06 +00003744 if (MirrorsPrimaryTemplate) {
3745 // C++ [temp.class.spec]p9b3:
3746 //
Mike Stump11289f42009-09-09 15:08:12 +00003747 // -- The argument list of the specialization shall not be identical
3748 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003749 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003750 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003751 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003752 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003753 ClassTemplate->getIdentifier(),
3754 TemplateNameLoc,
3755 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003756 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003757 AS_none);
3758 }
3759
Douglas Gregor2208a292009-09-26 20:57:03 +00003760 // FIXME: Diagnose friend partial specializations
3761
Douglas Gregor92354b62010-02-09 00:37:32 +00003762 if (!Name.isDependent() &&
3763 !TemplateSpecializationType::anyDependentTemplateArguments(
3764 TemplateArgs.getArgumentArray(),
3765 TemplateArgs.size())) {
3766 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3767 << ClassTemplate->getDeclName();
3768 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00003769 }
3770 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003771
Douglas Gregor67a65642009-02-17 23:15:12 +00003772 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003773 ClassTemplateSpecializationDecl *PrevDecl = 0;
3774
3775 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003776 // FIXME: Template parameter list matters, too
Douglas Gregor2373c592009-05-31 09:31:02 +00003777 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003778 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
3779 Converted.flatSize(),
3780 InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00003781 else
3782 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003783 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
3784 Converted.flatSize(), InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003785
3786 ClassTemplateSpecializationDecl *Specialization = 0;
3787
Douglas Gregorf47b9112009-02-25 22:02:03 +00003788 // Check whether we can declare a class template specialization in
3789 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003790 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003791 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003792 TemplateNameLoc,
3793 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003794 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003795
Douglas Gregor15301382009-07-30 17:40:51 +00003796 // The canonical type
3797 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003798 if (PrevDecl &&
3799 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003800 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003801 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003802 // arguments was referenced but not declared, or we're only
3803 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003804 // declaration node as our own, updating its source location to
3805 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003806 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003807 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003808 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003809 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003810 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003811 // Build the canonical type that describes the converted template
3812 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003813 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3814 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003815 Converted.getFlatArguments(),
3816 Converted.flatSize());
3817
Douglas Gregor2373c592009-05-31 09:31:02 +00003818 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003819 ClassTemplatePartialSpecializationDecl *PrevPartial
3820 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00003821 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003822 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump11289f42009-09-09 15:08:12 +00003823 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00003824 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00003825 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003826 TemplateNameLoc,
3827 TemplateParams,
3828 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003829 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003830 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003831 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00003832 PrevPartial,
3833 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00003834 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00003835 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003836 Partial->setTemplateParameterListsInfo(Context,
3837 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003838 (TemplateParameterList**) TemplateParameterLists.release());
3839 }
Douglas Gregor2373c592009-05-31 09:31:02 +00003840
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003841 if (!PrevPartial)
3842 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00003843 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003844
Douglas Gregor21610382009-10-29 00:04:11 +00003845 // If we are providing an explicit specialization of a member class
3846 // template specialization, make a note of that.
3847 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3848 PrevPartial->setMemberSpecialization();
3849
Douglas Gregor91772d12009-06-13 00:26:55 +00003850 // Check that all of the template parameters of the class template
3851 // partial specialization are deducible from the template
3852 // arguments. If not, this class template partial specialization
3853 // will never be used.
3854 llvm::SmallVector<bool, 8> DeducibleParams;
3855 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003856 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003857 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003858 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003859 unsigned NumNonDeducible = 0;
3860 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3861 if (!DeducibleParams[I])
3862 ++NumNonDeducible;
3863
3864 if (NumNonDeducible) {
3865 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3866 << (NumNonDeducible > 1)
3867 << SourceRange(TemplateNameLoc, RAngleLoc);
3868 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3869 if (!DeducibleParams[I]) {
3870 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3871 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003872 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003873 diag::note_partial_spec_unused_parameter)
3874 << Param->getDeclName();
3875 else
Mike Stump11289f42009-09-09 15:08:12 +00003876 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003877 diag::note_partial_spec_unused_parameter)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003878 << "<anonymous>";
Douglas Gregor91772d12009-06-13 00:26:55 +00003879 }
3880 }
3881 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003882 } else {
3883 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003884 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003885 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00003886 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00003887 ClassTemplate->getDeclContext(),
3888 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003889 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003890 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003891 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00003892 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00003893 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003894 Specialization->setTemplateParameterListsInfo(Context,
3895 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003896 (TemplateParameterList**) TemplateParameterLists.release());
3897 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003898
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003899 if (!PrevDecl)
3900 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00003901
3902 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003903 }
3904
Douglas Gregor06db9f52009-10-12 20:18:28 +00003905 // C++ [temp.expl.spec]p6:
3906 // If a template, a member template or the member of a class template is
3907 // explicitly specialized then that specialization shall be declared
3908 // before the first use of that specialization that would cause an implicit
3909 // instantiation to take place, in every translation unit in which such a
3910 // use occurs; no diagnostic is required.
3911 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003912 bool Okay = false;
3913 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3914 // Is there any previous explicit specialization declaration?
3915 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3916 Okay = true;
3917 break;
3918 }
3919 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003920
Douglas Gregorc854c662010-02-26 06:03:23 +00003921 if (!Okay) {
3922 SourceRange Range(TemplateNameLoc, RAngleLoc);
3923 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3924 << Context.getTypeDeclType(Specialization) << Range;
3925
3926 Diag(PrevDecl->getPointOfInstantiation(),
3927 diag::note_instantiation_required_here)
3928 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003929 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003930 return true;
3931 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003932 }
3933
Douglas Gregor2208a292009-09-26 20:57:03 +00003934 // If this is not a friend, note that this is an explicit specialization.
3935 if (TUK != TUK_Friend)
3936 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003937
3938 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003939 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003940 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003941 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003942 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003943 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003944 Diag(Def->getLocation(), diag::note_previous_definition);
3945 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003946 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003947 }
3948 }
3949
Douglas Gregord56a91e2009-02-26 22:19:44 +00003950 // Build the fully-sugared type for this class template
3951 // specialization as the user wrote in the specialization
3952 // itself. This means that we'll pretty-print the type retrieved
3953 // from the specialization's declaration the way that the user
3954 // actually wrote the specialization, rather than formatting the
3955 // name based on the "canonical" representation used to store the
3956 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003957 TypeSourceInfo *WrittenTy
3958 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3959 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00003960 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003961 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregord890b732010-07-06 18:33:12 +00003962 if (TemplateParams)
3963 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnara8075c852010-06-12 07:44:57 +00003964 }
Douglas Gregorc40290e2009-03-09 23:48:35 +00003965 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003966
Douglas Gregor1e249f82009-02-25 22:18:32 +00003967 // C++ [temp.expl.spec]p9:
3968 // A template explicit specialization is in the scope of the
3969 // namespace in which the template was defined.
3970 //
3971 // We actually implement this paragraph where we set the semantic
3972 // context (in the creation of the ClassTemplateSpecializationDecl),
3973 // but we also maintain the lexical context where the actual
3974 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003975 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003976
Douglas Gregor67a65642009-02-17 23:15:12 +00003977 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003978 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003979 Specialization->startDefinition();
3980
Douglas Gregor2208a292009-09-26 20:57:03 +00003981 if (TUK == TUK_Friend) {
3982 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3983 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00003984 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00003985 /*FIXME:*/KWLoc);
3986 Friend->setAccess(AS_public);
3987 CurContext->addDecl(Friend);
3988 } else {
3989 // Add the specialization into its lexical context, so that it can
3990 // be seen when iterating through the list of declarations in that
3991 // context. However, specializations are not found by name lookup.
3992 CurContext->addDecl(Specialization);
3993 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003994 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003995}
Douglas Gregor333489b2009-03-27 23:10:48 +00003996
Mike Stump11289f42009-09-09 15:08:12 +00003997Sema::DeclPtrTy
3998Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003999 MultiTemplateParamsArg TemplateParameterLists,
4000 Declarator &D) {
4001 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4002}
4003
Mike Stump11289f42009-09-09 15:08:12 +00004004Sema::DeclPtrTy
4005Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004006 MultiTemplateParamsArg TemplateParameterLists,
4007 Declarator &D) {
4008 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4009 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4010 "Not a function declarator!");
4011 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00004012
Douglas Gregor17a7c122009-06-24 00:54:41 +00004013 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004014 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004015 }
Mike Stump11289f42009-09-09 15:08:12 +00004016
Douglas Gregor17a7c122009-06-24 00:54:41 +00004017 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004018
4019 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004020 move(TemplateParameterLists),
4021 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004022 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00004023 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00004024 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004025 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00004026 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
4027 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004028 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00004029}
4030
John McCall4f7ced62010-02-11 01:33:53 +00004031/// \brief Strips various properties off an implicit instantiation
4032/// that has just been explicitly specialized.
4033static void StripImplicitInstantiation(NamedDecl *D) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004034 D->dropAttrs();
John McCall4f7ced62010-02-11 01:33:53 +00004035
4036 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4037 FD->setInlineSpecified(false);
4038 }
4039}
4040
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004041/// \brief Diagnose cases where we have an explicit template specialization
4042/// before/after an explicit template instantiation, producing diagnostics
4043/// for those cases where they are required and determining whether the
4044/// new specialization/instantiation will have any effect.
4045///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004046/// \param NewLoc the location of the new explicit specialization or
4047/// instantiation.
4048///
4049/// \param NewTSK the kind of the new explicit specialization or instantiation.
4050///
4051/// \param PrevDecl the previous declaration of the entity.
4052///
4053/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4054///
4055/// \param PrevPointOfInstantiation if valid, indicates where the previus
4056/// declaration was instantiated (either implicitly or explicitly).
4057///
Abramo Bagnara8075c852010-06-12 07:44:57 +00004058/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004059/// specialization or instantiation has no effect and should be ignored.
4060///
4061/// \returns true if there was an error that should prevent the introduction of
4062/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004063bool
4064Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4065 TemplateSpecializationKind NewTSK,
4066 NamedDecl *PrevDecl,
4067 TemplateSpecializationKind PrevTSK,
4068 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004069 bool &HasNoEffect) {
4070 HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004071
4072 switch (NewTSK) {
4073 case TSK_Undeclared:
4074 case TSK_ImplicitInstantiation:
4075 assert(false && "Don't check implicit instantiations here");
4076 return false;
4077
4078 case TSK_ExplicitSpecialization:
4079 switch (PrevTSK) {
4080 case TSK_Undeclared:
4081 case TSK_ExplicitSpecialization:
4082 // Okay, we're just specializing something that is either already
4083 // explicitly specialized or has merely been mentioned without any
4084 // instantiation.
4085 return false;
4086
4087 case TSK_ImplicitInstantiation:
4088 if (PrevPointOfInstantiation.isInvalid()) {
4089 // The declaration itself has not actually been instantiated, so it is
4090 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004091 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004092 return false;
4093 }
4094 // Fall through
4095
4096 case TSK_ExplicitInstantiationDeclaration:
4097 case TSK_ExplicitInstantiationDefinition:
4098 assert((PrevTSK == TSK_ImplicitInstantiation ||
4099 PrevPointOfInstantiation.isValid()) &&
4100 "Explicit instantiation without point of instantiation?");
4101
4102 // C++ [temp.expl.spec]p6:
4103 // If a template, a member template or the member of a class template
4104 // is explicitly specialized then that specialization shall be declared
4105 // before the first use of that specialization that would cause an
4106 // implicit instantiation to take place, in every translation unit in
4107 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004108 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4109 // Is there any previous explicit specialization declaration?
4110 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4111 return false;
4112 }
4113
Douglas Gregor1d957a32009-10-27 18:42:08 +00004114 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004115 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004116 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004117 << (PrevTSK != TSK_ImplicitInstantiation);
4118
4119 return true;
4120 }
4121 break;
4122
4123 case TSK_ExplicitInstantiationDeclaration:
4124 switch (PrevTSK) {
4125 case TSK_ExplicitInstantiationDeclaration:
4126 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00004127 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004128 return false;
4129
4130 case TSK_Undeclared:
4131 case TSK_ImplicitInstantiation:
4132 // We're explicitly instantiating something that may have already been
4133 // implicitly instantiated; that's fine.
4134 return false;
4135
4136 case TSK_ExplicitSpecialization:
4137 // C++0x [temp.explicit]p4:
4138 // For a given set of template parameters, if an explicit instantiation
4139 // of a template appears after a declaration of an explicit
4140 // specialization for that template, the explicit instantiation has no
4141 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00004142 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004143 return false;
4144
4145 case TSK_ExplicitInstantiationDefinition:
4146 // C++0x [temp.explicit]p10:
4147 // If an entity is the subject of both an explicit instantiation
4148 // declaration and an explicit instantiation definition in the same
4149 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004150 Diag(NewLoc,
4151 diag::err_explicit_instantiation_declaration_after_definition);
4152 Diag(PrevPointOfInstantiation,
4153 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004154 assert(PrevPointOfInstantiation.isValid() &&
4155 "Explicit instantiation without point of instantiation?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00004156 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004157 return false;
4158 }
4159 break;
4160
4161 case TSK_ExplicitInstantiationDefinition:
4162 switch (PrevTSK) {
4163 case TSK_Undeclared:
4164 case TSK_ImplicitInstantiation:
4165 // We're explicitly instantiating something that may have already been
4166 // implicitly instantiated; that's fine.
4167 return false;
4168
4169 case TSK_ExplicitSpecialization:
4170 // C++ DR 259, C++0x [temp.explicit]p4:
4171 // For a given set of template parameters, if an explicit
4172 // instantiation of a template appears after a declaration of
4173 // an explicit specialization for that template, the explicit
4174 // instantiation has no effect.
4175 //
4176 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004177 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004178 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004179 if (!getLangOptions().CPlusPlus0x) {
4180 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004181 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004182 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004183 diag::note_previous_template_specialization);
4184 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004185 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004186 return false;
4187
4188 case TSK_ExplicitInstantiationDeclaration:
4189 // We're explicity instantiating a definition for something for which we
4190 // were previously asked to suppress instantiations. That's fine.
4191 return false;
4192
4193 case TSK_ExplicitInstantiationDefinition:
4194 // C++0x [temp.spec]p5:
4195 // For a given template and a given set of template-arguments,
4196 // - an explicit instantiation definition shall appear at most once
4197 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004198 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004199 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004200 Diag(PrevPointOfInstantiation,
4201 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004202 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004203 return false;
4204 }
4205 break;
4206 }
4207
4208 assert(false && "Missing specialization/instantiation case?");
4209
4210 return false;
4211}
4212
John McCallb9c78482010-04-08 09:05:18 +00004213/// \brief Perform semantic analysis for the given dependent function
4214/// template specialization. The only possible way to get a dependent
4215/// function template specialization is with a friend declaration,
4216/// like so:
4217///
4218/// template <class T> void foo(T);
4219/// template <class T> class A {
4220/// friend void foo<>(T);
4221/// };
4222///
4223/// There really isn't any useful analysis we can do here, so we
4224/// just store the information.
4225bool
4226Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4227 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4228 LookupResult &Previous) {
4229 // Remove anything from Previous that isn't a function template in
4230 // the correct context.
4231 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4232 LookupResult::Filter F = Previous.makeFilter();
4233 while (F.hasNext()) {
4234 NamedDecl *D = F.next()->getUnderlyingDecl();
4235 if (!isa<FunctionTemplateDecl>(D) ||
4236 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4237 F.erase();
4238 }
4239 F.done();
4240
4241 // Should this be diagnosed here?
4242 if (Previous.empty()) return true;
4243
4244 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4245 ExplicitTemplateArgs);
4246 return false;
4247}
4248
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004249/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004250/// specialization.
4251///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004252/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004253/// explicit function template specialization. On successful completion,
4254/// the function declaration \p FD will become a function template
4255/// specialization.
4256///
4257/// \param FD the function declaration, which will be updated to become a
4258/// function template specialization.
4259///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004260/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4261/// if any. Note that this may be valid info even when 0 arguments are
4262/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4263/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004264///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004265/// \param PrevDecl the set of declarations that may be specialized by
4266/// this function specialization.
4267bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004268Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004269 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004270 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004271 // The set of function template specializations that could match this
4272 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004273 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004274
4275 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00004276 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4277 I != E; ++I) {
4278 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4279 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004280 // Only consider templates found within the same semantic lookup scope as
4281 // FD.
4282 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4283 continue;
4284
4285 // C++ [temp.expl.spec]p11:
4286 // A trailing template-argument can be left unspecified in the
4287 // template-id naming an explicit function template specialization
4288 // provided it can be deduced from the function argument type.
4289 // Perform template argument deduction to determine whether we may be
4290 // specializing this template.
4291 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004292 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004293 FunctionDecl *Specialization = 0;
4294 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004295 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004296 FD->getType(),
4297 Specialization,
4298 Info)) {
4299 // FIXME: Template argument deduction failed; record why it failed, so
4300 // that we can provide nifty diagnostics.
4301 (void)TDK;
4302 continue;
4303 }
4304
4305 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004306 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004307 }
4308 }
4309
Douglas Gregor5de279c2009-09-26 03:41:46 +00004310 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004311 UnresolvedSetIterator Result
4312 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4313 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004314 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004315 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004316 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004317 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004318 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004319 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004320 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004321
4322 // Ignore access information; it doesn't figure into redeclaration checking.
4323 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004324 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004325
4326 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004327 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004328
4329 // If this is a friend declaration, then we're not really declaring
4330 // an explicit specialization.
4331 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004332
Douglas Gregor54888652009-10-07 00:13:32 +00004333 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004334 if (!isFriend &&
4335 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004336 Specialization->getPrimaryTemplate(),
4337 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004338 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004339 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004340
4341 // C++ [temp.expl.spec]p6:
4342 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004343 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004344 // before the first use of that specialization that would cause an implicit
4345 // instantiation to take place, in every translation unit in which such a
4346 // use occurs; no diagnostic is required.
4347 FunctionTemplateSpecializationInfo *SpecInfo
4348 = Specialization->getTemplateSpecializationInfo();
4349 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004350
Abramo Bagnara8075c852010-06-12 07:44:57 +00004351 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00004352 if (!isFriend &&
4353 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004354 TSK_ExplicitSpecialization,
4355 Specialization,
4356 SpecInfo->getTemplateSpecializationKind(),
4357 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004358 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004359 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004360
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004361 // Mark the prior declaration as an explicit specialization, so that later
4362 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004363 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00004364 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004365 MarkUnusedFileScopedDecl(Specialization);
4366 }
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004367
4368 // Turn the given function declaration into a function template
4369 // specialization, with the template arguments from the previous
4370 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004371 // Take copies of (semantic and syntactic) template argument lists.
4372 const TemplateArgumentList* TemplArgs = new (Context)
4373 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4374 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4375 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004376 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004377 TemplArgs, /*InsertPos=*/0,
4378 SpecInfo->getTemplateSpecializationKind(),
4379 TemplArgsAsWritten);
4380
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004381 // The "previous declaration" for this function template specialization is
4382 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004383 Previous.clear();
4384 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004385 return false;
4386}
4387
Douglas Gregor86d142a2009-10-08 07:24:58 +00004388/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004389/// specialization.
4390///
4391/// This routine performs all of the semantic analysis required for an
4392/// explicit member function specialization. On successful completion,
4393/// the function declaration \p FD will become a member function
4394/// specialization.
4395///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004396/// \param Member the member declaration, which will be updated to become a
4397/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004398///
John McCall1f82f242009-11-18 22:49:29 +00004399/// \param Previous the set of declarations, one of which may be specialized
4400/// by this function specialization; the set will be modified to contain the
4401/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004402bool
John McCall1f82f242009-11-18 22:49:29 +00004403Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004404 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004405
Douglas Gregor86d142a2009-10-08 07:24:58 +00004406 // Try to find the member we are instantiating.
4407 NamedDecl *Instantiation = 0;
4408 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004409 MemberSpecializationInfo *MSInfo = 0;
4410
John McCall1f82f242009-11-18 22:49:29 +00004411 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004412 // Nowhere to look anyway.
4413 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004414 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4415 I != E; ++I) {
4416 NamedDecl *D = (*I)->getUnderlyingDecl();
4417 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004418 if (Context.hasSameType(Function->getType(), Method->getType())) {
4419 Instantiation = Method;
4420 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004421 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004422 break;
4423 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004424 }
4425 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004426 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004427 VarDecl *PrevVar;
4428 if (Previous.isSingleResult() &&
4429 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004430 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004431 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004432 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004433 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004434 }
4435 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004436 CXXRecordDecl *PrevRecord;
4437 if (Previous.isSingleResult() &&
4438 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4439 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004440 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004441 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004442 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004443 }
4444
4445 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004446 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004447 // specializations are always out-of-line, the caller will complain about
4448 // this mismatch later.
4449 return false;
4450 }
John McCalle820e5e2010-04-13 20:37:33 +00004451
4452 // If this is a friend, just bail out here before we start turning
4453 // things into explicit specializations.
4454 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4455 // Preserve instantiation information.
4456 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4457 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4458 cast<CXXMethodDecl>(InstantiatedFrom),
4459 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4460 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4461 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4462 cast<CXXRecordDecl>(InstantiatedFrom),
4463 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4464 }
4465
4466 Previous.clear();
4467 Previous.addDecl(Instantiation);
4468 return false;
4469 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004470
Douglas Gregor86d142a2009-10-08 07:24:58 +00004471 // Make sure that this is a specialization of a member.
4472 if (!InstantiatedFrom) {
4473 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4474 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004475 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4476 return true;
4477 }
4478
Douglas Gregor06db9f52009-10-12 20:18:28 +00004479 // C++ [temp.expl.spec]p6:
4480 // If a template, a member template or the member of a class template is
4481 // explicitly specialized then that spe- cialization shall be declared
4482 // before the first use of that specialization that would cause an implicit
4483 // instantiation to take place, in every translation unit in which such a
4484 // use occurs; no diagnostic is required.
4485 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004486
Abramo Bagnara8075c852010-06-12 07:44:57 +00004487 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00004488 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4489 TSK_ExplicitSpecialization,
4490 Instantiation,
4491 MSInfo->getTemplateSpecializationKind(),
4492 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004493 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004494 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004495
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004496 // Check the scope of this explicit specialization.
4497 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004498 InstantiatedFrom,
4499 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004500 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004501 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004502
Douglas Gregor86d142a2009-10-08 07:24:58 +00004503 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004504 // the original declaration to note that it is an explicit specialization
4505 // (if it was previously an implicit instantiation). This latter step
4506 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004507 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004508 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4509 if (InstantiationFunction->getTemplateSpecializationKind() ==
4510 TSK_ImplicitInstantiation) {
4511 InstantiationFunction->setTemplateSpecializationKind(
4512 TSK_ExplicitSpecialization);
4513 InstantiationFunction->setLocation(Member->getLocation());
4514 }
4515
Douglas Gregor86d142a2009-10-08 07:24:58 +00004516 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4517 cast<CXXMethodDecl>(InstantiatedFrom),
4518 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004519 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004520 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004521 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4522 if (InstantiationVar->getTemplateSpecializationKind() ==
4523 TSK_ImplicitInstantiation) {
4524 InstantiationVar->setTemplateSpecializationKind(
4525 TSK_ExplicitSpecialization);
4526 InstantiationVar->setLocation(Member->getLocation());
4527 }
4528
Douglas Gregor86d142a2009-10-08 07:24:58 +00004529 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4530 cast<VarDecl>(InstantiatedFrom),
4531 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004532 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004533 } else {
4534 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004535 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4536 if (InstantiationClass->getTemplateSpecializationKind() ==
4537 TSK_ImplicitInstantiation) {
4538 InstantiationClass->setTemplateSpecializationKind(
4539 TSK_ExplicitSpecialization);
4540 InstantiationClass->setLocation(Member->getLocation());
4541 }
4542
Douglas Gregor86d142a2009-10-08 07:24:58 +00004543 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004544 cast<CXXRecordDecl>(InstantiatedFrom),
4545 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004546 }
4547
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004548 // Save the caller the trouble of having to figure out which declaration
4549 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004550 Previous.clear();
4551 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004552 return false;
4553}
4554
Douglas Gregore47f5a72009-10-14 23:41:34 +00004555/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004556///
4557/// \returns true if a serious error occurs, false otherwise.
4558static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00004559 SourceLocation InstLoc,
4560 bool WasQualifiedName) {
4561 DeclContext *ExpectedContext
4562 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4563 DeclContext *CurContext = S.CurContext->getLookupContext();
4564
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004565 if (CurContext->isRecord()) {
4566 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4567 << D;
4568 return true;
4569 }
4570
Douglas Gregore47f5a72009-10-14 23:41:34 +00004571 // C++0x [temp.explicit]p2:
4572 // An explicit instantiation shall appear in an enclosing namespace of its
4573 // template.
4574 //
4575 // This is DR275, which we do not retroactively apply to C++98/03.
4576 if (S.getLangOptions().CPlusPlus0x &&
4577 !CurContext->Encloses(ExpectedContext)) {
4578 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004579 S.Diag(InstLoc,
4580 S.getLangOptions().CPlusPlus0x?
4581 diag::err_explicit_instantiation_out_of_scope
4582 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004583 << D << NS;
4584 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004585 S.Diag(InstLoc,
4586 S.getLangOptions().CPlusPlus0x?
4587 diag::err_explicit_instantiation_must_be_global
4588 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004589 << D;
4590 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004591 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004592 }
4593
4594 // C++0x [temp.explicit]p2:
4595 // If the name declared in the explicit instantiation is an unqualified
4596 // name, the explicit instantiation shall appear in the namespace where
4597 // its template is declared or, if that namespace is inline (7.3.1), any
4598 // namespace from its enclosing namespace set.
4599 if (WasQualifiedName)
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004600 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004601
4602 if (CurContext->Equals(ExpectedContext))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004603 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004604
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004605 S.Diag(InstLoc,
4606 S.getLangOptions().CPlusPlus0x?
4607 diag::err_explicit_instantiation_unqualified_wrong_namespace
4608 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004609 << D << ExpectedContext;
4610 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004611 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004612}
4613
4614/// \brief Determine whether the given scope specifier has a template-id in it.
4615static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4616 if (!SS.isSet())
4617 return false;
4618
4619 // C++0x [temp.explicit]p2:
4620 // If the explicit instantiation is for a member function, a member class
4621 // or a static data member of a class template specialization, the name of
4622 // the class template specialization in the qualified-id for the member
4623 // name shall be a simple-template-id.
4624 //
4625 // C++98 has the same restriction, just worded differently.
4626 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4627 NNS; NNS = NNS->getPrefix())
4628 if (Type *T = NNS->getAsType())
4629 if (isa<TemplateSpecializationType>(T))
4630 return true;
4631
4632 return false;
4633}
4634
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004635// Explicit instantiation of a class template specialization
Douglas Gregora1f49972009-05-13 00:25:59 +00004636Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004637Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004638 SourceLocation ExternLoc,
4639 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004640 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004641 SourceLocation KWLoc,
4642 const CXXScopeSpec &SS,
4643 TemplateTy TemplateD,
4644 SourceLocation TemplateNameLoc,
4645 SourceLocation LAngleLoc,
4646 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004647 SourceLocation RAngleLoc,
4648 AttributeList *Attr) {
4649 // Find the class template we're specializing
4650 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004651 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004652 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4653
4654 // Check that the specialization uses the same tag kind as the
4655 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004656 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4657 assert(Kind != TTK_Enum &&
4658 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004659 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004660 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004661 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004662 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004663 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004664 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004665 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004666 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004667 diag::note_previous_use);
4668 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4669 }
4670
Douglas Gregore47f5a72009-10-14 23:41:34 +00004671 // C++0x [temp.explicit]p2:
4672 // There are two forms of explicit instantiation: an explicit instantiation
4673 // definition and an explicit instantiation declaration. An explicit
4674 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004675 TemplateSpecializationKind TSK
4676 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4677 : TSK_ExplicitInstantiationDeclaration;
4678
Douglas Gregora1f49972009-05-13 00:25:59 +00004679 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004680 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004681 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004682
4683 // Check that the template argument list is well-formed for this
4684 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004685 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4686 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004687 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4688 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004689 return true;
4690
Mike Stump11289f42009-09-09 15:08:12 +00004691 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004692 ClassTemplate->getTemplateParameters()->size()) &&
4693 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004694
Douglas Gregora1f49972009-05-13 00:25:59 +00004695 // Find the class template specialization declaration that
4696 // corresponds to these arguments.
Douglas Gregora1f49972009-05-13 00:25:59 +00004697 void *InsertPos = 0;
4698 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004699 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4700 Converted.flatSize(), InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004701
Abramo Bagnara8075c852010-06-12 07:44:57 +00004702 TemplateSpecializationKind PrevDecl_TSK
4703 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4704
Douglas Gregor54888652009-10-07 00:13:32 +00004705 // C++0x [temp.explicit]p2:
4706 // [...] An explicit instantiation shall appear in an enclosing
4707 // namespace of its template. [...]
4708 //
4709 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004710 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4711 SS.isSet()))
4712 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004713
Douglas Gregora1f49972009-05-13 00:25:59 +00004714 ClassTemplateSpecializationDecl *Specialization = 0;
4715
Douglas Gregor0681a352009-11-25 06:01:46 +00004716 bool ReusedDecl = false;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004717 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004718 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00004719 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004720 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004721 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004722 HasNoEffect))
Douglas Gregora1f49972009-05-13 00:25:59 +00004723 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004724
Abramo Bagnara8075c852010-06-12 07:44:57 +00004725 // Even though HasNoEffect == true means that this explicit instantiation
4726 // has no effect on semantics, we go on to put its syntax in the AST.
4727
4728 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4729 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004730 // Since the only prior class template specialization with these
4731 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00004732 // declaration node as our own, updating the source location
4733 // for the template name to reflect our new declaration.
4734 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004735 Specialization = PrevDecl;
4736 Specialization->setLocation(TemplateNameLoc);
4737 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004738 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004739 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004740 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004741
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004742 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004743 // Create a new class template specialization declaration node for
4744 // this explicit specialization.
4745 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004746 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00004747 ClassTemplate->getDeclContext(),
4748 TemplateNameLoc,
4749 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004750 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004751 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004752
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004753 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00004754 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004755 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004756 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004757 }
4758
4759 // Build the fully-sugared type for this explicit instantiation as
4760 // the user wrote in the explicit instantiation itself. This means
4761 // that we'll pretty-print the type retrieved from the
4762 // specialization's declaration the way that the user actually wrote
4763 // the explicit instantiation, rather than formatting the name based
4764 // on the "canonical" representation used to store the template
4765 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004766 TypeSourceInfo *WrittenTy
4767 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4768 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004769 Context.getTypeDeclType(Specialization));
4770 Specialization->setTypeAsWritten(WrittenTy);
4771 TemplateArgsIn.release();
4772
Abramo Bagnara8075c852010-06-12 07:44:57 +00004773 // Set source locations for keywords.
4774 Specialization->setExternLoc(ExternLoc);
4775 Specialization->setTemplateKeywordLoc(TemplateLoc);
4776
4777 // Add the explicit instantiation into its lexical context. However,
4778 // since explicit instantiations are never found by name lookup, we
4779 // just put it into the declaration context directly.
4780 Specialization->setLexicalDeclContext(CurContext);
4781 CurContext->addDecl(Specialization);
4782
4783 // Syntax is now OK, so return if it has no other effect on semantics.
4784 if (HasNoEffect) {
4785 // Set the template specialization kind.
4786 Specialization->setTemplateSpecializationKind(TSK);
4787 return DeclPtrTy::make(Specialization);
Douglas Gregor0681a352009-11-25 06:01:46 +00004788 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004789
4790 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004791 // A definition of a class template or class member template
4792 // shall be in scope at the point of the explicit instantiation of
4793 // the class template or class member template.
4794 //
4795 // This check comes when we actually try to perform the
4796 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004797 ClassTemplateSpecializationDecl *Def
4798 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004799 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004800 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004801 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004802 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00004803 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004804 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
4805 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004806
Douglas Gregor1d957a32009-10-27 18:42:08 +00004807 // Instantiate the members of this class template specialization.
4808 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004809 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004810 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004811 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4812
4813 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4814 // TSK_ExplicitInstantiationDefinition
4815 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4816 TSK == TSK_ExplicitInstantiationDefinition)
4817 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004818
Douglas Gregor12e49d32009-10-15 22:53:21 +00004819 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004820 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004821
Abramo Bagnara8075c852010-06-12 07:44:57 +00004822 // Set the template specialization kind.
4823 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00004824 return DeclPtrTy::make(Specialization);
4825}
4826
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004827// Explicit instantiation of a member class of a class template.
4828Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004829Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004830 SourceLocation ExternLoc,
4831 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004832 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004833 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004834 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004835 IdentifierInfo *Name,
4836 SourceLocation NameLoc,
4837 AttributeList *Attr) {
4838
Douglas Gregord6ab8742009-05-28 23:31:59 +00004839 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004840 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004841 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004842 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004843 MultiTemplateParamsArg(*this, 0, 0),
4844 Owned, IsDependent);
4845 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4846
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004847 if (!TagD)
4848 return true;
4849
4850 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4851 if (Tag->isEnum()) {
4852 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4853 << Context.getTypeDeclType(Tag);
4854 return true;
4855 }
4856
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004857 if (Tag->isInvalidDecl())
4858 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004859
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004860 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4861 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4862 if (!Pattern) {
4863 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4864 << Context.getTypeDeclType(Record);
4865 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4866 return true;
4867 }
4868
Douglas Gregore47f5a72009-10-14 23:41:34 +00004869 // C++0x [temp.explicit]p2:
4870 // If the explicit instantiation is for a class or member class, the
4871 // elaborated-type-specifier in the declaration shall include a
4872 // simple-template-id.
4873 //
4874 // C++98 has the same restriction, just worded differently.
4875 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00004876 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004877 << Record << SS.getRange();
4878
4879 // C++0x [temp.explicit]p2:
4880 // There are two forms of explicit instantiation: an explicit instantiation
4881 // definition and an explicit instantiation declaration. An explicit
4882 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004883 TemplateSpecializationKind TSK
4884 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4885 : TSK_ExplicitInstantiationDeclaration;
4886
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004887 // C++0x [temp.explicit]p2:
4888 // [...] An explicit instantiation shall appear in an enclosing
4889 // namespace of its template. [...]
4890 //
4891 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004892 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004893
4894 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004895 CXXRecordDecl *PrevDecl
4896 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004897 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004898 PrevDecl = Record;
4899 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004900 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00004901 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004902 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004903 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004904 PrevDecl,
4905 MSInfo->getTemplateSpecializationKind(),
4906 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004907 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004908 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004909 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004910 return TagD;
4911 }
4912
Douglas Gregor12e49d32009-10-15 22:53:21 +00004913 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004914 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004915 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004916 // C++ [temp.explicit]p3:
4917 // A definition of a member class of a class template shall be in scope
4918 // at the point of an explicit instantiation of the member class.
4919 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004920 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004921 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004922 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4923 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004924 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4925 << Pattern;
4926 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004927 } else {
4928 if (InstantiateClass(NameLoc, Record, Def,
4929 getTemplateInstantiationArgs(Record),
4930 TSK))
4931 return true;
4932
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004933 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004934 if (!RecordDef)
4935 return true;
4936 }
4937 }
4938
4939 // Instantiate all of the members of the class.
4940 InstantiateClassMembers(NameLoc, RecordDef,
4941 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004942
Douglas Gregor88d292c2010-05-13 16:44:06 +00004943 if (TSK == TSK_ExplicitInstantiationDefinition)
4944 MarkVTableUsed(NameLoc, RecordDef, true);
4945
Mike Stump87c57ac2009-05-16 07:39:55 +00004946 // FIXME: We don't have any representation for explicit instantiations of
4947 // member classes. Such a representation is not needed for compilation, but it
4948 // should be available for clients that want to see all of the declarations in
4949 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004950 return TagD;
4951}
4952
Douglas Gregor450f00842009-09-25 18:43:00 +00004953Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4954 SourceLocation ExternLoc,
4955 SourceLocation TemplateLoc,
4956 Declarator &D) {
4957 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004958 // TODO: check if/when DNInfo should replace Name.
4959 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4960 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00004961 if (!Name) {
4962 if (!D.isInvalidType())
4963 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4964 diag::err_explicit_instantiation_requires_name)
4965 << D.getDeclSpec().getSourceRange()
4966 << D.getSourceRange();
4967
4968 return true;
4969 }
4970
4971 // The scope passed in may not be a decl scope. Zip up the scope tree until
4972 // we find one that is.
4973 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4974 (S->getFlags() & Scope::TemplateParamScope) != 0)
4975 S = S->getParent();
4976
4977 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00004978 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
4979 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00004980 if (R.isNull())
4981 return true;
4982
4983 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4984 // Cannot explicitly instantiate a typedef.
4985 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4986 << Name;
4987 return true;
4988 }
4989
Douglas Gregor3c74d412009-10-14 20:14:33 +00004990 // C++0x [temp.explicit]p1:
4991 // [...] An explicit instantiation of a function template shall not use the
4992 // inline or constexpr specifiers.
4993 // Presumably, this also applies to member functions of class templates as
4994 // well.
4995 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4996 Diag(D.getDeclSpec().getInlineSpecLoc(),
4997 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00004998 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004999
5000 // FIXME: check for constexpr specifier.
5001
Douglas Gregore47f5a72009-10-14 23:41:34 +00005002 // C++0x [temp.explicit]p2:
5003 // There are two forms of explicit instantiation: an explicit instantiation
5004 // definition and an explicit instantiation declaration. An explicit
5005 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00005006 TemplateSpecializationKind TSK
5007 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5008 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005009
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005010 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005011 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00005012
5013 if (!R->isFunctionType()) {
5014 // C++ [temp.explicit]p1:
5015 // A [...] static data member of a class template can be explicitly
5016 // instantiated from the member definition associated with its class
5017 // template.
John McCall27b18f82009-11-17 02:14:36 +00005018 if (Previous.isAmbiguous())
5019 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00005020
John McCall67c00872009-12-02 08:25:40 +00005021 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005022 if (!Prev || !Prev->isStaticDataMember()) {
5023 // We expect to see a data data member here.
5024 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5025 << Name;
5026 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5027 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005028 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005029 return true;
5030 }
5031
5032 if (!Prev->getInstantiatedFromStaticDataMember()) {
5033 // FIXME: Check for explicit specialization?
5034 Diag(D.getIdentifierLoc(),
5035 diag::err_explicit_instantiation_data_member_not_instantiated)
5036 << Prev;
5037 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5038 // FIXME: Can we provide a note showing where this was declared?
5039 return true;
5040 }
5041
Douglas Gregore47f5a72009-10-14 23:41:34 +00005042 // C++0x [temp.explicit]p2:
5043 // If the explicit instantiation is for a member function, a member class
5044 // or a static data member of a class template specialization, the name of
5045 // the class template specialization in the qualified-id for the member
5046 // name shall be a simple-template-id.
5047 //
5048 // C++98 has the same restriction, just worded differently.
5049 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5050 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005051 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005052 << Prev << D.getCXXScopeSpec().getRange();
5053
5054 // Check the scope of this explicit instantiation.
5055 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5056
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005057 // Verify that it is okay to explicitly instantiate here.
5058 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5059 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00005060 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005061 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005062 MSInfo->getTemplateSpecializationKind(),
5063 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005064 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005065 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005066 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005067 return DeclPtrTy();
5068
Douglas Gregor450f00842009-09-25 18:43:00 +00005069 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005070 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005071 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00005072 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
5073 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00005074
5075 // FIXME: Create an ExplicitInstantiation node?
5076 return DeclPtrTy();
5077 }
5078
Douglas Gregor0e876e02009-09-25 23:53:26 +00005079 // If the declarator is a template-id, translate the parser's template
5080 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005081 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005082 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005083 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5084 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005085 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5086 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005087 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5088 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005089 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005090 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005091 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005092 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005093 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005094
Douglas Gregor450f00842009-09-25 18:43:00 +00005095 // C++ [temp.explicit]p1:
5096 // A [...] function [...] can be explicitly instantiated from its template.
5097 // A member function [...] of a class template can be explicitly
5098 // instantiated from the member definition associated with its class
5099 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005100 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005101 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5102 P != PEnd; ++P) {
5103 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005104 if (!HasExplicitTemplateArgs) {
5105 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5106 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5107 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005108
John McCall58cc69d2010-01-27 01:50:18 +00005109 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005110 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5111 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005112 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005113 }
5114 }
5115
5116 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5117 if (!FunTmpl)
5118 continue;
5119
John McCallbc077cf2010-02-08 23:07:23 +00005120 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005121 FunctionDecl *Specialization = 0;
5122 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005123 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005124 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005125 R, Specialization, Info)) {
5126 // FIXME: Keep track of almost-matches?
5127 (void)TDK;
5128 continue;
5129 }
5130
John McCall58cc69d2010-01-27 01:50:18 +00005131 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005132 }
5133
5134 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005135 UnresolvedSetIterator Result
5136 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005137 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005138 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5139 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5140 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005141
John McCall58cc69d2010-01-27 01:50:18 +00005142 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005143 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005144
5145 // Ignore access control bits, we don't need them for redeclaration checking.
5146 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005147
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005148 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005149 Diag(D.getIdentifierLoc(),
5150 diag::err_explicit_instantiation_member_function_not_instantiated)
5151 << Specialization
5152 << (Specialization->getTemplateSpecializationKind() ==
5153 TSK_ExplicitSpecialization);
5154 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5155 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005156 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005157
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005158 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005159 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5160 PrevDecl = Specialization;
5161
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005162 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005163 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005164 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005165 PrevDecl,
5166 PrevDecl->getTemplateSpecializationKind(),
5167 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005168 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005169 return true;
5170
5171 // FIXME: We may still want to build some representation of this
5172 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00005173 if (HasNoEffect)
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005174 return DeclPtrTy();
5175 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005176
5177 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005178
5179 if (TSK == TSK_ExplicitInstantiationDefinition)
5180 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5181 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005182
Douglas Gregore47f5a72009-10-14 23:41:34 +00005183 // C++0x [temp.explicit]p2:
5184 // If the explicit instantiation is for a member function, a member class
5185 // or a static data member of a class template specialization, the name of
5186 // the class template specialization in the qualified-id for the member
5187 // name shall be a simple-template-id.
5188 //
5189 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005190 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005191 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005192 D.getCXXScopeSpec().isSet() &&
5193 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5194 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005195 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005196 << Specialization << D.getCXXScopeSpec().getRange();
5197
5198 CheckExplicitInstantiationScope(*this,
5199 FunTmpl? (NamedDecl *)FunTmpl
5200 : Specialization->getInstantiatedFromMemberFunction(),
5201 D.getIdentifierLoc(),
5202 D.getCXXScopeSpec().isSet());
5203
Douglas Gregor450f00842009-09-25 18:43:00 +00005204 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5205 return DeclPtrTy();
5206}
5207
Douglas Gregor333489b2009-03-27 23:10:48 +00005208Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005209Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5210 const CXXScopeSpec &SS, IdentifierInfo *Name,
5211 SourceLocation TagLoc, SourceLocation NameLoc) {
5212 // This has to hold, because SS is expected to be defined.
5213 assert(Name && "Expected a name in a dependent tag");
5214
5215 NestedNameSpecifier *NNS
5216 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5217 if (!NNS)
5218 return true;
5219
Abramo Bagnara6150c882010-05-11 21:36:43 +00005220 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005221
Douglas Gregorba41d012010-04-24 16:38:41 +00005222 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5223 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005224 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005225 return true;
5226 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005227
5228 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5229 return Context.getDependentNameType(Kwd, NNS, Name).getAsOpaquePtr();
John McCall7f41d982009-09-11 04:59:25 +00005230}
5231
5232Sema::TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005233Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5234 const CXXScopeSpec &SS, const IdentifierInfo &II,
5235 SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005236 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005237 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5238 if (!NNS)
5239 return true;
5240
Douglas Gregorf7d77712010-06-16 22:31:08 +00005241 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5242 !getLangOptions().CPlusPlus0x)
5243 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5244 << FixItHint::CreateRemoval(TypenameLoc);
5245
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005246 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005247 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005248 if (T.isNull())
5249 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005250
5251 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5252 if (isa<DependentNameType>(T)) {
5253 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005254 TL.setKeywordLoc(TypenameLoc);
5255 TL.setQualifierRange(SS.getRange());
5256 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005257 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005258 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005259 TL.setKeywordLoc(TypenameLoc);
5260 TL.setQualifierRange(SS.getRange());
5261 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005262 }
5263
5264 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor333489b2009-03-27 23:10:48 +00005265}
5266
Douglas Gregordce2b622009-04-01 00:28:59 +00005267Sema::TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005268Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5269 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
5270 TypeTy *Ty) {
5271 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5272 !getLangOptions().CPlusPlus0x)
5273 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5274 << FixItHint::CreateRemoval(TypenameLoc);
5275
John McCallf7bcc812010-05-28 23:32:21 +00005276 TypeSourceInfo *InnerTSI = 0;
5277 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCallf7bcc812010-05-28 23:32:21 +00005278
5279 assert(isa<TemplateSpecializationType>(T) &&
5280 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005281
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005282 if (computeDeclContext(SS, false)) {
5283 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005284 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005285 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005286
5287 // Push the inner type, preserving its source locations if possible.
5288 TypeLocBuilder Builder;
5289 if (InnerTSI)
5290 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5291 else
5292 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5293
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005294 /* Note: NNS already embedded in template specialization type T. */
5295 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCallf7bcc812010-05-28 23:32:21 +00005296 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5297 TL.setKeywordLoc(TypenameLoc);
5298 TL.setQualifierRange(SS.getRange());
5299
5300 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCall99b2fe52010-04-29 23:50:39 +00005301 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005302 }
Mike Stump11289f42009-09-09 15:08:12 +00005303
John McCallc392f372010-06-11 00:33:02 +00005304 // TODO: it's really silly that we make a template specialization
5305 // type earlier only to drop it again here.
5306 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5307 DependentTemplateName *DTN =
5308 TST->getTemplateName().getAsDependentTemplateName();
5309 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005310 assert(DTN->getQualifier()
5311 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5312 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5313 DTN->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00005314 DTN->getIdentifier(),
5315 TST->getNumArgs(),
5316 TST->getArgs());
John McCall99b2fe52010-04-29 23:50:39 +00005317 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCallc392f372010-06-11 00:33:02 +00005318 DependentTemplateSpecializationTypeLoc TL =
5319 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5320 if (InnerTSI) {
5321 TemplateSpecializationTypeLoc TSTL =
5322 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5323 TL.setLAngleLoc(TSTL.getLAngleLoc());
5324 TL.setRAngleLoc(TSTL.getRAngleLoc());
5325 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5326 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5327 } else {
5328 TL.initializeLocal(SourceLocation());
5329 }
John McCallf7bcc812010-05-28 23:32:21 +00005330 TL.setKeywordLoc(TypenameLoc);
5331 TL.setQualifierRange(SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005332 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00005333}
5334
Douglas Gregor333489b2009-03-27 23:10:48 +00005335/// \brief Build the type that describes a C++ typename specifier,
5336/// e.g., "typename T::type".
5337QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005338Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5339 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005340 SourceLocation KeywordLoc, SourceRange NNSRange,
5341 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005342 CXXScopeSpec SS;
5343 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005344 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005345
John McCall0b66eb32010-05-01 00:40:08 +00005346 DeclContext *Ctx = computeDeclContext(SS);
5347 if (!Ctx) {
5348 // If the nested-name-specifier is dependent and couldn't be
5349 // resolved to a type, build a typename type.
5350 assert(NNS->isDependent());
5351 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005352 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005353
John McCall0b66eb32010-05-01 00:40:08 +00005354 // If the nested-name-specifier refers to the current instantiation,
5355 // the "typename" keyword itself is superfluous. In C++03, the
5356 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5357 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00005358 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005359
John McCall0b66eb32010-05-01 00:40:08 +00005360 if (RequireCompleteDeclContext(SS, Ctx))
5361 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005362
5363 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005364 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005365 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005366 unsigned DiagID = 0;
5367 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005368 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005369 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005370 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005371 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005372
5373 case LookupResult::NotFoundInCurrentInstantiation:
5374 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005375 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005376
5377 case LookupResult::Found:
Douglas Gregorf7d77712010-06-16 22:31:08 +00005378 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005379 // We found a type. Build an ElaboratedType, since the
5380 // typename-specifier was just sugar.
5381 return Context.getElaboratedType(ETK_Typename, NNS,
5382 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005383 }
5384
5385 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005386 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005387 break;
5388
John McCalle61f2ba2009-11-18 02:36:19 +00005389 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005390 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005391 return QualType();
5392
Douglas Gregor333489b2009-03-27 23:10:48 +00005393 case LookupResult::FoundOverloaded:
5394 DiagID = diag::err_typename_nested_not_type;
5395 Referenced = *Result.begin();
5396 break;
5397
John McCall6538c932009-10-10 05:48:19 +00005398 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005399 return QualType();
5400 }
5401
5402 // If we get here, it's because name lookup did not find a
5403 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005404 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5405 IILoc);
5406 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005407 if (Referenced)
5408 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5409 << Name;
5410 return QualType();
5411}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005412
5413namespace {
5414 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005415 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005416 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005417 SourceLocation Loc;
5418 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005419
Douglas Gregor15acfb92009-08-06 16:20:37 +00005420 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005421 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5422
Mike Stump11289f42009-09-09 15:08:12 +00005423 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005424 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005425 DeclarationName Entity)
5426 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005427 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005428
5429 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005430 /// transformed.
5431 ///
5432 /// For the purposes of type reconstruction, a type has already been
5433 /// transformed if it is NULL or if it is not dependent.
5434 bool AlreadyTransformed(QualType T) {
5435 return T.isNull() || !T->isDependentType();
5436 }
Mike Stump11289f42009-09-09 15:08:12 +00005437
5438 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005439 /// rebuilt.
5440 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005441
Douglas Gregor15acfb92009-08-06 16:20:37 +00005442 /// \brief Returns the name of the entity whose type is being rebuilt.
5443 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005444
Douglas Gregoref6ab412009-10-27 06:26:26 +00005445 /// \brief Sets the "base" location and entity when that
5446 /// information is known based on another transformation.
5447 void setBase(SourceLocation Loc, DeclarationName Entity) {
5448 this->Loc = Loc;
5449 this->Entity = Entity;
5450 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00005451 };
5452}
5453
Douglas Gregor15acfb92009-08-06 16:20:37 +00005454/// \brief Rebuilds a type within the context of the current instantiation.
5455///
Mike Stump11289f42009-09-09 15:08:12 +00005456/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005457/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005458/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005459/// partial specialization thereof). This routine will rebuild that type now
5460/// that we have entered the declarator's scope, which may produce different
5461/// canonical types, e.g.,
5462///
5463/// \code
5464/// template<typename T>
5465/// struct X {
5466/// typedef T* pointer;
5467/// pointer data();
5468/// };
5469///
5470/// template<typename T>
5471/// typename X<T>::pointer X<T>::data() { ... }
5472/// \endcode
5473///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005474/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005475/// since we do not know that we can look into X<T> when we parsed the type.
5476/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005477/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005478/// as the canonical type of T*, allowing the return types of the out-of-line
5479/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005480TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5481 SourceLocation Loc,
5482 DeclarationName Name) {
5483 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005484 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005485
Douglas Gregor15acfb92009-08-06 16:20:37 +00005486 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5487 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005488}
Douglas Gregorbe999392009-09-15 16:23:51 +00005489
John McCall99b2fe52010-04-29 23:50:39 +00005490bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5491 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005492
5493 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5494 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5495 DeclarationName());
5496 NestedNameSpecifier *Rebuilt =
5497 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005498 if (!Rebuilt) return true;
5499
5500 SS.setScopeRep(Rebuilt);
5501 return false;
John McCall2408e322010-04-27 00:57:59 +00005502}
5503
Douglas Gregorbe999392009-09-15 16:23:51 +00005504/// \brief Produces a formatted string that describes the binding of
5505/// template parameters to template arguments.
5506std::string
5507Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5508 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005509 // FIXME: For variadic templates, we'll need to get the structured list.
5510 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5511 Args.flat_size());
5512}
5513
5514std::string
5515Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5516 const TemplateArgument *Args,
5517 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005518 std::string Result;
5519
Douglas Gregore62e6a02009-11-11 19:13:48 +00005520 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005521 return Result;
5522
5523 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005524 if (I >= NumArgs)
5525 break;
5526
Douglas Gregorbe999392009-09-15 16:23:51 +00005527 if (I == 0)
5528 Result += "[with ";
5529 else
5530 Result += ", ";
5531
5532 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5533 Result += Id->getName();
5534 } else {
5535 Result += '$';
5536 Result += llvm::utostr(I);
5537 }
5538
5539 Result += " = ";
5540
5541 switch (Args[I].getKind()) {
5542 case TemplateArgument::Null:
5543 Result += "<no value>";
5544 break;
5545
5546 case TemplateArgument::Type: {
5547 std::string TypeStr;
5548 Args[I].getAsType().getAsStringInternal(TypeStr,
5549 Context.PrintingPolicy);
5550 Result += TypeStr;
5551 break;
5552 }
5553
5554 case TemplateArgument::Declaration: {
5555 bool Unnamed = true;
5556 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5557 if (ND->getDeclName()) {
5558 Unnamed = false;
5559 Result += ND->getNameAsString();
5560 }
5561 }
5562
5563 if (Unnamed) {
5564 Result += "<anonymous>";
5565 }
5566 break;
5567 }
5568
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005569 case TemplateArgument::Template: {
5570 std::string Str;
5571 llvm::raw_string_ostream OS(Str);
5572 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5573 Result += OS.str();
5574 break;
5575 }
5576
Douglas Gregorbe999392009-09-15 16:23:51 +00005577 case TemplateArgument::Integral: {
5578 Result += Args[I].getAsIntegral()->toString(10);
5579 break;
5580 }
5581
5582 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005583 // FIXME: This is non-optimal, since we're regurgitating the
5584 // expression we were given.
5585 std::string Str;
5586 {
5587 llvm::raw_string_ostream OS(Str);
5588 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5589 Context.PrintingPolicy);
5590 }
5591 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005592 break;
5593 }
5594
5595 case TemplateArgument::Pack:
5596 // FIXME: Format template argument packs
5597 Result += "<template argument pack>";
5598 break;
5599 }
5600 }
5601
5602 Result += ']';
5603 return Result;
5604}