blob: 05d0ec172aae4fed792a9bec390d58c41af251eb [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"
John McCall8b0666c2010-08-20 18:27:03 +000020#include "clang/Sema/DeclSpec.h"
21#include "clang/Sema/ParsedTemplate.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,
John McCallba7bf592010-08-24 05:47:05 +0000107 ParsedType 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 McCallba7bf592010-08-24 05:47:05 +0000134 QualType ObjectType = ObjectTypePtr.get();
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 McCalldadc5752010-08-24 06:29:42 +0000347ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000348Sema::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
John McCalldadc5752010-08-24 06:29:42 +0000379ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000380Sema::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.
John McCall48871652010-08-21 09:40:31 +0000413TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
414 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
415 D = 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: {
John McCall3e56fd42010-08-23 07:28:44 +0000439 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000440 return TemplateArgumentLoc(TemplateArgument(Template),
441 Arg.getScopeSpec().getRange(),
442 Arg.getLocation());
443 }
444 }
445
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000446 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000447 return TemplateArgumentLoc();
448}
449
450/// \brief Translates template arguments as provided by the parser
451/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000452void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
453 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000454 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000455 TemplateArgs.addArgument(translateTemplateArgument(*this,
456 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000457}
458
Douglas Gregor5101c242008-12-05 18:15:24 +0000459/// ActOnTypeParameter - Called when a C++ template type parameter
460/// (e.g., "typename T") has been parsed. Typename specifies whether
461/// the keyword "typename" was used to declare the type parameter
462/// (otherwise, "class" was used), and KeyLoc is the location of the
463/// "class" or "typename" keyword. ParamName is the name of the
464/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregor2ebcae12010-06-16 15:23:05 +0000465/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000466/// If the type parameter has a default argument, it will be added
467/// later via ActOnTypeParameterDefault.
John McCall48871652010-08-21 09:40:31 +0000468Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
469 SourceLocation EllipsisLoc,
470 SourceLocation KeyLoc,
471 IdentifierInfo *ParamName,
472 SourceLocation ParamNameLoc,
473 unsigned Depth, unsigned Position,
474 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000475 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000476 assert(S->isTemplateParamScope() &&
477 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000478 bool Invalid = false;
479
480 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000481 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000482 LookupOrdinaryName,
483 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000484 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000485 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000486 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000487 }
488
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000489 SourceLocation Loc = ParamNameLoc;
490 if (!ParamName)
491 Loc = KeyLoc;
492
Douglas Gregor5101c242008-12-05 18:15:24 +0000493 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000494 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
495 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000496 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000497 if (Invalid)
498 Param->setInvalidDecl();
499
500 if (ParamName) {
501 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000502 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000503 IdResolver.AddDecl(Param);
504 }
505
Douglas Gregordc13ded2010-07-01 00:00:45 +0000506 // Handle the default argument, if provided.
507 if (DefaultArg) {
508 TypeSourceInfo *DefaultTInfo;
509 GetTypeFromParser(DefaultArg, &DefaultTInfo);
510
511 assert(DefaultTInfo && "expected source information for type");
512
513 // C++0x [temp.param]p9:
514 // A default template-argument may be specified for any kind of
515 // template-parameter that is not a template parameter pack.
516 if (Ellipsis) {
517 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
John McCall48871652010-08-21 09:40:31 +0000518 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000519 }
520
521 // Check the template argument itself.
522 if (CheckTemplateArgument(Param, DefaultTInfo)) {
523 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000524 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000525 }
526
527 Param->setDefaultArgument(DefaultTInfo, false);
528 }
529
John McCall48871652010-08-21 09:40:31 +0000530 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000531}
532
Douglas Gregor463421d2009-03-03 04:44:36 +0000533/// \brief Check that the type of a non-type template parameter is
534/// well-formed.
535///
536/// \returns the (possibly-promoted) parameter type if valid;
537/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000538QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000539Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000540 // We don't allow variably-modified types as the type of non-type template
541 // parameters.
542 if (T->isVariablyModifiedType()) {
543 Diag(Loc, diag::err_variably_modified_nontype_template_param)
544 << T;
545 return QualType();
546 }
547
Douglas Gregor463421d2009-03-03 04:44:36 +0000548 // C++ [temp.param]p4:
549 //
550 // A non-type template-parameter shall have one of the following
551 // (optionally cv-qualified) types:
552 //
553 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000554 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000555 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000556 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000557 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000558 T->isReferenceType() ||
559 // -- pointer to member.
560 T->isMemberPointerType() ||
561 // If T is a dependent type, we can't do the check now, so we
562 // assume that it is well-formed.
563 T->isDependentType())
564 return T;
565 // C++ [temp.param]p8:
566 //
567 // A non-type template-parameter of type "array of T" or
568 // "function returning T" is adjusted to be of type "pointer to
569 // T" or "pointer to function returning T", respectively.
570 else if (T->isArrayType())
571 // FIXME: Keep the type prior to promotion?
572 return Context.getArrayDecayedType(T);
573 else if (T->isFunctionType())
574 // FIXME: Keep the type prior to promotion?
575 return Context.getPointerType(T);
Douglas Gregor959d5a02010-05-22 16:17:30 +0000576
Douglas Gregor463421d2009-03-03 04:44:36 +0000577 Diag(Loc, diag::err_template_nontype_parm_bad_type)
578 << T;
579
580 return QualType();
581}
582
John McCall48871652010-08-21 09:40:31 +0000583Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
584 unsigned Depth,
585 unsigned Position,
586 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000587 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000588 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
589 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000590
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000591 assert(S->isTemplateParamScope() &&
592 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000593 bool Invalid = false;
594
595 IdentifierInfo *ParamName = D.getIdentifier();
596 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000597 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000598 LookupOrdinaryName,
599 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000600 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000601 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000602 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000603 }
604
Douglas Gregor463421d2009-03-03 04:44:36 +0000605 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000606 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000607 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000608 Invalid = true;
609 }
Douglas Gregor81338792009-02-10 17:43:50 +0000610
Douglas Gregor5101c242008-12-05 18:15:24 +0000611 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000612 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
613 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000614 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000615 if (Invalid)
616 Param->setInvalidDecl();
617
618 if (D.getIdentifier()) {
619 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000620 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000621 IdResolver.AddDecl(Param);
622 }
Douglas Gregordc13ded2010-07-01 00:00:45 +0000623
624 // Check the well-formedness of the default template argument, if provided.
John McCallb268a282010-08-23 23:25:46 +0000625 if (Default) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000626 TemplateArgument Converted;
627 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
628 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000629 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000630 }
631
John McCallb268a282010-08-23 23:25:46 +0000632 Param->setDefaultArgument(Default, false);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000633 }
634
John McCall48871652010-08-21 09:40:31 +0000635 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000636}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000637
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000638/// ActOnTemplateTemplateParameter - Called when a C++ template template
639/// parameter (e.g. T in template <template <typename> class T> class array)
640/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000641Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
642 SourceLocation TmpLoc,
643 TemplateParamsTy *Params,
644 IdentifierInfo *Name,
645 SourceLocation NameLoc,
646 unsigned Depth,
647 unsigned Position,
648 SourceLocation EqualLoc,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000649 const ParsedTemplateArgument &Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000650 assert(S->isTemplateParamScope() &&
651 "Template template parameter not in template parameter scope!");
652
653 // Construct the parameter object.
654 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000655 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
656 TmpLoc, Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000657 (TemplateParameterList*)Params);
658
Douglas Gregordc13ded2010-07-01 00:00:45 +0000659 // If the template template parameter has a name, then link the identifier
660 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000661 if (Name) {
John McCall48871652010-08-21 09:40:31 +0000662 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000663 IdResolver.AddDecl(Param);
664 }
665
Douglas Gregordc13ded2010-07-01 00:00:45 +0000666 if (!Default.isInvalid()) {
667 // Check only that we have a template template argument. We don't want to
668 // try to check well-formedness now, because our template template parameter
669 // might have dependent types in its template parameters, which we wouldn't
670 // be able to match now.
671 //
672 // If none of the template template parameter's template arguments mention
673 // other template parameters, we could actually perform more checking here.
674 // However, it isn't worth doing.
675 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
676 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
677 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
678 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000679 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000680 }
681
682 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000683 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000684
John McCall48871652010-08-21 09:40:31 +0000685 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000686}
687
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000688/// ActOnTemplateParameterList - Builds a TemplateParameterList that
689/// contains the template parameters in Params/NumParams.
690Sema::TemplateParamsTy *
691Sema::ActOnTemplateParameterList(unsigned Depth,
692 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000693 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000694 SourceLocation LAngleLoc,
John McCall48871652010-08-21 09:40:31 +0000695 Decl **Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000696 SourceLocation RAngleLoc) {
697 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000698 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000699
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000700 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000701 (NamedDecl**)Params, NumParams,
702 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000703}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000704
John McCall3e11ebe2010-03-15 10:12:16 +0000705static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
706 if (SS.isSet())
707 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
708 SS.getRange());
709}
710
Douglas Gregorc08f4892009-03-25 00:13:59 +0000711Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000712Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000713 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000714 IdentifierInfo *Name, SourceLocation NameLoc,
715 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000716 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000717 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000718 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000719 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000720 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000721 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000722
723 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000724 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000725 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000726
Abramo Bagnara6150c882010-05-11 21:36:43 +0000727 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
728 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000729
730 // There is no such thing as an unnamed class template.
731 if (!Name) {
732 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000733 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000734 }
735
736 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000737 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000738 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000739 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000740 if (SS.isNotEmpty() && !SS.isInvalid()) {
741 SemanticContext = computeDeclContext(SS, true);
742 if (!SemanticContext) {
743 // FIXME: Produce a reasonable diagnostic here
744 return true;
745 }
Mike Stump11289f42009-09-09 15:08:12 +0000746
John McCall0b66eb32010-05-01 00:40:08 +0000747 if (RequireCompleteDeclContext(SS, SemanticContext))
748 return true;
749
John McCall27b18f82009-11-17 02:14:36 +0000750 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000751 } else {
752 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000753 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000754 }
Mike Stump11289f42009-09-09 15:08:12 +0000755
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000756 if (Previous.isAmbiguous())
757 return true;
758
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000759 NamedDecl *PrevDecl = 0;
760 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000761 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000762
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000763 // If there is a previous declaration with the same name, check
764 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000765 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000766 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000767
768 // We may have found the injected-class-name of a class template,
769 // class template partial specialization, or class template specialization.
770 // In these cases, grab the template that is being defined or specialized.
771 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
772 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
773 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
774 PrevClassTemplate
775 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
776 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
777 PrevClassTemplate
778 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
779 ->getSpecializedTemplate();
780 }
781 }
782
John McCalld43784f2009-12-18 11:25:59 +0000783 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000784 // C++ [namespace.memdef]p3:
785 // [...] When looking for a prior declaration of a class or a function
786 // declared as a friend, and when the name of the friend class or
787 // function is neither a qualified name nor a template-id, scopes outside
788 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000789 if (!SS.isSet()) {
790 DeclContext *OutermostContext = CurContext;
791 while (!OutermostContext->isFileContext())
792 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000793
Douglas Gregorb74b1032010-04-18 17:37:40 +0000794 if (PrevDecl &&
795 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
796 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
797 SemanticContext = PrevDecl->getDeclContext();
798 } else {
799 // Declarations in outer scopes don't matter. However, the outermost
800 // context we computed is the semantic context for our new
801 // declaration.
802 PrevDecl = PrevClassTemplate = 0;
803 SemanticContext = OutermostContext;
804 }
John McCall90d3bb92009-12-17 23:21:11 +0000805 }
Douglas Gregorb74b1032010-04-18 17:37:40 +0000806
John McCall90d3bb92009-12-17 23:21:11 +0000807 if (CurContext->isDependentContext()) {
808 // If this is a dependent context, we don't want to link the friend
809 // class template to the template in scope, because that would perform
810 // checking of the template parameter lists that can't be performed
811 // until the outer context is instantiated.
812 PrevDecl = PrevClassTemplate = 0;
813 }
814 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
815 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000816
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000817 if (PrevClassTemplate) {
818 // Ensure that the template parameter lists are compatible.
819 if (!TemplateParameterListsAreEqual(TemplateParams,
820 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000821 /*Complain=*/true,
822 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000823 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000824
825 // C++ [temp.class]p4:
826 // In a redeclaration, partial specialization, explicit
827 // specialization or explicit instantiation of a class template,
828 // the class-key shall agree in kind with the original class
829 // template declaration (7.1.5.3).
830 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000831 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000832 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000833 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000834 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000835 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000836 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000837 }
838
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000839 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000840 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000841 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000842 Diag(NameLoc, diag::err_redefinition) << Name;
843 Diag(Def->getLocation(), diag::note_previous_definition);
844 // FIXME: Would it make sense to try to "forget" the previous
845 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000846 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000847 }
848 }
849 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
850 // Maybe we will complain about the shadowed template parameter.
851 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
852 // Just pretend that we didn't see the previous declaration.
853 PrevDecl = 0;
854 } else if (PrevDecl) {
855 // C++ [temp]p5:
856 // A class template shall not have the same name as any other
857 // template, class, function, object, enumeration, enumerator,
858 // namespace, or type in the same scope (3.3), except as specified
859 // in (14.5.4).
860 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
861 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000862 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000863 }
864
Douglas Gregordba32632009-02-10 19:49:53 +0000865 // Check the template parameter list of this declaration, possibly
866 // merging in the template parameter list from the previous class
867 // template declaration.
868 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000869 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
870 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000871 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000872
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000873 if (SS.isSet()) {
874 // If the name of the template was qualified, we must be defining the
875 // template out-of-line.
876 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
877 !(TUK == TUK_Friend && CurContext->isDependentContext()))
878 Diag(NameLoc, diag::err_member_def_does_not_match)
879 << Name << SemanticContext << SS.getRange();
880 }
881
Mike Stump11289f42009-09-09 15:08:12 +0000882 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000883 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000884 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000885 PrevClassTemplate->getTemplatedDecl() : 0,
886 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000887 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000888
889 ClassTemplateDecl *NewTemplate
890 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
891 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000892 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000893 NewClass->setDescribedClassTemplate(NewTemplate);
894
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000895 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000896 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +0000897 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000898 assert(T->isDependentType() && "Class template type is not dependent?");
899 (void)T;
900
Douglas Gregorcf915552009-10-13 16:30:37 +0000901 // If we are providing an explicit specialization of a member that is a
902 // class template, make a note of that.
903 if (PrevClassTemplate &&
904 PrevClassTemplate->getInstantiatedFromMemberTemplate())
905 PrevClassTemplate->setMemberSpecialization();
906
Anders Carlsson137108d2009-03-26 01:24:28 +0000907 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000908 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000909 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000910
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000911 // Set the lexical context of these templates
912 NewClass->setLexicalDeclContext(CurContext);
913 NewTemplate->setLexicalDeclContext(CurContext);
914
John McCall9bb74a52009-07-31 02:45:11 +0000915 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000916 NewClass->startDefinition();
917
918 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000919 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000920
John McCall27b5c252009-09-14 21:59:20 +0000921 if (TUK != TUK_Friend)
922 PushOnScopeChains(NewTemplate, S);
923 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000924 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000925 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000926 NewClass->setAccess(PrevClassTemplate->getAccess());
927 }
John McCall27b5c252009-09-14 21:59:20 +0000928
Douglas Gregor3dad8422009-09-26 06:47:28 +0000929 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
930 PrevClassTemplate != NULL);
931
John McCall27b5c252009-09-14 21:59:20 +0000932 // Friend templates are visible in fairly strange ways.
933 if (!CurContext->isDependentContext()) {
934 DeclContext *DC = SemanticContext->getLookupContext();
935 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
936 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
937 PushOnScopeChains(NewTemplate, EnclosingScope,
938 /* AddToContext = */ false);
939 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000940
941 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
942 NewClass->getLocation(),
943 NewTemplate,
944 /*FIXME:*/NewClass->getLocation());
945 Friend->setAccess(AS_public);
946 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000947 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000948
Douglas Gregordba32632009-02-10 19:49:53 +0000949 if (Invalid) {
950 NewTemplate->setInvalidDecl();
951 NewClass->setInvalidDecl();
952 }
John McCall48871652010-08-21 09:40:31 +0000953 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000954}
955
Douglas Gregored5731f2009-11-25 17:50:39 +0000956/// \brief Diagnose the presence of a default template argument on a
957/// template parameter, which is ill-formed in certain contexts.
958///
959/// \returns true if the default template argument should be dropped.
960static bool DiagnoseDefaultTemplateArgument(Sema &S,
961 Sema::TemplateParamListContext TPC,
962 SourceLocation ParamLoc,
963 SourceRange DefArgRange) {
964 switch (TPC) {
965 case Sema::TPC_ClassTemplate:
966 return false;
967
968 case Sema::TPC_FunctionTemplate:
969 // C++ [temp.param]p9:
970 // A default template-argument shall not be specified in a
971 // function template declaration or a function template
972 // definition [...]
973 // (This sentence is not in C++0x, per DR226).
974 if (!S.getLangOptions().CPlusPlus0x)
975 S.Diag(ParamLoc,
976 diag::err_template_parameter_default_in_function_template)
977 << DefArgRange;
978 return false;
979
980 case Sema::TPC_ClassTemplateMember:
981 // C++0x [temp.param]p9:
982 // A default template-argument shall not be specified in the
983 // template-parameter-lists of the definition of a member of a
984 // class template that appears outside of the member's class.
985 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
986 << DefArgRange;
987 return true;
988
989 case Sema::TPC_FriendFunctionTemplate:
990 // C++ [temp.param]p9:
991 // A default template-argument shall not be specified in a
992 // friend template declaration.
993 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
994 << DefArgRange;
995 return true;
996
997 // FIXME: C++0x [temp.param]p9 allows default template-arguments
998 // for friend function templates if there is only a single
999 // declaration (and it is a definition). Strange!
1000 }
1001
1002 return false;
1003}
1004
Douglas Gregordba32632009-02-10 19:49:53 +00001005/// \brief Checks the validity of a template parameter list, possibly
1006/// considering the template parameter list from a previous
1007/// declaration.
1008///
1009/// If an "old" template parameter list is provided, it must be
1010/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1011/// template parameter list.
1012///
1013/// \param NewParams Template parameter list for a new template
1014/// declaration. This template parameter list will be updated with any
1015/// default arguments that are carried through from the previous
1016/// template parameter list.
1017///
1018/// \param OldParams If provided, template parameter list from a
1019/// previous declaration of the same template. Default template
1020/// arguments will be merged from the old template parameter list to
1021/// the new template parameter list.
1022///
Douglas Gregored5731f2009-11-25 17:50:39 +00001023/// \param TPC Describes the context in which we are checking the given
1024/// template parameter list.
1025///
Douglas Gregordba32632009-02-10 19:49:53 +00001026/// \returns true if an error occurred, false otherwise.
1027bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001028 TemplateParameterList *OldParams,
1029 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001030 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001031
Douglas Gregordba32632009-02-10 19:49:53 +00001032 // C++ [temp.param]p10:
1033 // The set of default template-arguments available for use with a
1034 // template declaration or definition is obtained by merging the
1035 // default arguments from the definition (if in scope) and all
1036 // declarations in scope in the same way default function
1037 // arguments are (8.3.6).
1038 bool SawDefaultArgument = false;
1039 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001040
Anders Carlsson327865d2009-06-12 23:20:15 +00001041 bool SawParameterPack = false;
1042 SourceLocation ParameterPackLoc;
1043
Mike Stumpc89c8e32009-02-11 23:03:27 +00001044 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001045 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001046 if (OldParams)
1047 OldParam = OldParams->begin();
1048
1049 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1050 NewParamEnd = NewParams->end();
1051 NewParam != NewParamEnd; ++NewParam) {
1052 // Variables used to diagnose redundant default arguments
1053 bool RedundantDefaultArg = false;
1054 SourceLocation OldDefaultLoc;
1055 SourceLocation NewDefaultLoc;
1056
1057 // Variables used to diagnose missing default arguments
1058 bool MissingDefaultArg = false;
1059
Anders Carlsson327865d2009-06-12 23:20:15 +00001060 // C++0x [temp.param]p11:
1061 // If a template parameter of a class template is a template parameter pack,
1062 // it must be the last template parameter.
1063 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001064 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001065 diag::err_template_param_pack_must_be_last_template_parameter);
1066 Invalid = true;
1067 }
1068
Douglas Gregordba32632009-02-10 19:49:53 +00001069 if (TemplateTypeParmDecl *NewTypeParm
1070 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001071 // Check the presence of a default argument here.
1072 if (NewTypeParm->hasDefaultArgument() &&
1073 DiagnoseDefaultTemplateArgument(*this, TPC,
1074 NewTypeParm->getLocation(),
1075 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001076 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001077 NewTypeParm->removeDefaultArgument();
1078
1079 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001080 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001081 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001082
Anders Carlsson327865d2009-06-12 23:20:15 +00001083 if (NewTypeParm->isParameterPack()) {
1084 assert(!NewTypeParm->hasDefaultArgument() &&
1085 "Parameter packs can't have a default argument!");
1086 SawParameterPack = true;
1087 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001088 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001089 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001090 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1091 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1092 SawDefaultArgument = true;
1093 RedundantDefaultArg = true;
1094 PreviousDefaultArgLoc = NewDefaultLoc;
1095 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1096 // Merge the default argument from the old declaration to the
1097 // new declaration.
1098 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001099 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001100 true);
1101 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1102 } else if (NewTypeParm->hasDefaultArgument()) {
1103 SawDefaultArgument = true;
1104 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1105 } else if (SawDefaultArgument)
1106 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001107 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001108 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001109 // Check the presence of a default argument here.
1110 if (NewNonTypeParm->hasDefaultArgument() &&
1111 DiagnoseDefaultTemplateArgument(*this, TPC,
1112 NewNonTypeParm->getLocation(),
1113 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001114 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001115 }
1116
Mike Stump12b8ce12009-08-04 21:02:39 +00001117 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001118 NonTypeTemplateParmDecl *OldNonTypeParm
1119 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001120 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001121 NewNonTypeParm->hasDefaultArgument()) {
1122 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1123 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1124 SawDefaultArgument = true;
1125 RedundantDefaultArg = true;
1126 PreviousDefaultArgLoc = NewDefaultLoc;
1127 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1128 // Merge the default argument from the old declaration to the
1129 // new declaration.
1130 SawDefaultArgument = true;
1131 // FIXME: We need to create a new kind of "default argument"
1132 // expression that points to a previous template template
1133 // parameter.
1134 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001135 OldNonTypeParm->getDefaultArgument(),
1136 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001137 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1138 } else if (NewNonTypeParm->hasDefaultArgument()) {
1139 SawDefaultArgument = true;
1140 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1141 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001142 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001143 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001144 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001145 TemplateTemplateParmDecl *NewTemplateParm
1146 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001147 if (NewTemplateParm->hasDefaultArgument() &&
1148 DiagnoseDefaultTemplateArgument(*this, TPC,
1149 NewTemplateParm->getLocation(),
1150 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001151 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001152
1153 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001154 TemplateTemplateParmDecl *OldTemplateParm
1155 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001156 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001157 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001158 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1159 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001160 SawDefaultArgument = true;
1161 RedundantDefaultArg = true;
1162 PreviousDefaultArgLoc = NewDefaultLoc;
1163 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1164 // Merge the default argument from the old declaration to the
1165 // new declaration.
1166 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001167 // FIXME: We need to create a new kind of "default argument" expression
1168 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001169 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001170 OldTemplateParm->getDefaultArgument(),
1171 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001172 PreviousDefaultArgLoc
1173 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001174 } else if (NewTemplateParm->hasDefaultArgument()) {
1175 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001176 PreviousDefaultArgLoc
1177 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001178 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001179 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001180 }
1181
1182 if (RedundantDefaultArg) {
1183 // C++ [temp.param]p12:
1184 // A template-parameter shall not be given default arguments
1185 // by two different declarations in the same scope.
1186 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1187 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1188 Invalid = true;
1189 } else if (MissingDefaultArg) {
1190 // C++ [temp.param]p11:
1191 // If a template-parameter has a default template-argument,
1192 // all subsequent template-parameters shall have a default
1193 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001194 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001195 diag::err_template_param_default_arg_missing);
1196 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1197 Invalid = true;
1198 }
1199
1200 // If we have an old template parameter list that we're merging
1201 // in, move on to the next parameter.
1202 if (OldParams)
1203 ++OldParam;
1204 }
1205
1206 return Invalid;
1207}
Douglas Gregord32e0282009-02-09 23:23:08 +00001208
Mike Stump11289f42009-09-09 15:08:12 +00001209/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001210/// specifier, returning the template parameter list that applies to the
1211/// name.
1212///
1213/// \param DeclStartLoc the start of the declaration that has a scope
1214/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001215///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001216/// \param SS the scope specifier that will be matched to the given template
1217/// parameter lists. This scope specifier precedes a qualified name that is
1218/// being declared.
1219///
1220/// \param ParamLists the template parameter lists, from the outermost to the
1221/// innermost template parameter lists.
1222///
1223/// \param NumParamLists the number of template parameter lists in ParamLists.
1224///
John McCalle820e5e2010-04-13 20:37:33 +00001225/// \param IsFriend Whether to apply the slightly different rules for
1226/// matching template parameters to scope specifiers in friend
1227/// declarations.
1228///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001229/// \param IsExplicitSpecialization will be set true if the entity being
1230/// declared is an explicit specialization, false otherwise.
1231///
Mike Stump11289f42009-09-09 15:08:12 +00001232/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001233/// name that is preceded by the scope specifier @p SS. This template
1234/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001235/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001236/// template specialization), or may be NULL (if we were's declaring isn't
1237/// itself a template).
1238TemplateParameterList *
1239Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1240 const CXXScopeSpec &SS,
1241 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001242 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001243 bool IsFriend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001244 bool &IsExplicitSpecialization,
1245 bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001246 IsExplicitSpecialization = false;
1247
Douglas Gregord8d297c2009-07-21 23:53:31 +00001248 // Find the template-ids that occur within the nested-name-specifier. These
1249 // template-ids will match up with the template parameter lists.
1250 llvm::SmallVector<const TemplateSpecializationType *, 4>
1251 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001252 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1253 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001254 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1255 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001256 const Type *T = NNS->getAsType();
1257 if (!T) break;
1258
1259 // C++0x [temp.expl.spec]p17:
1260 // A member or a member template may be nested within many
1261 // enclosing class templates. In an explicit specialization for
1262 // such a member, the member declaration shall be preceded by a
1263 // template<> for each enclosing class template that is
1264 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001265 //
1266 // Following the existing practice of GNU and EDG, we allow a typedef of a
1267 // template specialization type.
1268 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1269 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001270
Mike Stump11289f42009-09-09 15:08:12 +00001271 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001272 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001273 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1274 if (!Template)
1275 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001276
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001277 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001278 ClassTemplateSpecializationDecl *SpecDecl
1279 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1280 // If the nested name specifier refers to an explicit specialization,
1281 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001282 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1283 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001284 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001285 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001286 }
Mike Stump11289f42009-09-09 15:08:12 +00001287
Douglas Gregord8d297c2009-07-21 23:53:31 +00001288 TemplateIdsInSpecifier.push_back(SpecType);
1289 }
1290 }
Mike Stump11289f42009-09-09 15:08:12 +00001291
Douglas Gregord8d297c2009-07-21 23:53:31 +00001292 // Reverse the list of template-ids in the scope specifier, so that we can
1293 // more easily match up the template-ids and the template parameter lists.
1294 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001295
Douglas Gregord8d297c2009-07-21 23:53:31 +00001296 SourceLocation FirstTemplateLoc = DeclStartLoc;
1297 if (NumParamLists)
1298 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001299
Douglas Gregord8d297c2009-07-21 23:53:31 +00001300 // Match the template-ids found in the specifier to the template parameter
1301 // lists.
1302 unsigned Idx = 0;
1303 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1304 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001305 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1306 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001307 if (Idx >= NumParamLists) {
1308 // We have a template-id without a corresponding template parameter
1309 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001310
1311 // ...which is fine if this is a friend declaration.
1312 if (IsFriend) {
1313 IsExplicitSpecialization = true;
1314 break;
1315 }
1316
Douglas Gregord8d297c2009-07-21 23:53:31 +00001317 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001318 // FIXME: the location information here isn't great.
1319 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001320 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001321 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001322 << SS.getRange();
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001323 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001324 } else {
1325 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1326 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001327 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001328 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001329 }
1330 return 0;
1331 }
Mike Stump11289f42009-09-09 15:08:12 +00001332
Douglas Gregord8d297c2009-07-21 23:53:31 +00001333 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001334 if (DependentTemplateId) {
John McCall2408e322010-04-27 00:57:59 +00001335 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00001336
John McCall2408e322010-04-27 00:57:59 +00001337 // Are there cases in (e.g.) friends where this won't match?
1338 if (const InjectedClassNameType *Injected
1339 = TemplateId->getAs<InjectedClassNameType>()) {
1340 CXXRecordDecl *Record = Injected->getDecl();
1341 if (ClassTemplatePartialSpecializationDecl *Partial =
1342 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1343 ExpectedTemplateParams = Partial->getTemplateParameters();
1344 else
1345 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1346 ->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001347 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001348
John McCall2408e322010-04-27 00:57:59 +00001349 if (ExpectedTemplateParams)
1350 TemplateParameterListsAreEqual(ParamLists[Idx],
1351 ExpectedTemplateParams,
1352 true, TPL_TemplateMatch);
1353
Douglas Gregored5731f2009-11-25 17:50:39 +00001354 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001355 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001356 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001357 diag::err_template_param_list_matches_nontemplate)
1358 << TemplateId
1359 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001360 else
1361 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001362 }
Mike Stump11289f42009-09-09 15:08:12 +00001363
Douglas Gregord8d297c2009-07-21 23:53:31 +00001364 // If there were at least as many template-ids as there were template
1365 // parameter lists, then there are no template parameter lists remaining for
1366 // the declaration itself.
Douglas Gregor5be1eb82010-08-20 03:26:10 +00001367 if (Idx >= NumParamLists)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001368 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001369
Douglas Gregord8d297c2009-07-21 23:53:31 +00001370 // If there were too many template parameter lists, complain about that now.
1371 if (Idx != NumParamLists - 1) {
1372 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001373 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001374 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001375 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1376 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001377 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1378 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001379
1380 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1381 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1382 diag::note_explicit_template_spec_does_not_need_header)
1383 << ExplicitSpecializationsInSpecifier.back();
1384 ExplicitSpecializationsInSpecifier.pop_back();
1385 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001386
1387 // We have a template parameter list with no corresponding scope, which
1388 // means that the resulting template declaration can't be instantiated
1389 // properly (we'll end up with dependent nodes when we shouldn't).
1390 if (!isExplicitSpecHeader)
1391 Invalid = true;
1392
Douglas Gregord8d297c2009-07-21 23:53:31 +00001393 ++Idx;
1394 }
1395 }
Mike Stump11289f42009-09-09 15:08:12 +00001396
Douglas Gregord8d297c2009-07-21 23:53:31 +00001397 // Return the last template parameter list, which corresponds to the
1398 // entity being declared.
1399 return ParamLists[NumParamLists - 1];
1400}
1401
Douglas Gregordc572a32009-03-30 22:58:21 +00001402QualType Sema::CheckTemplateIdType(TemplateName Name,
1403 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001404 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001405 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001406 if (!Template) {
1407 // The template name does not resolve to a template, so we just
1408 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001409 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001410 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001411
Douglas Gregorc40290e2009-03-09 23:48:35 +00001412 // Check that the template argument list is well-formed for this
1413 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001414 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001415 TemplateArgs.size());
1416 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001417 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001418 return QualType();
1419
Mike Stump11289f42009-09-09 15:08:12 +00001420 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001421 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001422 "Converted template argument list is too short!");
1423
1424 QualType CanonType;
1425
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001426 if (Name.isDependent() ||
1427 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001428 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001429 // This class template specialization is a dependent
1430 // type. Therefore, its canonical type is another class template
1431 // specialization type that contains all of the converted
1432 // arguments in canonical form. This ensures that, e.g., A<T> and
1433 // A<T, T> have identical types when A is declared as:
1434 //
1435 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001436 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001437 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001438 Converted.getFlatArguments(),
1439 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001440
Douglas Gregora8e02e72009-07-28 23:00:59 +00001441 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001442 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001443 // In the future, we need to teach getTemplateSpecializationType to only
1444 // build the canonical type and return that to us.
1445 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001446
1447 // This might work out to be a current instantiation, in which
1448 // case the canonical type needs to be the InjectedClassNameType.
1449 //
1450 // TODO: in theory this could be a simple hashtable lookup; most
1451 // changes to CurContext don't change the set of current
1452 // instantiations.
1453 if (isa<ClassTemplateDecl>(Template)) {
1454 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1455 // If we get out to a namespace, we're done.
1456 if (Ctx->isFileContext()) break;
1457
1458 // If this isn't a record, keep looking.
1459 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1460 if (!Record) continue;
1461
1462 // Look for one of the two cases with InjectedClassNameTypes
1463 // and check whether it's the same template.
1464 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1465 !Record->getDescribedClassTemplate())
1466 continue;
1467
1468 // Fetch the injected class name type and check whether its
1469 // injected type is equal to the type we just built.
1470 QualType ICNT = Context.getTypeDeclType(Record);
1471 QualType Injected = cast<InjectedClassNameType>(ICNT)
1472 ->getInjectedSpecializationType();
1473
1474 if (CanonType != Injected->getCanonicalTypeInternal())
1475 continue;
1476
1477 // If so, the canonical type of this TST is the injected
1478 // class name type of the record we just found.
1479 assert(ICNT.isCanonical());
1480 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00001481 break;
1482 }
1483 }
Mike Stump11289f42009-09-09 15:08:12 +00001484 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001485 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001486 // Find the class template specialization declaration that
1487 // corresponds to these arguments.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001488 void *InsertPos = 0;
1489 ClassTemplateSpecializationDecl *Decl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001490 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
1491 Converted.flatSize(), InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001492 if (!Decl) {
1493 // This is the first time we have referenced this class template
1494 // specialization. Create the canonical declaration and add it to
1495 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001496 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001497 ClassTemplate->getTemplatedDecl()->getTagKind(),
1498 ClassTemplate->getDeclContext(),
1499 ClassTemplate->getLocation(),
1500 ClassTemplate,
1501 Converted, 0);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001502 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001503 Decl->setLexicalDeclContext(CurContext);
1504 }
1505
1506 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001507 assert(isa<RecordType>(CanonType) &&
1508 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001509 }
Mike Stump11289f42009-09-09 15:08:12 +00001510
Douglas Gregorc40290e2009-03-09 23:48:35 +00001511 // Build the fully-sugared type for this class template
1512 // specialization, which refers back to the class template
1513 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00001514 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001515}
1516
Douglas Gregor67a65642009-02-17 23:15:12 +00001517Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001518Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001519 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001520 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001521 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001522 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001523
Douglas Gregorc40290e2009-03-09 23:48:35 +00001524 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001525 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001526 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001527
John McCall6b51f282009-11-23 01:53:49 +00001528 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001529 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001530
1531 if (Result.isNull())
1532 return true;
1533
John McCallbcd03502009-12-07 02:54:59 +00001534 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001535 TemplateSpecializationTypeLoc TL
1536 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1537 TL.setTemplateNameLoc(TemplateLoc);
1538 TL.setLAngleLoc(LAngleLoc);
1539 TL.setRAngleLoc(RAngleLoc);
1540 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1541 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1542
John McCallba7bf592010-08-24 05:47:05 +00001543 return CreateParsedType(Result, DI);
John McCalld8fe9af2009-09-08 17:47:29 +00001544}
John McCall06f6fe8d2009-09-04 01:14:41 +00001545
John McCalld8fe9af2009-09-08 17:47:29 +00001546Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1547 TagUseKind TUK,
1548 DeclSpec::TST TagSpec,
1549 SourceLocation TagLoc) {
1550 if (TypeResult.isInvalid())
1551 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001552
John McCall0ad16662009-10-29 08:12:44 +00001553 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001554 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001555 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001556
John McCalld8fe9af2009-09-08 17:47:29 +00001557 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001558 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001559
John McCalld8fe9af2009-09-08 17:47:29 +00001560 if (const RecordType *RT = Type->getAs<RecordType>()) {
1561 RecordDecl *D = RT->getDecl();
1562
1563 IdentifierInfo *Id = D->getIdentifier();
1564 assert(Id && "templated class must have an identifier");
1565
1566 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1567 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001568 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001569 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001570 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001571 }
1572 }
1573
Abramo Bagnara6150c882010-05-11 21:36:43 +00001574 ElaboratedTypeKeyword Keyword
1575 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1576 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001577
John McCallba7bf592010-08-24 05:47:05 +00001578 return ParsedType::make(ElabType);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001579}
1580
John McCalldadc5752010-08-24 06:29:42 +00001581ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001582 LookupResult &R,
1583 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001584 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001585 // FIXME: Can we do any checking at this point? I guess we could check the
1586 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001587 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001588 // though.
John McCalle66edc12009-11-24 19:00:30 +00001589
1590 // These should be filtered out by our callers.
1591 assert(!R.empty() && "empty lookup results when building templateid");
1592 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1593
1594 NestedNameSpecifier *Qualifier = 0;
1595 SourceRange QualifierRange;
1596 if (SS.isSet()) {
1597 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1598 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001599 }
John McCall58cc69d2010-01-27 01:50:18 +00001600
1601 // We don't want lookup warnings at this point.
1602 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001603
John McCalle66edc12009-11-24 19:00:30 +00001604 bool Dependent
1605 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1606 &TemplateArgs);
1607 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001608 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001609 Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001610 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001611 RequiresADL, TemplateArgs,
1612 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001613
1614 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001615}
1616
John McCalle66edc12009-11-24 19:00:30 +00001617// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00001618ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001619Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001620 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +00001621 const TemplateArgumentListInfo &TemplateArgs) {
1622 DeclContext *DC;
1623 if (!(DC = computeDeclContext(SS, false)) ||
1624 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001625 RequireCompleteDeclContext(SS, DC))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001626 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001627
Douglas Gregor786123d2010-05-21 23:18:07 +00001628 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001629 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00001630 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1631 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00001632
John McCalle66edc12009-11-24 19:00:30 +00001633 if (R.isAmbiguous())
1634 return ExprError();
1635
1636 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001637 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1638 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001639 return ExprError();
1640 }
1641
1642 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001643 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1644 << (NestedNameSpecifier*) SS.getScopeRep()
1645 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001646 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1647 return ExprError();
1648 }
1649
1650 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001651}
1652
Douglas Gregorb67535d2009-03-31 00:43:58 +00001653/// \brief Form a dependent template name.
1654///
1655/// This action forms a dependent template name given the template
1656/// name and its (presumably dependent) scope specifier. For
1657/// example, given "MetaFun::template apply", the scope specifier \p
1658/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1659/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregorbb119652010-06-16 23:00:59 +00001660TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1661 SourceLocation TemplateKWLoc,
1662 CXXScopeSpec &SS,
1663 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00001664 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00001665 bool EnteringContext,
1666 TemplateTy &Result) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00001667 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1668 !getLangOptions().CPlusPlus0x)
1669 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1670 << FixItHint::CreateRemoval(TemplateKWLoc);
1671
Douglas Gregor9abe2372010-01-19 16:01:07 +00001672 DeclContext *LookupCtx = 0;
1673 if (SS.isSet())
1674 LookupCtx = computeDeclContext(SS, EnteringContext);
1675 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00001676 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00001677 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001678 // C++0x [temp.names]p5:
1679 // If a name prefixed by the keyword template is not the name of
1680 // a template, the program is ill-formed. [Note: the keyword
1681 // template may not be applied to non-template members of class
1682 // templates. -end note ] [ Note: as is the case with the
1683 // typename prefix, the template prefix is allowed in cases
1684 // where it is not strictly necessary; i.e., when the
1685 // nested-name-specifier or the expression on the left of the ->
1686 // or . is not dependent on a template-parameter, or the use
1687 // does not appear in the scope of a template. -end note]
1688 //
1689 // Note: C++03 was more strict here, because it banned the use of
1690 // the "template" keyword prior to a template-name that was not a
1691 // dependent name. C++ DR468 relaxed this requirement (the
1692 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00001693 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00001694 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001695 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1696 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00001697 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001698 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1699 isa<CXXRecordDecl>(LookupCtx) &&
1700 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregorbb119652010-06-16 23:00:59 +00001701 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00001702 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001703 Diag(Name.getSourceRange().getBegin(),
1704 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001705 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001706 << Name.getSourceRange()
1707 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001708 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00001709 } else {
1710 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00001711 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001712 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001713 }
1714
Mike Stump11289f42009-09-09 15:08:12 +00001715 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001716 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001717
1718 switch (Name.getKind()) {
1719 case UnqualifiedId::IK_Identifier:
Douglas Gregorbb119652010-06-16 23:00:59 +00001720 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1721 Name.Identifier));
1722 return TNK_Dependent_template_name;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001723
Douglas Gregor71395fa2009-11-04 00:56:37 +00001724 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00001725 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00001726 Name.OperatorFunctionId.Operator));
Douglas Gregorbb119652010-06-16 23:00:59 +00001727 return TNK_Dependent_template_name;
Alexis Hunted0530f2009-11-28 08:58:14 +00001728
1729 case UnqualifiedId::IK_LiteralOperatorId:
1730 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1731
Douglas Gregor3cf81312009-11-03 23:16:33 +00001732 default:
1733 break;
1734 }
1735
1736 Diag(Name.getSourceRange().getBegin(),
1737 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001738 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001739 << Name.getSourceRange()
1740 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001741 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001742}
1743
Mike Stump11289f42009-09-09 15:08:12 +00001744bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001745 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001746 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001747 const TemplateArgument &Arg = AL.getArgument();
1748
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001749 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001750 switch(Arg.getKind()) {
1751 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001752 // C++ [temp.arg.type]p1:
1753 // A template-argument for a template-parameter which is a
1754 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001755 break;
1756 case TemplateArgument::Template: {
1757 // We have a template type parameter but the template argument
1758 // is a template without any arguments.
1759 SourceRange SR = AL.getSourceRange();
1760 TemplateName Name = Arg.getAsTemplate();
1761 Diag(SR.getBegin(), diag::err_template_missing_args)
1762 << Name << SR;
1763 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1764 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001765
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001766 return true;
1767 }
1768 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001769 // We have a template type parameter but the template argument
1770 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001771 SourceRange SR = AL.getSourceRange();
1772 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001773 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001774
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001775 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001776 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001777 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001778
John McCallbcd03502009-12-07 02:54:59 +00001779 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001780 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001781
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001782 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001783 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001784 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001785 return false;
1786}
1787
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001788/// \brief Substitute template arguments into the default template argument for
1789/// the given template type parameter.
1790///
1791/// \param SemaRef the semantic analysis object for which we are performing
1792/// the substitution.
1793///
1794/// \param Template the template that we are synthesizing template arguments
1795/// for.
1796///
1797/// \param TemplateLoc the location of the template name that started the
1798/// template-id we are checking.
1799///
1800/// \param RAngleLoc the location of the right angle bracket ('>') that
1801/// terminates the template-id.
1802///
1803/// \param Param the template template parameter whose default we are
1804/// substituting into.
1805///
1806/// \param Converted the list of template arguments provided for template
1807/// parameters that precede \p Param in the template parameter list.
1808///
1809/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001810static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001811SubstDefaultTemplateArgument(Sema &SemaRef,
1812 TemplateDecl *Template,
1813 SourceLocation TemplateLoc,
1814 SourceLocation RAngleLoc,
1815 TemplateTypeParmDecl *Param,
1816 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001817 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001818
1819 // If the argument type is dependent, instantiate it now based
1820 // on the previously-computed template arguments.
1821 if (ArgType->getType()->isDependentType()) {
1822 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1823 /*TakeArgs=*/false);
1824
1825 MultiLevelTemplateArgumentList AllTemplateArgs
1826 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1827
1828 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1829 Template, Converted.getFlatArguments(),
1830 Converted.flatSize(),
1831 SourceRange(TemplateLoc, RAngleLoc));
1832
1833 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1834 Param->getDefaultArgumentLoc(),
1835 Param->getDeclName());
1836 }
1837
1838 return ArgType;
1839}
1840
1841/// \brief Substitute template arguments into the default template argument for
1842/// the given non-type template parameter.
1843///
1844/// \param SemaRef the semantic analysis object for which we are performing
1845/// the substitution.
1846///
1847/// \param Template the template that we are synthesizing template arguments
1848/// for.
1849///
1850/// \param TemplateLoc the location of the template name that started the
1851/// template-id we are checking.
1852///
1853/// \param RAngleLoc the location of the right angle bracket ('>') that
1854/// terminates the template-id.
1855///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001856/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001857/// substituting into.
1858///
1859/// \param Converted the list of template arguments provided for template
1860/// parameters that precede \p Param in the template parameter list.
1861///
1862/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00001863static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001864SubstDefaultTemplateArgument(Sema &SemaRef,
1865 TemplateDecl *Template,
1866 SourceLocation TemplateLoc,
1867 SourceLocation RAngleLoc,
1868 NonTypeTemplateParmDecl *Param,
1869 TemplateArgumentListBuilder &Converted) {
1870 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1871 /*TakeArgs=*/false);
1872
1873 MultiLevelTemplateArgumentList AllTemplateArgs
1874 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1875
1876 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1877 Template, Converted.getFlatArguments(),
1878 Converted.flatSize(),
1879 SourceRange(TemplateLoc, RAngleLoc));
1880
1881 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1882}
1883
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001884/// \brief Substitute template arguments into the default template argument for
1885/// the given template template parameter.
1886///
1887/// \param SemaRef the semantic analysis object for which we are performing
1888/// the substitution.
1889///
1890/// \param Template the template that we are synthesizing template arguments
1891/// for.
1892///
1893/// \param TemplateLoc the location of the template name that started the
1894/// template-id we are checking.
1895///
1896/// \param RAngleLoc the location of the right angle bracket ('>') that
1897/// terminates the template-id.
1898///
1899/// \param Param the template template parameter whose default we are
1900/// substituting into.
1901///
1902/// \param Converted the list of template arguments provided for template
1903/// parameters that precede \p Param in the template parameter list.
1904///
1905/// \returns the substituted template argument, or NULL if an error occurred.
1906static TemplateName
1907SubstDefaultTemplateArgument(Sema &SemaRef,
1908 TemplateDecl *Template,
1909 SourceLocation TemplateLoc,
1910 SourceLocation RAngleLoc,
1911 TemplateTemplateParmDecl *Param,
1912 TemplateArgumentListBuilder &Converted) {
1913 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1914 /*TakeArgs=*/false);
1915
1916 MultiLevelTemplateArgumentList AllTemplateArgs
1917 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1918
1919 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1920 Template, Converted.getFlatArguments(),
1921 Converted.flatSize(),
1922 SourceRange(TemplateLoc, RAngleLoc));
1923
1924 return SemaRef.SubstTemplateName(
1925 Param->getDefaultArgument().getArgument().getAsTemplate(),
1926 Param->getDefaultArgument().getTemplateNameLoc(),
1927 AllTemplateArgs);
1928}
1929
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001930/// \brief If the given template parameter has a default template
1931/// argument, substitute into that default template argument and
1932/// return the corresponding template argument.
1933TemplateArgumentLoc
1934Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1935 SourceLocation TemplateLoc,
1936 SourceLocation RAngleLoc,
1937 Decl *Param,
1938 TemplateArgumentListBuilder &Converted) {
1939 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1940 if (!TypeParm->hasDefaultArgument())
1941 return TemplateArgumentLoc();
1942
John McCallbcd03502009-12-07 02:54:59 +00001943 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001944 TemplateLoc,
1945 RAngleLoc,
1946 TypeParm,
1947 Converted);
1948 if (DI)
1949 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1950
1951 return TemplateArgumentLoc();
1952 }
1953
1954 if (NonTypeTemplateParmDecl *NonTypeParm
1955 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1956 if (!NonTypeParm->hasDefaultArgument())
1957 return TemplateArgumentLoc();
1958
John McCalldadc5752010-08-24 06:29:42 +00001959 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001960 TemplateLoc,
1961 RAngleLoc,
1962 NonTypeParm,
1963 Converted);
1964 if (Arg.isInvalid())
1965 return TemplateArgumentLoc();
1966
1967 Expr *ArgE = Arg.takeAs<Expr>();
1968 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1969 }
1970
1971 TemplateTemplateParmDecl *TempTempParm
1972 = cast<TemplateTemplateParmDecl>(Param);
1973 if (!TempTempParm->hasDefaultArgument())
1974 return TemplateArgumentLoc();
1975
1976 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1977 TemplateLoc,
1978 RAngleLoc,
1979 TempTempParm,
1980 Converted);
1981 if (TName.isNull())
1982 return TemplateArgumentLoc();
1983
1984 return TemplateArgumentLoc(TemplateArgument(TName),
1985 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1986 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1987}
1988
Douglas Gregorda0fb532009-11-11 19:31:23 +00001989/// \brief Check that the given template argument corresponds to the given
1990/// template parameter.
1991bool Sema::CheckTemplateArgument(NamedDecl *Param,
1992 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001993 TemplateDecl *Template,
1994 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001995 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001996 TemplateArgumentListBuilder &Converted,
1997 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001998 // Check template type parameters.
1999 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002000 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002001
Douglas Gregoreebed722009-11-11 19:41:09 +00002002 // Check non-type template parameters.
2003 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00002004 // Do substitution on the type of the non-type template parameter
2005 // with the template arguments we've seen thus far.
2006 QualType NTTPType = NTTP->getType();
2007 if (NTTPType->isDependentType()) {
2008 // Do substitution on the type of the non-type template parameter.
2009 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2010 NTTP, Converted.getFlatArguments(),
2011 Converted.flatSize(),
2012 SourceRange(TemplateLoc, RAngleLoc));
2013
2014 TemplateArgumentList TemplateArgs(Context, Converted,
2015 /*TakeArgs=*/false);
2016 NTTPType = SubstType(NTTPType,
2017 MultiLevelTemplateArgumentList(TemplateArgs),
2018 NTTP->getLocation(),
2019 NTTP->getDeclName());
2020 // If that worked, check the non-type template parameter type
2021 // for validity.
2022 if (!NTTPType.isNull())
2023 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2024 NTTP->getLocation());
2025 if (NTTPType.isNull())
2026 return true;
2027 }
2028
2029 switch (Arg.getArgument().getKind()) {
2030 case TemplateArgument::Null:
2031 assert(false && "Should never see a NULL template argument here");
2032 return true;
2033
2034 case TemplateArgument::Expression: {
2035 Expr *E = Arg.getArgument().getAsExpr();
2036 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002037 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002038 return true;
2039
2040 Converted.Append(Result);
2041 break;
2042 }
2043
2044 case TemplateArgument::Declaration:
2045 case TemplateArgument::Integral:
2046 // We've already checked this template argument, so just copy
2047 // it to the list of converted arguments.
2048 Converted.Append(Arg.getArgument());
2049 break;
2050
2051 case TemplateArgument::Template:
2052 // We were given a template template argument. It may not be ill-formed;
2053 // see below.
2054 if (DependentTemplateName *DTN
2055 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2056 // We have a template argument such as \c T::template X, which we
2057 // parsed as a template template argument. However, since we now
2058 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002059 // template name into an expression.
2060
2061 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2062 Arg.getTemplateNameLoc());
2063
John McCalle66edc12009-11-24 19:00:30 +00002064 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2065 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002066 Arg.getTemplateQualifierRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002067 NameInfo);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002068
2069 TemplateArgument Result;
2070 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2071 return true;
2072
2073 Converted.Append(Result);
2074 break;
2075 }
2076
2077 // We have a template argument that actually does refer to a class
2078 // template, template alias, or template template parameter, and
2079 // therefore cannot be a non-type template argument.
2080 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2081 << Arg.getSourceRange();
2082
2083 Diag(Param->getLocation(), diag::note_template_param_here);
2084 return true;
2085
2086 case TemplateArgument::Type: {
2087 // We have a non-type template parameter but the template
2088 // argument is a type.
2089
2090 // C++ [temp.arg]p2:
2091 // In a template-argument, an ambiguity between a type-id and
2092 // an expression is resolved to a type-id, regardless of the
2093 // form of the corresponding template-parameter.
2094 //
2095 // We warn specifically about this case, since it can be rather
2096 // confusing for users.
2097 QualType T = Arg.getArgument().getAsType();
2098 SourceRange SR = Arg.getSourceRange();
2099 if (T->isFunctionType())
2100 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2101 else
2102 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2103 Diag(Param->getLocation(), diag::note_template_param_here);
2104 return true;
2105 }
2106
2107 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002108 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002109 break;
2110 }
2111
2112 return false;
2113 }
2114
2115
2116 // Check template template parameters.
2117 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2118
2119 // Substitute into the template parameter list of the template
2120 // template parameter, since previously-supplied template arguments
2121 // may appear within the template template parameter.
2122 {
2123 // Set up a template instantiation context.
2124 LocalInstantiationScope Scope(*this);
2125 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2126 TempParm, Converted.getFlatArguments(),
2127 Converted.flatSize(),
2128 SourceRange(TemplateLoc, RAngleLoc));
2129
2130 TemplateArgumentList TemplateArgs(Context, Converted,
2131 /*TakeArgs=*/false);
2132 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2133 SubstDecl(TempParm, CurContext,
2134 MultiLevelTemplateArgumentList(TemplateArgs)));
2135 if (!TempParm)
2136 return true;
2137
2138 // FIXME: TempParam is leaked.
2139 }
2140
2141 switch (Arg.getArgument().getKind()) {
2142 case TemplateArgument::Null:
2143 assert(false && "Should never see a NULL template argument here");
2144 return true;
2145
2146 case TemplateArgument::Template:
2147 if (CheckTemplateArgument(TempParm, Arg))
2148 return true;
2149
2150 Converted.Append(Arg.getArgument());
2151 break;
2152
2153 case TemplateArgument::Expression:
2154 case TemplateArgument::Type:
2155 // We have a template template parameter but the template
2156 // argument does not refer to a template.
2157 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2158 return true;
2159
2160 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002161 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002162 "Declaration argument with template template parameter");
2163 break;
2164 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002165 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002166 "Integral argument with template template parameter");
2167 break;
2168
2169 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002170 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002171 break;
2172 }
2173
2174 return false;
2175}
2176
Douglas Gregord32e0282009-02-09 23:23:08 +00002177/// \brief Check that the given template argument list is well-formed
2178/// for specializing the given template.
2179bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2180 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002181 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002182 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002183 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002184 TemplateParameterList *Params = Template->getTemplateParameters();
2185 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002186 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002187 bool Invalid = false;
2188
John McCall6b51f282009-11-23 01:53:49 +00002189 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2190
Mike Stump11289f42009-09-09 15:08:12 +00002191 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002192 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002193
Anders Carlsson15201f12009-06-13 02:08:00 +00002194 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002195 (NumArgs < Params->getMinRequiredArguments() &&
2196 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002197 // FIXME: point at either the first arg beyond what we can handle,
2198 // or the '>', depending on whether we have too many or too few
2199 // arguments.
2200 SourceRange Range;
2201 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002202 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002203 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2204 << (NumArgs > NumParams)
2205 << (isa<ClassTemplateDecl>(Template)? 0 :
2206 isa<FunctionTemplateDecl>(Template)? 1 :
2207 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2208 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002209 Diag(Template->getLocation(), diag::note_template_decl_here)
2210 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002211 Invalid = true;
2212 }
Mike Stump11289f42009-09-09 15:08:12 +00002213
2214 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002215 // [...] The type and form of each template-argument specified in
2216 // a template-id shall match the type and form specified for the
2217 // corresponding parameter declared by the template in its
2218 // template-parameter-list.
2219 unsigned ArgIdx = 0;
2220 for (TemplateParameterList::iterator Param = Params->begin(),
2221 ParamEnd = Params->end();
2222 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002223 if (ArgIdx > NumArgs && PartialTemplateArgs)
2224 break;
Mike Stump11289f42009-09-09 15:08:12 +00002225
Douglas Gregoreebed722009-11-11 19:41:09 +00002226 // If we have a template parameter pack, check every remaining template
2227 // argument against that template parameter pack.
2228 if ((*Param)->isTemplateParameterPack()) {
2229 Converted.BeginPack();
2230 for (; ArgIdx < NumArgs; ++ArgIdx) {
2231 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2232 TemplateLoc, RAngleLoc, Converted)) {
2233 Invalid = true;
2234 break;
2235 }
2236 }
2237 Converted.EndPack();
2238 continue;
2239 }
2240
Douglas Gregor84d49a22009-11-11 21:54:23 +00002241 if (ArgIdx < NumArgs) {
2242 // Check the template argument we were given.
2243 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2244 TemplateLoc, RAngleLoc, Converted))
2245 return true;
2246
2247 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002248 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002249
Douglas Gregor84d49a22009-11-11 21:54:23 +00002250 // We have a default template argument that we will use.
2251 TemplateArgumentLoc Arg;
2252
2253 // Retrieve the default template argument from the template
2254 // parameter. For each kind of template parameter, we substitute the
2255 // template arguments provided thus far and any "outer" template arguments
2256 // (when the template parameter was part of a nested template) into
2257 // the default argument.
2258 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2259 if (!TTP->hasDefaultArgument()) {
2260 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2261 break;
2262 }
2263
John McCallbcd03502009-12-07 02:54:59 +00002264 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002265 Template,
2266 TemplateLoc,
2267 RAngleLoc,
2268 TTP,
2269 Converted);
2270 if (!ArgType)
2271 return true;
2272
2273 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2274 ArgType);
2275 } else if (NonTypeTemplateParmDecl *NTTP
2276 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2277 if (!NTTP->hasDefaultArgument()) {
2278 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2279 break;
2280 }
2281
John McCalldadc5752010-08-24 06:29:42 +00002282 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002283 TemplateLoc,
2284 RAngleLoc,
2285 NTTP,
2286 Converted);
2287 if (E.isInvalid())
2288 return true;
2289
2290 Expr *Ex = E.takeAs<Expr>();
2291 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2292 } else {
2293 TemplateTemplateParmDecl *TempParm
2294 = cast<TemplateTemplateParmDecl>(*Param);
2295
2296 if (!TempParm->hasDefaultArgument()) {
2297 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2298 break;
2299 }
2300
2301 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2302 TemplateLoc,
2303 RAngleLoc,
2304 TempParm,
2305 Converted);
2306 if (Name.isNull())
2307 return true;
2308
2309 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2310 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2311 TempParm->getDefaultArgument().getTemplateNameLoc());
2312 }
2313
2314 // Introduce an instantiation record that describes where we are using
2315 // the default template argument.
2316 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2317 Converted.getFlatArguments(),
2318 Converted.flatSize(),
2319 SourceRange(TemplateLoc, RAngleLoc));
2320
2321 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002322 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002323 RAngleLoc, Converted))
2324 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002325 }
2326
2327 return Invalid;
2328}
2329
2330/// \brief Check a template argument against its corresponding
2331/// template type parameter.
2332///
2333/// This routine implements the semantics of C++ [temp.arg.type]. It
2334/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002335bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002336 TypeSourceInfo *ArgInfo) {
2337 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002338 QualType Arg = ArgInfo->getType();
2339
Douglas Gregord32e0282009-02-09 23:23:08 +00002340 // C++ [temp.arg.type]p2:
2341 // A local type, a type with no linkage, an unnamed type or a type
2342 // compounded from any of these types shall not be used as a
2343 // template-argument for a template type-parameter.
2344 //
Douglas Gregor959d5a02010-05-22 16:17:30 +00002345 // FIXME: Perform the unnamed type check.
2346 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002347 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002348 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002349 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002350 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002351 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002352 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002353 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall0ad16662009-10-29 08:12:44 +00002354 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2355 << QualType(Tag, 0) << SR;
2356 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002357 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002358 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002359 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2360 return true;
Douglas Gregor959d5a02010-05-22 16:17:30 +00002361 } else if (Arg->isVariablyModifiedType()) {
2362 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2363 << Arg;
2364 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002365 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002366 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002367 }
2368
2369 return false;
2370}
2371
Douglas Gregorccb07762009-02-11 19:52:55 +00002372/// \brief Checks whether the given template argument is the address
2373/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002374static bool
2375CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2376 NonTypeTemplateParmDecl *Param,
2377 QualType ParamType,
2378 Expr *ArgIn,
2379 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002380 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002381 Expr *Arg = ArgIn;
2382 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002383
2384 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002385 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002386 Arg = Cast->getSubExpr();
2387
2388 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002389 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002390 // A template-argument for a non-type, non-template
2391 // template-parameter shall be one of: [...]
2392 //
2393 // -- the address of an object or function with external
2394 // linkage, including function templates and function
2395 // template-ids but excluding non-static class members,
2396 // expressed as & id-expression where the & is optional if
2397 // the name refers to a function or array, or if the
2398 // corresponding template-parameter is a reference; or
2399 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002400
Douglas Gregorccb07762009-02-11 19:52:55 +00002401 // Ignore (and complain about) any excess parentheses.
2402 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2403 if (!Invalid) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002404 S.Diag(Arg->getSourceRange().getBegin(),
2405 diag::err_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002406 << Arg->getSourceRange();
2407 Invalid = true;
2408 }
2409
2410 Arg = Parens->getSubExpr();
2411 }
2412
Douglas Gregorb242683d2010-04-01 18:32:35 +00002413 bool AddressTaken = false;
2414 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002415 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002416 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002417 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002418 AddressTaken = true;
2419 AddrOpLoc = UnOp->getOperatorLoc();
2420 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002421 } else
2422 DRE = dyn_cast<DeclRefExpr>(Arg);
2423
Douglas Gregorb242683d2010-04-01 18:32:35 +00002424 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002425 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2426 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002427 S.Diag(Param->getLocation(), diag::note_template_param_here);
2428 return true;
2429 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002430
2431 // Stop checking the precise nature of the argument if it is value dependent,
2432 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002433 if (Arg->isValueDependent()) {
2434 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002435 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002436 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002437
Douglas Gregorb242683d2010-04-01 18:32:35 +00002438 if (!isa<ValueDecl>(DRE->getDecl())) {
2439 S.Diag(Arg->getSourceRange().getBegin(),
2440 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002441 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002442 S.Diag(Param->getLocation(), diag::note_template_param_here);
2443 return true;
2444 }
2445
2446 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002447
2448 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002449 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2450 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002451 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002452 S.Diag(Param->getLocation(), diag::note_template_param_here);
2453 return true;
2454 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002455
2456 // Cannot refer to non-static member functions
2457 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002458 if (!Method->isStatic()) {
2459 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002460 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002461 S.Diag(Param->getLocation(), diag::note_template_param_here);
2462 return true;
2463 }
Mike Stump11289f42009-09-09 15:08:12 +00002464
Douglas Gregorccb07762009-02-11 19:52:55 +00002465 // Functions must have external linkage.
2466 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002467 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002468 S.Diag(Arg->getSourceRange().getBegin(),
2469 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002470 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002471 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002472 << true;
2473 return true;
2474 }
2475
2476 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002477 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002478
Douglas Gregorb242683d2010-04-01 18:32:35 +00002479 // If the template parameter has pointer type, the function decays.
2480 if (ParamType->isPointerType() && !AddressTaken)
2481 ArgType = S.Context.getPointerType(Func->getType());
2482 else if (AddressTaken && ParamType->isReferenceType()) {
2483 // If we originally had an address-of operator, but the
2484 // parameter has reference type, complain and (if things look
2485 // like they will work) drop the address-of operator.
2486 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2487 ParamType.getNonReferenceType())) {
2488 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2489 << ParamType;
2490 S.Diag(Param->getLocation(), diag::note_template_param_here);
2491 return true;
2492 }
2493
2494 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2495 << ParamType
2496 << FixItHint::CreateRemoval(AddrOpLoc);
2497 S.Diag(Param->getLocation(), diag::note_template_param_here);
2498
2499 ArgType = Func->getType();
2500 }
2501 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002502 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002503 S.Diag(Arg->getSourceRange().getBegin(),
2504 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002505 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002506 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002507 << true;
2508 return true;
2509 }
2510
Douglas Gregorb242683d2010-04-01 18:32:35 +00002511 // A value of reference type is not an object.
2512 if (Var->getType()->isReferenceType()) {
2513 S.Diag(Arg->getSourceRange().getBegin(),
2514 diag::err_template_arg_reference_var)
2515 << Var->getType() << Arg->getSourceRange();
2516 S.Diag(Param->getLocation(), diag::note_template_param_here);
2517 return true;
2518 }
2519
Douglas Gregorccb07762009-02-11 19:52:55 +00002520 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002521 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002522
2523 // If the template parameter has pointer type, we must have taken
2524 // the address of this object.
2525 if (ParamType->isReferenceType()) {
2526 if (AddressTaken) {
2527 // If we originally had an address-of operator, but the
2528 // parameter has reference type, complain and (if things look
2529 // like they will work) drop the address-of operator.
2530 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2531 ParamType.getNonReferenceType())) {
2532 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2533 << ParamType;
2534 S.Diag(Param->getLocation(), diag::note_template_param_here);
2535 return true;
2536 }
2537
2538 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2539 << ParamType
2540 << FixItHint::CreateRemoval(AddrOpLoc);
2541 S.Diag(Param->getLocation(), diag::note_template_param_here);
2542
2543 ArgType = Var->getType();
2544 }
2545 } else if (!AddressTaken && ParamType->isPointerType()) {
2546 if (Var->getType()->isArrayType()) {
2547 // Array-to-pointer decay.
2548 ArgType = S.Context.getArrayDecayedType(Var->getType());
2549 } else {
2550 // If the template parameter has pointer type but the address of
2551 // this object was not taken, complain and (possibly) recover by
2552 // taking the address of the entity.
2553 ArgType = S.Context.getPointerType(Var->getType());
2554 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2555 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2556 << ParamType;
2557 S.Diag(Param->getLocation(), diag::note_template_param_here);
2558 return true;
2559 }
2560
2561 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2562 << ParamType
2563 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2564
2565 S.Diag(Param->getLocation(), diag::note_template_param_here);
2566 }
2567 }
2568 } else {
2569 // We found something else, but we don't know specifically what it is.
2570 S.Diag(Arg->getSourceRange().getBegin(),
2571 diag::err_template_arg_not_object_or_func)
2572 << Arg->getSourceRange();
2573 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2574 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002575 }
Mike Stump11289f42009-09-09 15:08:12 +00002576
Douglas Gregorb242683d2010-04-01 18:32:35 +00002577 if (ParamType->isPointerType() &&
2578 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2579 S.IsQualificationConversion(ArgType, ParamType)) {
2580 // For pointer-to-object types, qualification conversions are
2581 // permitted.
2582 } else {
2583 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2584 if (!ParamRef->getPointeeType()->isFunctionType()) {
2585 // C++ [temp.arg.nontype]p5b3:
2586 // For a non-type template-parameter of type reference to
2587 // object, no conversions apply. The type referred to by the
2588 // reference may be more cv-qualified than the (otherwise
2589 // identical) type of the template- argument. The
2590 // template-parameter is bound directly to the
2591 // template-argument, which shall be an lvalue.
2592
2593 // FIXME: Other qualifiers?
2594 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2595 unsigned ArgQuals = ArgType.getCVRQualifiers();
2596
2597 if ((ParamQuals | ArgQuals) != ParamQuals) {
2598 S.Diag(Arg->getSourceRange().getBegin(),
2599 diag::err_template_arg_ref_bind_ignores_quals)
2600 << ParamType << Arg->getType()
2601 << Arg->getSourceRange();
2602 S.Diag(Param->getLocation(), diag::note_template_param_here);
2603 return true;
2604 }
2605 }
2606 }
2607
2608 // At this point, the template argument refers to an object or
2609 // function with external linkage. We now need to check whether the
2610 // argument and parameter types are compatible.
2611 if (!S.Context.hasSameUnqualifiedType(ArgType,
2612 ParamType.getNonReferenceType())) {
2613 // We can't perform this conversion or binding.
2614 if (ParamType->isReferenceType())
2615 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2616 << ParamType << Arg->getType() << Arg->getSourceRange();
2617 else
2618 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2619 << Arg->getType() << ParamType << Arg->getSourceRange();
2620 S.Diag(Param->getLocation(), diag::note_template_param_here);
2621 return true;
2622 }
2623 }
2624
2625 // Create the template argument.
2626 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002627 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002628 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002629}
2630
2631/// \brief Checks whether the given template argument is a pointer to
2632/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002633bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2634 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002635 bool Invalid = false;
2636
2637 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002638 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002639 Arg = Cast->getSubExpr();
2640
2641 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002642 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002643 // A template-argument for a non-type, non-template
2644 // template-parameter shall be one of: [...]
2645 //
2646 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002647 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002648
2649 // Ignore (and complain about) any excess parentheses.
2650 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2651 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002652 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002653 diag::err_template_arg_extra_parens)
2654 << Arg->getSourceRange();
2655 Invalid = true;
2656 }
2657
2658 Arg = Parens->getSubExpr();
2659 }
2660
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002661 // A pointer-to-member constant written &Class::member.
2662 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002663 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2664 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2665 if (DRE && !DRE->getQualifier())
2666 DRE = 0;
2667 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002668 }
2669 // A constant of pointer-to-member type.
2670 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2671 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2672 if (VD->getType()->isMemberPointerType()) {
2673 if (isa<NonTypeTemplateParmDecl>(VD) ||
2674 (isa<VarDecl>(VD) &&
2675 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2676 if (Arg->isTypeDependent() || Arg->isValueDependent())
2677 Converted = TemplateArgument(Arg->Retain());
2678 else
2679 Converted = TemplateArgument(VD->getCanonicalDecl());
2680 return Invalid;
2681 }
2682 }
2683 }
2684
2685 DRE = 0;
2686 }
2687
Douglas Gregorccb07762009-02-11 19:52:55 +00002688 if (!DRE)
2689 return Diag(Arg->getSourceRange().getBegin(),
2690 diag::err_template_arg_not_pointer_to_member_form)
2691 << Arg->getSourceRange();
2692
2693 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2694 assert((isa<FieldDecl>(DRE->getDecl()) ||
2695 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2696 "Only non-static member pointers can make it here");
2697
2698 // Okay: this is the address of a non-static member, and therefore
2699 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002700 if (Arg->isTypeDependent() || Arg->isValueDependent())
2701 Converted = TemplateArgument(Arg->Retain());
2702 else
2703 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002704 return Invalid;
2705 }
2706
2707 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002708 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002709 diag::err_template_arg_not_pointer_to_member_form)
2710 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002711 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002712 diag::note_template_arg_refers_here);
2713 return true;
2714}
2715
Douglas Gregord32e0282009-02-09 23:23:08 +00002716/// \brief Check a template argument against its corresponding
2717/// non-type template parameter.
2718///
Douglas Gregor463421d2009-03-03 04:44:36 +00002719/// This routine implements the semantics of C++ [temp.arg.nontype].
2720/// It returns true if an error occurred, and false otherwise. \p
2721/// InstantiatedParamType is the type of the non-type template
2722/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002723///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002724/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002725bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002726 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002727 TemplateArgument &Converted,
2728 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002729 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2730
Douglas Gregor86560402009-02-10 23:36:10 +00002731 // If either the parameter has a dependent type or the argument is
2732 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002733 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2734 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002735 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002736 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002737 }
Douglas Gregor86560402009-02-10 23:36:10 +00002738
2739 // C++ [temp.arg.nontype]p5:
2740 // The following conversions are performed on each expression used
2741 // as a non-type template-argument. If a non-type
2742 // template-argument cannot be converted to the type of the
2743 // corresponding template-parameter then the program is
2744 // ill-formed.
2745 //
2746 // -- for a non-type template-parameter of integral or
2747 // enumeration type, integral promotions (4.5) and integral
2748 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002749 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002750 QualType ArgType = Arg->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +00002751 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002752 // C++ [temp.arg.nontype]p1:
2753 // A template-argument for a non-type, non-template
2754 // template-parameter shall be one of:
2755 //
2756 // -- an integral constant-expression of integral or enumeration
2757 // type; or
2758 // -- the name of a non-type template-parameter; or
2759 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002760 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00002761 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002762 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002763 diag::err_template_arg_not_integral_or_enumeral)
2764 << ArgType << Arg->getSourceRange();
2765 Diag(Param->getLocation(), diag::note_template_param_here);
2766 return true;
2767 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002768 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002769 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2770 << ArgType << Arg->getSourceRange();
2771 return true;
2772 }
2773
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002774 // From here on out, all we care about are the unqualified forms
2775 // of the parameter and argument types.
2776 ParamType = ParamType.getUnqualifiedType();
2777 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00002778
2779 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002780 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002781 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002782 } else if (CTAK == CTAK_Deduced) {
2783 // C++ [temp.deduct.type]p17:
2784 // If, in the declaration of a function template with a non-type
2785 // template-parameter, the non-type template- parameter is used
2786 // in an expression in the function parameter-list and, if the
2787 // corresponding template-argument is deduced, the
2788 // template-argument type shall match the type of the
2789 // template-parameter exactly, except that a template-argument
2790 // deduced from an array bound may be of any integral type.
2791 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2792 << ArgType << ParamType;
2793 Diag(Param->getLocation(), diag::note_template_param_here);
2794 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00002795 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2796 !ParamType->isEnumeralType()) {
2797 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002798 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002799 } else {
2800 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002801 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002802 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002803 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002804 Diag(Param->getLocation(), diag::note_template_param_here);
2805 return true;
2806 }
2807
Douglas Gregor52aba872009-03-14 00:20:21 +00002808 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002809 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002810 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002811
2812 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002813 llvm::APSInt OldValue = Value;
2814
2815 // Coerce the template argument's value to the value it will have
2816 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002817 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002818 if (Value.getBitWidth() != AllowedBits)
2819 Value.extOrTrunc(AllowedBits);
2820 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002821
2822 // Complain if an unsigned parameter received a negative value.
2823 if (IntegerType->isUnsignedIntegerType()
2824 && (OldValue.isSigned() && OldValue.isNegative())) {
2825 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2826 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2827 << Arg->getSourceRange();
2828 Diag(Param->getLocation(), diag::note_template_param_here);
2829 }
2830
2831 // Complain if we overflowed the template parameter's type.
2832 unsigned RequiredBits;
2833 if (IntegerType->isUnsignedIntegerType())
2834 RequiredBits = OldValue.getActiveBits();
2835 else if (OldValue.isUnsigned())
2836 RequiredBits = OldValue.getActiveBits() + 1;
2837 else
2838 RequiredBits = OldValue.getMinSignedBits();
2839 if (RequiredBits > AllowedBits) {
2840 Diag(Arg->getSourceRange().getBegin(),
2841 diag::warn_template_arg_too_large)
2842 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2843 << Arg->getSourceRange();
2844 Diag(Param->getLocation(), diag::note_template_param_here);
2845 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002846 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002847
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002848 // Add the value of this argument to the list of converted
2849 // arguments. We use the bitwidth and signedness of the template
2850 // parameter.
2851 if (Arg->isValueDependent()) {
2852 // The argument is value-dependent. Create a new
2853 // TemplateArgument with the converted expression.
2854 Converted = TemplateArgument(Arg);
2855 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002856 }
2857
John McCall0ad16662009-10-29 08:12:44 +00002858 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002859 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002860 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002861 return false;
2862 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002863
John McCall16df1e52010-03-30 21:47:33 +00002864 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2865
Douglas Gregorb242683d2010-04-01 18:32:35 +00002866 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2867 // from a template argument of type std::nullptr_t to a non-type
2868 // template parameter of type pointer to object, pointer to
2869 // function, or pointer-to-member, respectively.
2870 if (ArgType->isNullPtrType() &&
2871 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2872 Converted = TemplateArgument((NamedDecl *)0);
2873 return false;
2874 }
2875
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002876 // Handle pointer-to-function, reference-to-function, and
2877 // pointer-to-member-function all in (roughly) the same way.
2878 if (// -- For a non-type template-parameter of type pointer to
2879 // function, only the function-to-pointer conversion (4.3) is
2880 // applied. If the template-argument represents a set of
2881 // overloaded functions (or a pointer to such), the matching
2882 // function is selected from the set (13.4).
2883 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002884 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002885 // -- For a non-type template-parameter of type reference to
2886 // function, no conversions apply. If the template-argument
2887 // represents a set of overloaded functions, the matching
2888 // function is selected from the set (13.4).
2889 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002890 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002891 // -- For a non-type template-parameter of type pointer to
2892 // member function, no conversions apply. If the
2893 // template-argument represents a set of overloaded member
2894 // functions, the matching member function is selected from
2895 // the set (13.4).
2896 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002897 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002898 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002899
Douglas Gregor064fdb22010-04-14 23:11:21 +00002900 if (Arg->getType() == Context.OverloadTy) {
2901 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2902 true,
2903 FoundResult)) {
2904 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2905 return true;
2906
2907 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2908 ArgType = Arg->getType();
2909 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00002910 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002911 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002912
Douglas Gregorb242683d2010-04-01 18:32:35 +00002913 if (!ParamType->isMemberPointerType())
2914 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2915 ParamType,
2916 Arg, Converted);
2917
2918 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002919 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp, CastCategory(Arg));
Douglas Gregorb242683d2010-04-01 18:32:35 +00002920 } else if (!Context.hasSameUnqualifiedType(ArgType,
2921 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002922 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002923 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002924 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002925 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002926 Diag(Param->getLocation(), diag::note_template_param_here);
2927 return true;
2928 }
Mike Stump11289f42009-09-09 15:08:12 +00002929
Douglas Gregorb242683d2010-04-01 18:32:35 +00002930 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002931 }
2932
Chris Lattner696197c2009-02-20 21:37:53 +00002933 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002934 // -- for a non-type template-parameter of type pointer to
2935 // object, qualification conversions (4.4) and the
2936 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002937 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00002938 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002939 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002940
Douglas Gregorb242683d2010-04-01 18:32:35 +00002941 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2942 ParamType,
2943 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00002944 }
Mike Stump11289f42009-09-09 15:08:12 +00002945
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002946 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002947 // -- For a non-type template-parameter of type reference to
2948 // object, no conversions apply. The type referred to by the
2949 // reference may be more cv-qualified than the (otherwise
2950 // identical) type of the template-argument. The
2951 // template-parameter is bound directly to the
2952 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00002953 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002954 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002955
Douglas Gregor064fdb22010-04-14 23:11:21 +00002956 if (Arg->getType() == Context.OverloadTy) {
2957 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2958 ParamRefType->getPointeeType(),
2959 true,
2960 FoundResult)) {
2961 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2962 return true;
2963
2964 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2965 ArgType = Arg->getType();
2966 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00002967 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002968 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002969
Douglas Gregorb242683d2010-04-01 18:32:35 +00002970 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2971 ParamType,
2972 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002973 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002974
2975 // -- For a non-type template-parameter of type pointer to data
2976 // member, qualification conversions (4.4) are applied.
2977 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2978
Douglas Gregor1515f762009-02-11 18:22:40 +00002979 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002980 // Types match exactly: nothing more to do here.
2981 } else if (IsQualificationConversion(ArgType, ParamType)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002982 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp, CastCategory(Arg));
Douglas Gregor0e558532009-02-11 16:16:59 +00002983 } else {
2984 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002985 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002986 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002987 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002988 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002989 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002990 }
2991
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002992 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002993}
2994
2995/// \brief Check a template argument against its corresponding
2996/// template template parameter.
2997///
2998/// This routine implements the semantics of C++ [temp.arg.template].
2999/// It returns true if an error occurred, and false otherwise.
3000bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003001 const TemplateArgumentLoc &Arg) {
3002 TemplateName Name = Arg.getArgument().getAsTemplate();
3003 TemplateDecl *Template = Name.getAsTemplateDecl();
3004 if (!Template) {
3005 // Any dependent template name is fine.
3006 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3007 return false;
3008 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003009
3010 // C++ [temp.arg.template]p1:
3011 // A template-argument for a template template-parameter shall be
3012 // the name of a class template, expressed as id-expression. Only
3013 // primary class templates are considered when matching the
3014 // template template argument with the corresponding parameter;
3015 // partial specializations are not considered even if their
3016 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003017 //
3018 // Note that we also allow template template parameters here, which
3019 // will happen when we are dealing with, e.g., class template
3020 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003021 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003022 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003023 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003024 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003025 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003026 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003027 << Template;
3028 }
3029
3030 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3031 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003032 true,
3033 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003034 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003035}
3036
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003037/// \brief Given a non-type template argument that refers to a
3038/// declaration and the type of its corresponding non-type template
3039/// parameter, produce an expression that properly refers to that
3040/// declaration.
John McCalldadc5752010-08-24 06:29:42 +00003041ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003042Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3043 QualType ParamType,
3044 SourceLocation Loc) {
3045 assert(Arg.getKind() == TemplateArgument::Declaration &&
3046 "Only declaration template arguments permitted here");
3047 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3048
3049 if (VD->getDeclContext()->isRecord() &&
3050 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3051 // If the value is a class member, we might have a pointer-to-member.
3052 // Determine whether the non-type template template parameter is of
3053 // pointer-to-member type. If so, we need to build an appropriate
3054 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3055 // would refer to the member itself.
3056 if (ParamType->isMemberPointerType()) {
3057 QualType ClassType
3058 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3059 NestedNameSpecifier *Qualifier
John McCallb268a282010-08-23 23:25:46 +00003060 = NestedNameSpecifier::Create(Context, 0, false,
3061 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003062 CXXScopeSpec SS;
3063 SS.setScopeRep(Qualifier);
John McCalldadc5752010-08-24 06:29:42 +00003064 ExprResult RefExpr = BuildDeclRefExpr(VD,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003065 VD->getType().getNonReferenceType(),
3066 Loc,
3067 &SS);
3068 if (RefExpr.isInvalid())
3069 return ExprError();
3070
John McCallb268a282010-08-23 23:25:46 +00003071 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, RefExpr.get());
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.
John McCalldadc5752010-08-24 06:29:42 +00003095 ExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003096 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
John McCallb268a282010-08-23 23:25:46 +00003112 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, RefExpr.get());
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.
John McCalldadc5752010-08-24 06:29:42 +00003131ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003132Sema::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
John McCall48871652010-08-21 09:40:31 +00003606DeclResult
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 }
John McCall48871652010-08-21 09:40:31 +00003994 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00003995}
Douglas Gregor333489b2009-03-27 23:10:48 +00003996
John McCall48871652010-08-21 09:40:31 +00003997Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003998 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00003999 Declarator &D) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004000 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4001}
4002
John McCall48871652010-08-21 09:40:31 +00004003Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004004 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004005 Declarator &D) {
Douglas Gregor17a7c122009-06-24 00:54:41 +00004006 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4007 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4008 "Not a function declarator!");
4009 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00004010
Douglas Gregor17a7c122009-06-24 00:54:41 +00004011 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004012 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004013 }
Mike Stump11289f42009-09-09 15:08:12 +00004014
Douglas Gregor17a7c122009-06-24 00:54:41 +00004015 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004016
John McCall48871652010-08-21 09:40:31 +00004017 Decl *DP = HandleDeclarator(ParentScope, D,
4018 move(TemplateParameterLists),
4019 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004020 if (FunctionTemplateDecl *FunctionTemplate
John McCall48871652010-08-21 09:40:31 +00004021 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump11289f42009-09-09 15:08:12 +00004022 return ActOnStartOfFunctionDef(FnBodyScope,
John McCall48871652010-08-21 09:40:31 +00004023 FunctionTemplate->getTemplatedDecl());
4024 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4025 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4026 return 0;
Douglas Gregor17a7c122009-06-24 00:54:41 +00004027}
4028
John McCall4f7ced62010-02-11 01:33:53 +00004029/// \brief Strips various properties off an implicit instantiation
4030/// that has just been explicitly specialized.
4031static void StripImplicitInstantiation(NamedDecl *D) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004032 D->dropAttrs();
John McCall4f7ced62010-02-11 01:33:53 +00004033
4034 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4035 FD->setInlineSpecified(false);
4036 }
4037}
4038
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004039/// \brief Diagnose cases where we have an explicit template specialization
4040/// before/after an explicit template instantiation, producing diagnostics
4041/// for those cases where they are required and determining whether the
4042/// new specialization/instantiation will have any effect.
4043///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004044/// \param NewLoc the location of the new explicit specialization or
4045/// instantiation.
4046///
4047/// \param NewTSK the kind of the new explicit specialization or instantiation.
4048///
4049/// \param PrevDecl the previous declaration of the entity.
4050///
4051/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4052///
4053/// \param PrevPointOfInstantiation if valid, indicates where the previus
4054/// declaration was instantiated (either implicitly or explicitly).
4055///
Abramo Bagnara8075c852010-06-12 07:44:57 +00004056/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004057/// specialization or instantiation has no effect and should be ignored.
4058///
4059/// \returns true if there was an error that should prevent the introduction of
4060/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004061bool
4062Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4063 TemplateSpecializationKind NewTSK,
4064 NamedDecl *PrevDecl,
4065 TemplateSpecializationKind PrevTSK,
4066 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004067 bool &HasNoEffect) {
4068 HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004069
4070 switch (NewTSK) {
4071 case TSK_Undeclared:
4072 case TSK_ImplicitInstantiation:
4073 assert(false && "Don't check implicit instantiations here");
4074 return false;
4075
4076 case TSK_ExplicitSpecialization:
4077 switch (PrevTSK) {
4078 case TSK_Undeclared:
4079 case TSK_ExplicitSpecialization:
4080 // Okay, we're just specializing something that is either already
4081 // explicitly specialized or has merely been mentioned without any
4082 // instantiation.
4083 return false;
4084
4085 case TSK_ImplicitInstantiation:
4086 if (PrevPointOfInstantiation.isInvalid()) {
4087 // The declaration itself has not actually been instantiated, so it is
4088 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004089 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004090 return false;
4091 }
4092 // Fall through
4093
4094 case TSK_ExplicitInstantiationDeclaration:
4095 case TSK_ExplicitInstantiationDefinition:
4096 assert((PrevTSK == TSK_ImplicitInstantiation ||
4097 PrevPointOfInstantiation.isValid()) &&
4098 "Explicit instantiation without point of instantiation?");
4099
4100 // C++ [temp.expl.spec]p6:
4101 // If a template, a member template or the member of a class template
4102 // is explicitly specialized then that specialization shall be declared
4103 // before the first use of that specialization that would cause an
4104 // implicit instantiation to take place, in every translation unit in
4105 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004106 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4107 // Is there any previous explicit specialization declaration?
4108 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4109 return false;
4110 }
4111
Douglas Gregor1d957a32009-10-27 18:42:08 +00004112 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004113 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004114 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004115 << (PrevTSK != TSK_ImplicitInstantiation);
4116
4117 return true;
4118 }
4119 break;
4120
4121 case TSK_ExplicitInstantiationDeclaration:
4122 switch (PrevTSK) {
4123 case TSK_ExplicitInstantiationDeclaration:
4124 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00004125 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004126 return false;
4127
4128 case TSK_Undeclared:
4129 case TSK_ImplicitInstantiation:
4130 // We're explicitly instantiating something that may have already been
4131 // implicitly instantiated; that's fine.
4132 return false;
4133
4134 case TSK_ExplicitSpecialization:
4135 // C++0x [temp.explicit]p4:
4136 // For a given set of template parameters, if an explicit instantiation
4137 // of a template appears after a declaration of an explicit
4138 // specialization for that template, the explicit instantiation has no
4139 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00004140 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004141 return false;
4142
4143 case TSK_ExplicitInstantiationDefinition:
4144 // C++0x [temp.explicit]p10:
4145 // If an entity is the subject of both an explicit instantiation
4146 // declaration and an explicit instantiation definition in the same
4147 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004148 Diag(NewLoc,
4149 diag::err_explicit_instantiation_declaration_after_definition);
4150 Diag(PrevPointOfInstantiation,
4151 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004152 assert(PrevPointOfInstantiation.isValid() &&
4153 "Explicit instantiation without point of instantiation?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00004154 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004155 return false;
4156 }
4157 break;
4158
4159 case TSK_ExplicitInstantiationDefinition:
4160 switch (PrevTSK) {
4161 case TSK_Undeclared:
4162 case TSK_ImplicitInstantiation:
4163 // We're explicitly instantiating something that may have already been
4164 // implicitly instantiated; that's fine.
4165 return false;
4166
4167 case TSK_ExplicitSpecialization:
4168 // C++ DR 259, C++0x [temp.explicit]p4:
4169 // For a given set of template parameters, if an explicit
4170 // instantiation of a template appears after a declaration of
4171 // an explicit specialization for that template, the explicit
4172 // instantiation has no effect.
4173 //
4174 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004175 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004176 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004177 if (!getLangOptions().CPlusPlus0x) {
4178 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004179 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004180 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004181 diag::note_previous_template_specialization);
4182 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004183 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004184 return false;
4185
4186 case TSK_ExplicitInstantiationDeclaration:
4187 // We're explicity instantiating a definition for something for which we
4188 // were previously asked to suppress instantiations. That's fine.
4189 return false;
4190
4191 case TSK_ExplicitInstantiationDefinition:
4192 // C++0x [temp.spec]p5:
4193 // For a given template and a given set of template-arguments,
4194 // - an explicit instantiation definition shall appear at most once
4195 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004196 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004197 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004198 Diag(PrevPointOfInstantiation,
4199 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004200 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004201 return false;
4202 }
4203 break;
4204 }
4205
4206 assert(false && "Missing specialization/instantiation case?");
4207
4208 return false;
4209}
4210
John McCallb9c78482010-04-08 09:05:18 +00004211/// \brief Perform semantic analysis for the given dependent function
4212/// template specialization. The only possible way to get a dependent
4213/// function template specialization is with a friend declaration,
4214/// like so:
4215///
4216/// template <class T> void foo(T);
4217/// template <class T> class A {
4218/// friend void foo<>(T);
4219/// };
4220///
4221/// There really isn't any useful analysis we can do here, so we
4222/// just store the information.
4223bool
4224Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4225 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4226 LookupResult &Previous) {
4227 // Remove anything from Previous that isn't a function template in
4228 // the correct context.
4229 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4230 LookupResult::Filter F = Previous.makeFilter();
4231 while (F.hasNext()) {
4232 NamedDecl *D = F.next()->getUnderlyingDecl();
4233 if (!isa<FunctionTemplateDecl>(D) ||
4234 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4235 F.erase();
4236 }
4237 F.done();
4238
4239 // Should this be diagnosed here?
4240 if (Previous.empty()) return true;
4241
4242 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4243 ExplicitTemplateArgs);
4244 return false;
4245}
4246
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004247/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004248/// specialization.
4249///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004250/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004251/// explicit function template specialization. On successful completion,
4252/// the function declaration \p FD will become a function template
4253/// specialization.
4254///
4255/// \param FD the function declaration, which will be updated to become a
4256/// function template specialization.
4257///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004258/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4259/// if any. Note that this may be valid info even when 0 arguments are
4260/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4261/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004262///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004263/// \param PrevDecl the set of declarations that may be specialized by
4264/// this function specialization.
4265bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004266Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004267 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004268 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004269 // The set of function template specializations that could match this
4270 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004271 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004272
4273 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00004274 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4275 I != E; ++I) {
4276 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4277 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004278 // Only consider templates found within the same semantic lookup scope as
4279 // FD.
4280 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4281 continue;
4282
4283 // C++ [temp.expl.spec]p11:
4284 // A trailing template-argument can be left unspecified in the
4285 // template-id naming an explicit function template specialization
4286 // provided it can be deduced from the function argument type.
4287 // Perform template argument deduction to determine whether we may be
4288 // specializing this template.
4289 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004290 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004291 FunctionDecl *Specialization = 0;
4292 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004293 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004294 FD->getType(),
4295 Specialization,
4296 Info)) {
4297 // FIXME: Template argument deduction failed; record why it failed, so
4298 // that we can provide nifty diagnostics.
4299 (void)TDK;
4300 continue;
4301 }
4302
4303 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004304 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004305 }
4306 }
4307
Douglas Gregor5de279c2009-09-26 03:41:46 +00004308 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004309 UnresolvedSetIterator Result
4310 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4311 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004312 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004313 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004314 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004315 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004316 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004317 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004318 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004319
4320 // Ignore access information; it doesn't figure into redeclaration checking.
4321 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004322 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004323
4324 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004325 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004326
4327 // If this is a friend declaration, then we're not really declaring
4328 // an explicit specialization.
4329 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004330
Douglas Gregor54888652009-10-07 00:13:32 +00004331 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004332 if (!isFriend &&
4333 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004334 Specialization->getPrimaryTemplate(),
4335 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004336 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004337 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004338
4339 // C++ [temp.expl.spec]p6:
4340 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004341 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004342 // before the first use of that specialization that would cause an implicit
4343 // instantiation to take place, in every translation unit in which such a
4344 // use occurs; no diagnostic is required.
4345 FunctionTemplateSpecializationInfo *SpecInfo
4346 = Specialization->getTemplateSpecializationInfo();
4347 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004348
Abramo Bagnara8075c852010-06-12 07:44:57 +00004349 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00004350 if (!isFriend &&
4351 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004352 TSK_ExplicitSpecialization,
4353 Specialization,
4354 SpecInfo->getTemplateSpecializationKind(),
4355 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004356 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004357 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004358
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004359 // Mark the prior declaration as an explicit specialization, so that later
4360 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004361 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00004362 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004363 MarkUnusedFileScopedDecl(Specialization);
4364 }
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004365
4366 // Turn the given function declaration into a function template
4367 // specialization, with the template arguments from the previous
4368 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004369 // Take copies of (semantic and syntactic) template argument lists.
4370 const TemplateArgumentList* TemplArgs = new (Context)
4371 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4372 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4373 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004374 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004375 TemplArgs, /*InsertPos=*/0,
4376 SpecInfo->getTemplateSpecializationKind(),
4377 TemplArgsAsWritten);
4378
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004379 // The "previous declaration" for this function template specialization is
4380 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004381 Previous.clear();
4382 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004383 return false;
4384}
4385
Douglas Gregor86d142a2009-10-08 07:24:58 +00004386/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004387/// specialization.
4388///
4389/// This routine performs all of the semantic analysis required for an
4390/// explicit member function specialization. On successful completion,
4391/// the function declaration \p FD will become a member function
4392/// specialization.
4393///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004394/// \param Member the member declaration, which will be updated to become a
4395/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004396///
John McCall1f82f242009-11-18 22:49:29 +00004397/// \param Previous the set of declarations, one of which may be specialized
4398/// by this function specialization; the set will be modified to contain the
4399/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004400bool
John McCall1f82f242009-11-18 22:49:29 +00004401Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004402 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004403
Douglas Gregor86d142a2009-10-08 07:24:58 +00004404 // Try to find the member we are instantiating.
4405 NamedDecl *Instantiation = 0;
4406 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004407 MemberSpecializationInfo *MSInfo = 0;
4408
John McCall1f82f242009-11-18 22:49:29 +00004409 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004410 // Nowhere to look anyway.
4411 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004412 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4413 I != E; ++I) {
4414 NamedDecl *D = (*I)->getUnderlyingDecl();
4415 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004416 if (Context.hasSameType(Function->getType(), Method->getType())) {
4417 Instantiation = Method;
4418 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004419 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004420 break;
4421 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004422 }
4423 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004424 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004425 VarDecl *PrevVar;
4426 if (Previous.isSingleResult() &&
4427 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004428 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004429 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004430 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004431 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004432 }
4433 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004434 CXXRecordDecl *PrevRecord;
4435 if (Previous.isSingleResult() &&
4436 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4437 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004438 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004439 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004440 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004441 }
4442
4443 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004444 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004445 // specializations are always out-of-line, the caller will complain about
4446 // this mismatch later.
4447 return false;
4448 }
John McCalle820e5e2010-04-13 20:37:33 +00004449
4450 // If this is a friend, just bail out here before we start turning
4451 // things into explicit specializations.
4452 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4453 // Preserve instantiation information.
4454 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4455 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4456 cast<CXXMethodDecl>(InstantiatedFrom),
4457 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4458 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4459 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4460 cast<CXXRecordDecl>(InstantiatedFrom),
4461 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4462 }
4463
4464 Previous.clear();
4465 Previous.addDecl(Instantiation);
4466 return false;
4467 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004468
Douglas Gregor86d142a2009-10-08 07:24:58 +00004469 // Make sure that this is a specialization of a member.
4470 if (!InstantiatedFrom) {
4471 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4472 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004473 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4474 return true;
4475 }
4476
Douglas Gregor06db9f52009-10-12 20:18:28 +00004477 // C++ [temp.expl.spec]p6:
4478 // If a template, a member template or the member of a class template is
4479 // explicitly specialized then that spe- cialization shall be declared
4480 // before the first use of that specialization that would cause an implicit
4481 // instantiation to take place, in every translation unit in which such a
4482 // use occurs; no diagnostic is required.
4483 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004484
Abramo Bagnara8075c852010-06-12 07:44:57 +00004485 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00004486 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4487 TSK_ExplicitSpecialization,
4488 Instantiation,
4489 MSInfo->getTemplateSpecializationKind(),
4490 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004491 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004492 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004493
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004494 // Check the scope of this explicit specialization.
4495 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004496 InstantiatedFrom,
4497 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004498 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004499 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004500
Douglas Gregor86d142a2009-10-08 07:24:58 +00004501 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004502 // the original declaration to note that it is an explicit specialization
4503 // (if it was previously an implicit instantiation). This latter step
4504 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004505 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004506 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4507 if (InstantiationFunction->getTemplateSpecializationKind() ==
4508 TSK_ImplicitInstantiation) {
4509 InstantiationFunction->setTemplateSpecializationKind(
4510 TSK_ExplicitSpecialization);
4511 InstantiationFunction->setLocation(Member->getLocation());
4512 }
4513
Douglas Gregor86d142a2009-10-08 07:24:58 +00004514 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4515 cast<CXXMethodDecl>(InstantiatedFrom),
4516 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004517 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004518 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004519 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4520 if (InstantiationVar->getTemplateSpecializationKind() ==
4521 TSK_ImplicitInstantiation) {
4522 InstantiationVar->setTemplateSpecializationKind(
4523 TSK_ExplicitSpecialization);
4524 InstantiationVar->setLocation(Member->getLocation());
4525 }
4526
Douglas Gregor86d142a2009-10-08 07:24:58 +00004527 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4528 cast<VarDecl>(InstantiatedFrom),
4529 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004530 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004531 } else {
4532 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004533 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4534 if (InstantiationClass->getTemplateSpecializationKind() ==
4535 TSK_ImplicitInstantiation) {
4536 InstantiationClass->setTemplateSpecializationKind(
4537 TSK_ExplicitSpecialization);
4538 InstantiationClass->setLocation(Member->getLocation());
4539 }
4540
Douglas Gregor86d142a2009-10-08 07:24:58 +00004541 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004542 cast<CXXRecordDecl>(InstantiatedFrom),
4543 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004544 }
4545
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004546 // Save the caller the trouble of having to figure out which declaration
4547 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004548 Previous.clear();
4549 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004550 return false;
4551}
4552
Douglas Gregore47f5a72009-10-14 23:41:34 +00004553/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004554///
4555/// \returns true if a serious error occurs, false otherwise.
4556static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00004557 SourceLocation InstLoc,
4558 bool WasQualifiedName) {
4559 DeclContext *ExpectedContext
4560 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4561 DeclContext *CurContext = S.CurContext->getLookupContext();
4562
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004563 if (CurContext->isRecord()) {
4564 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4565 << D;
4566 return true;
4567 }
4568
Douglas Gregore47f5a72009-10-14 23:41:34 +00004569 // C++0x [temp.explicit]p2:
4570 // An explicit instantiation shall appear in an enclosing namespace of its
4571 // template.
4572 //
4573 // This is DR275, which we do not retroactively apply to C++98/03.
4574 if (S.getLangOptions().CPlusPlus0x &&
4575 !CurContext->Encloses(ExpectedContext)) {
4576 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004577 S.Diag(InstLoc,
4578 S.getLangOptions().CPlusPlus0x?
4579 diag::err_explicit_instantiation_out_of_scope
4580 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004581 << D << NS;
4582 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004583 S.Diag(InstLoc,
4584 S.getLangOptions().CPlusPlus0x?
4585 diag::err_explicit_instantiation_must_be_global
4586 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004587 << D;
4588 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004589 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004590 }
4591
4592 // C++0x [temp.explicit]p2:
4593 // If the name declared in the explicit instantiation is an unqualified
4594 // name, the explicit instantiation shall appear in the namespace where
4595 // its template is declared or, if that namespace is inline (7.3.1), any
4596 // namespace from its enclosing namespace set.
4597 if (WasQualifiedName)
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004598 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004599
4600 if (CurContext->Equals(ExpectedContext))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004601 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004602
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004603 S.Diag(InstLoc,
4604 S.getLangOptions().CPlusPlus0x?
4605 diag::err_explicit_instantiation_unqualified_wrong_namespace
4606 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004607 << D << ExpectedContext;
4608 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004609 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004610}
4611
4612/// \brief Determine whether the given scope specifier has a template-id in it.
4613static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4614 if (!SS.isSet())
4615 return false;
4616
4617 // C++0x [temp.explicit]p2:
4618 // If the explicit instantiation is for a member function, a member class
4619 // or a static data member of a class template specialization, the name of
4620 // the class template specialization in the qualified-id for the member
4621 // name shall be a simple-template-id.
4622 //
4623 // C++98 has the same restriction, just worded differently.
4624 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4625 NNS; NNS = NNS->getPrefix())
4626 if (Type *T = NNS->getAsType())
4627 if (isa<TemplateSpecializationType>(T))
4628 return true;
4629
4630 return false;
4631}
4632
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004633// Explicit instantiation of a class template specialization
Douglas Gregora1f49972009-05-13 00:25:59 +00004634Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004635Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004636 SourceLocation ExternLoc,
4637 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004638 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004639 SourceLocation KWLoc,
4640 const CXXScopeSpec &SS,
4641 TemplateTy TemplateD,
4642 SourceLocation TemplateNameLoc,
4643 SourceLocation LAngleLoc,
4644 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004645 SourceLocation RAngleLoc,
4646 AttributeList *Attr) {
4647 // Find the class template we're specializing
4648 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004649 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004650 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4651
4652 // Check that the specialization uses the same tag kind as the
4653 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004654 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4655 assert(Kind != TTK_Enum &&
4656 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004657 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004658 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004659 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004660 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004661 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004662 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004663 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004664 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004665 diag::note_previous_use);
4666 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4667 }
4668
Douglas Gregore47f5a72009-10-14 23:41:34 +00004669 // C++0x [temp.explicit]p2:
4670 // There are two forms of explicit instantiation: an explicit instantiation
4671 // definition and an explicit instantiation declaration. An explicit
4672 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004673 TemplateSpecializationKind TSK
4674 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4675 : TSK_ExplicitInstantiationDeclaration;
4676
Douglas Gregora1f49972009-05-13 00:25:59 +00004677 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004678 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004679 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004680
4681 // Check that the template argument list is well-formed for this
4682 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004683 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4684 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004685 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4686 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004687 return true;
4688
Mike Stump11289f42009-09-09 15:08:12 +00004689 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004690 ClassTemplate->getTemplateParameters()->size()) &&
4691 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004692
Douglas Gregora1f49972009-05-13 00:25:59 +00004693 // Find the class template specialization declaration that
4694 // corresponds to these arguments.
Douglas Gregora1f49972009-05-13 00:25:59 +00004695 void *InsertPos = 0;
4696 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004697 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4698 Converted.flatSize(), InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004699
Abramo Bagnara8075c852010-06-12 07:44:57 +00004700 TemplateSpecializationKind PrevDecl_TSK
4701 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4702
Douglas Gregor54888652009-10-07 00:13:32 +00004703 // C++0x [temp.explicit]p2:
4704 // [...] An explicit instantiation shall appear in an enclosing
4705 // namespace of its template. [...]
4706 //
4707 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004708 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4709 SS.isSet()))
4710 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004711
Douglas Gregora1f49972009-05-13 00:25:59 +00004712 ClassTemplateSpecializationDecl *Specialization = 0;
4713
Douglas Gregor0681a352009-11-25 06:01:46 +00004714 bool ReusedDecl = false;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004715 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004716 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00004717 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004718 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004719 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004720 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00004721 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00004722
Abramo Bagnara8075c852010-06-12 07:44:57 +00004723 // Even though HasNoEffect == true means that this explicit instantiation
4724 // has no effect on semantics, we go on to put its syntax in the AST.
4725
4726 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4727 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004728 // Since the only prior class template specialization with these
4729 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00004730 // declaration node as our own, updating the source location
4731 // for the template name to reflect our new declaration.
4732 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004733 Specialization = PrevDecl;
4734 Specialization->setLocation(TemplateNameLoc);
4735 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004736 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004737 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004738 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004739
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004740 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004741 // Create a new class template specialization declaration node for
4742 // this explicit specialization.
4743 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004744 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00004745 ClassTemplate->getDeclContext(),
4746 TemplateNameLoc,
4747 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004748 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004749 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004750
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004751 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00004752 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004753 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004754 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004755 }
4756
4757 // Build the fully-sugared type for this explicit instantiation as
4758 // the user wrote in the explicit instantiation itself. This means
4759 // that we'll pretty-print the type retrieved from the
4760 // specialization's declaration the way that the user actually wrote
4761 // the explicit instantiation, rather than formatting the name based
4762 // on the "canonical" representation used to store the template
4763 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004764 TypeSourceInfo *WrittenTy
4765 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4766 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004767 Context.getTypeDeclType(Specialization));
4768 Specialization->setTypeAsWritten(WrittenTy);
4769 TemplateArgsIn.release();
4770
Abramo Bagnara8075c852010-06-12 07:44:57 +00004771 // Set source locations for keywords.
4772 Specialization->setExternLoc(ExternLoc);
4773 Specialization->setTemplateKeywordLoc(TemplateLoc);
4774
4775 // Add the explicit instantiation into its lexical context. However,
4776 // since explicit instantiations are never found by name lookup, we
4777 // just put it into the declaration context directly.
4778 Specialization->setLexicalDeclContext(CurContext);
4779 CurContext->addDecl(Specialization);
4780
4781 // Syntax is now OK, so return if it has no other effect on semantics.
4782 if (HasNoEffect) {
4783 // Set the template specialization kind.
4784 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00004785 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00004786 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004787
4788 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004789 // A definition of a class template or class member template
4790 // shall be in scope at the point of the explicit instantiation of
4791 // the class template or class member template.
4792 //
4793 // This check comes when we actually try to perform the
4794 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004795 ClassTemplateSpecializationDecl *Def
4796 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004797 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004798 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004799 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004800 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00004801 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004802 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
4803 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004804
Douglas Gregor1d957a32009-10-27 18:42:08 +00004805 // Instantiate the members of this class template specialization.
4806 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004807 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004808 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004809 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4810
4811 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4812 // TSK_ExplicitInstantiationDefinition
4813 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4814 TSK == TSK_ExplicitInstantiationDefinition)
4815 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004816
Douglas Gregor12e49d32009-10-15 22:53:21 +00004817 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004818 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004819
Abramo Bagnara8075c852010-06-12 07:44:57 +00004820 // Set the template specialization kind.
4821 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00004822 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00004823}
4824
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004825// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00004826DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004827Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004828 SourceLocation ExternLoc,
4829 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004830 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004831 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004832 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004833 IdentifierInfo *Name,
4834 SourceLocation NameLoc,
4835 AttributeList *Attr) {
4836
Douglas Gregord6ab8742009-05-28 23:31:59 +00004837 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004838 bool IsDependent = false;
John McCall48871652010-08-21 09:40:31 +00004839 Decl *TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
4840 KWLoc, SS, Name, NameLoc, Attr, AS_none,
4841 MultiTemplateParamsArg(*this, 0, 0),
4842 Owned, IsDependent);
John McCall7f41d982009-09-11 04:59:25 +00004843 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4844
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004845 if (!TagD)
4846 return true;
4847
John McCall48871652010-08-21 09:40:31 +00004848 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004849 if (Tag->isEnum()) {
4850 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4851 << Context.getTypeDeclType(Tag);
4852 return true;
4853 }
4854
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004855 if (Tag->isInvalidDecl())
4856 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004857
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004858 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4859 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4860 if (!Pattern) {
4861 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4862 << Context.getTypeDeclType(Record);
4863 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4864 return true;
4865 }
4866
Douglas Gregore47f5a72009-10-14 23:41:34 +00004867 // C++0x [temp.explicit]p2:
4868 // If the explicit instantiation is for a class or member class, the
4869 // elaborated-type-specifier in the declaration shall include a
4870 // simple-template-id.
4871 //
4872 // C++98 has the same restriction, just worded differently.
4873 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00004874 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004875 << Record << SS.getRange();
4876
4877 // C++0x [temp.explicit]p2:
4878 // There are two forms of explicit instantiation: an explicit instantiation
4879 // definition and an explicit instantiation declaration. An explicit
4880 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004881 TemplateSpecializationKind TSK
4882 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4883 : TSK_ExplicitInstantiationDeclaration;
4884
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004885 // C++0x [temp.explicit]p2:
4886 // [...] An explicit instantiation shall appear in an enclosing
4887 // namespace of its template. [...]
4888 //
4889 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004890 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004891
4892 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004893 CXXRecordDecl *PrevDecl
4894 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004895 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004896 PrevDecl = Record;
4897 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004898 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00004899 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004900 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004901 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004902 PrevDecl,
4903 MSInfo->getTemplateSpecializationKind(),
4904 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004905 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004906 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004907 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004908 return TagD;
4909 }
4910
Douglas Gregor12e49d32009-10-15 22:53:21 +00004911 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004912 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004913 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004914 // C++ [temp.explicit]p3:
4915 // A definition of a member class of a class template shall be in scope
4916 // at the point of an explicit instantiation of the member class.
4917 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004918 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004919 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004920 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4921 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004922 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4923 << Pattern;
4924 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004925 } else {
4926 if (InstantiateClass(NameLoc, Record, Def,
4927 getTemplateInstantiationArgs(Record),
4928 TSK))
4929 return true;
4930
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004931 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004932 if (!RecordDef)
4933 return true;
4934 }
4935 }
4936
4937 // Instantiate all of the members of the class.
4938 InstantiateClassMembers(NameLoc, RecordDef,
4939 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004940
Douglas Gregor88d292c2010-05-13 16:44:06 +00004941 if (TSK == TSK_ExplicitInstantiationDefinition)
4942 MarkVTableUsed(NameLoc, RecordDef, true);
4943
Mike Stump87c57ac2009-05-16 07:39:55 +00004944 // FIXME: We don't have any representation for explicit instantiations of
4945 // member classes. Such a representation is not needed for compilation, but it
4946 // should be available for clients that want to see all of the declarations in
4947 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004948 return TagD;
4949}
4950
Douglas Gregor450f00842009-09-25 18:43:00 +00004951Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4952 SourceLocation ExternLoc,
4953 SourceLocation TemplateLoc,
4954 Declarator &D) {
4955 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004956 // TODO: check if/when DNInfo should replace Name.
4957 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4958 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00004959 if (!Name) {
4960 if (!D.isInvalidType())
4961 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4962 diag::err_explicit_instantiation_requires_name)
4963 << D.getDeclSpec().getSourceRange()
4964 << D.getSourceRange();
4965
4966 return true;
4967 }
4968
4969 // The scope passed in may not be a decl scope. Zip up the scope tree until
4970 // we find one that is.
4971 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4972 (S->getFlags() & Scope::TemplateParamScope) != 0)
4973 S = S->getParent();
4974
4975 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00004976 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
4977 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00004978 if (R.isNull())
4979 return true;
4980
4981 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4982 // Cannot explicitly instantiate a typedef.
4983 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4984 << Name;
4985 return true;
4986 }
4987
Douglas Gregor3c74d412009-10-14 20:14:33 +00004988 // C++0x [temp.explicit]p1:
4989 // [...] An explicit instantiation of a function template shall not use the
4990 // inline or constexpr specifiers.
4991 // Presumably, this also applies to member functions of class templates as
4992 // well.
4993 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4994 Diag(D.getDeclSpec().getInlineSpecLoc(),
4995 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00004996 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004997
4998 // FIXME: check for constexpr specifier.
4999
Douglas Gregore47f5a72009-10-14 23:41:34 +00005000 // C++0x [temp.explicit]p2:
5001 // There are two forms of explicit instantiation: an explicit instantiation
5002 // definition and an explicit instantiation declaration. An explicit
5003 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00005004 TemplateSpecializationKind TSK
5005 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5006 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005007
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005008 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005009 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00005010
5011 if (!R->isFunctionType()) {
5012 // C++ [temp.explicit]p1:
5013 // A [...] static data member of a class template can be explicitly
5014 // instantiated from the member definition associated with its class
5015 // template.
John McCall27b18f82009-11-17 02:14:36 +00005016 if (Previous.isAmbiguous())
5017 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00005018
John McCall67c00872009-12-02 08:25:40 +00005019 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005020 if (!Prev || !Prev->isStaticDataMember()) {
5021 // We expect to see a data data member here.
5022 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5023 << Name;
5024 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5025 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005026 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005027 return true;
5028 }
5029
5030 if (!Prev->getInstantiatedFromStaticDataMember()) {
5031 // FIXME: Check for explicit specialization?
5032 Diag(D.getIdentifierLoc(),
5033 diag::err_explicit_instantiation_data_member_not_instantiated)
5034 << Prev;
5035 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5036 // FIXME: Can we provide a note showing where this was declared?
5037 return true;
5038 }
5039
Douglas Gregore47f5a72009-10-14 23:41:34 +00005040 // C++0x [temp.explicit]p2:
5041 // If the explicit instantiation is for a member function, a member class
5042 // or a static data member of a class template specialization, the name of
5043 // the class template specialization in the qualified-id for the member
5044 // name shall be a simple-template-id.
5045 //
5046 // C++98 has the same restriction, just worded differently.
5047 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5048 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005049 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005050 << Prev << D.getCXXScopeSpec().getRange();
5051
5052 // Check the scope of this explicit instantiation.
5053 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5054
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005055 // Verify that it is okay to explicitly instantiate here.
5056 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5057 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00005058 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005059 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005060 MSInfo->getTemplateSpecializationKind(),
5061 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005062 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005063 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005064 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005065 return (Decl*) 0;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005066
Douglas Gregor450f00842009-09-25 18:43:00 +00005067 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005068 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005069 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00005070 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
5071 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00005072
5073 // FIXME: Create an ExplicitInstantiation node?
John McCall48871652010-08-21 09:40:31 +00005074 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005075 }
5076
Douglas Gregor0e876e02009-09-25 23:53:26 +00005077 // If the declarator is a template-id, translate the parser's template
5078 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005079 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005080 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005081 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5082 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005083 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5084 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005085 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5086 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005087 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005088 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005089 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005090 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005091 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005092
Douglas Gregor450f00842009-09-25 18:43:00 +00005093 // C++ [temp.explicit]p1:
5094 // A [...] function [...] can be explicitly instantiated from its template.
5095 // A member function [...] of a class template can be explicitly
5096 // instantiated from the member definition associated with its class
5097 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005098 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005099 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5100 P != PEnd; ++P) {
5101 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005102 if (!HasExplicitTemplateArgs) {
5103 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5104 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5105 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005106
John McCall58cc69d2010-01-27 01:50:18 +00005107 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005108 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5109 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005110 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005111 }
5112 }
5113
5114 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5115 if (!FunTmpl)
5116 continue;
5117
John McCallbc077cf2010-02-08 23:07:23 +00005118 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005119 FunctionDecl *Specialization = 0;
5120 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005121 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005122 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005123 R, Specialization, Info)) {
5124 // FIXME: Keep track of almost-matches?
5125 (void)TDK;
5126 continue;
5127 }
5128
John McCall58cc69d2010-01-27 01:50:18 +00005129 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005130 }
5131
5132 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005133 UnresolvedSetIterator Result
5134 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005135 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005136 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5137 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5138 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005139
John McCall58cc69d2010-01-27 01:50:18 +00005140 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005141 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005142
5143 // Ignore access control bits, we don't need them for redeclaration checking.
5144 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005145
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005146 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005147 Diag(D.getIdentifierLoc(),
5148 diag::err_explicit_instantiation_member_function_not_instantiated)
5149 << Specialization
5150 << (Specialization->getTemplateSpecializationKind() ==
5151 TSK_ExplicitSpecialization);
5152 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5153 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005154 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005155
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005156 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005157 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5158 PrevDecl = Specialization;
5159
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005160 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005161 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005162 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005163 PrevDecl,
5164 PrevDecl->getTemplateSpecializationKind(),
5165 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005166 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005167 return true;
5168
5169 // FIXME: We may still want to build some representation of this
5170 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00005171 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005172 return (Decl*) 0;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005173 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005174
5175 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005176
5177 if (TSK == TSK_ExplicitInstantiationDefinition)
5178 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5179 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005180
Douglas Gregore47f5a72009-10-14 23:41:34 +00005181 // C++0x [temp.explicit]p2:
5182 // If the explicit instantiation is for a member function, a member class
5183 // or a static data member of a class template specialization, the name of
5184 // the class template specialization in the qualified-id for the member
5185 // name shall be a simple-template-id.
5186 //
5187 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005188 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005189 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005190 D.getCXXScopeSpec().isSet() &&
5191 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5192 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005193 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005194 << Specialization << D.getCXXScopeSpec().getRange();
5195
5196 CheckExplicitInstantiationScope(*this,
5197 FunTmpl? (NamedDecl *)FunTmpl
5198 : Specialization->getInstantiatedFromMemberFunction(),
5199 D.getIdentifierLoc(),
5200 D.getCXXScopeSpec().isSet());
5201
Douglas Gregor450f00842009-09-25 18:43:00 +00005202 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCall48871652010-08-21 09:40:31 +00005203 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005204}
5205
Douglas Gregor333489b2009-03-27 23:10:48 +00005206Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005207Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5208 const CXXScopeSpec &SS, IdentifierInfo *Name,
5209 SourceLocation TagLoc, SourceLocation NameLoc) {
5210 // This has to hold, because SS is expected to be defined.
5211 assert(Name && "Expected a name in a dependent tag");
5212
5213 NestedNameSpecifier *NNS
5214 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5215 if (!NNS)
5216 return true;
5217
Abramo Bagnara6150c882010-05-11 21:36:43 +00005218 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005219
Douglas Gregorba41d012010-04-24 16:38:41 +00005220 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5221 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005222 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005223 return true;
5224 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005225
5226 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallba7bf592010-08-24 05:47:05 +00005227 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCall7f41d982009-09-11 04:59:25 +00005228}
5229
5230Sema::TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005231Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5232 const CXXScopeSpec &SS, const IdentifierInfo &II,
5233 SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005234 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005235 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5236 if (!NNS)
5237 return true;
5238
Douglas Gregorf7d77712010-06-16 22:31:08 +00005239 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5240 !getLangOptions().CPlusPlus0x)
5241 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5242 << FixItHint::CreateRemoval(TypenameLoc);
5243
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005244 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005245 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005246 if (T.isNull())
5247 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005248
5249 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5250 if (isa<DependentNameType>(T)) {
5251 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005252 TL.setKeywordLoc(TypenameLoc);
5253 TL.setQualifierRange(SS.getRange());
5254 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005255 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005256 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005257 TL.setKeywordLoc(TypenameLoc);
5258 TL.setQualifierRange(SS.getRange());
5259 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005260 }
5261
John McCallba7bf592010-08-24 05:47:05 +00005262 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00005263}
5264
Douglas Gregordce2b622009-04-01 00:28:59 +00005265Sema::TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005266Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5267 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallba7bf592010-08-24 05:47:05 +00005268 ParsedType Ty) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00005269 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5270 !getLangOptions().CPlusPlus0x)
5271 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5272 << FixItHint::CreateRemoval(TypenameLoc);
5273
John McCallf7bcc812010-05-28 23:32:21 +00005274 TypeSourceInfo *InnerTSI = 0;
5275 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCallf7bcc812010-05-28 23:32:21 +00005276
5277 assert(isa<TemplateSpecializationType>(T) &&
5278 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005279
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005280 if (computeDeclContext(SS, false)) {
5281 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005282 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005283 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005284
5285 // Push the inner type, preserving its source locations if possible.
5286 TypeLocBuilder Builder;
5287 if (InnerTSI)
5288 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5289 else
5290 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5291
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005292 /* Note: NNS already embedded in template specialization type T. */
5293 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCallf7bcc812010-05-28 23:32:21 +00005294 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5295 TL.setKeywordLoc(TypenameLoc);
5296 TL.setQualifierRange(SS.getRange());
5297
5298 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallba7bf592010-08-24 05:47:05 +00005299 return CreateParsedType(T, TSI);
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005300 }
Mike Stump11289f42009-09-09 15:08:12 +00005301
John McCallc392f372010-06-11 00:33:02 +00005302 // TODO: it's really silly that we make a template specialization
5303 // type earlier only to drop it again here.
5304 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5305 DependentTemplateName *DTN =
5306 TST->getTemplateName().getAsDependentTemplateName();
5307 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005308 assert(DTN->getQualifier()
5309 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5310 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5311 DTN->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00005312 DTN->getIdentifier(),
5313 TST->getNumArgs(),
5314 TST->getArgs());
John McCall99b2fe52010-04-29 23:50:39 +00005315 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCallc392f372010-06-11 00:33:02 +00005316 DependentTemplateSpecializationTypeLoc TL =
5317 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5318 if (InnerTSI) {
5319 TemplateSpecializationTypeLoc TSTL =
5320 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5321 TL.setLAngleLoc(TSTL.getLAngleLoc());
5322 TL.setRAngleLoc(TSTL.getRAngleLoc());
5323 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5324 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5325 } else {
5326 TL.initializeLocal(SourceLocation());
5327 }
John McCallf7bcc812010-05-28 23:32:21 +00005328 TL.setKeywordLoc(TypenameLoc);
5329 TL.setQualifierRange(SS.getRange());
John McCallba7bf592010-08-24 05:47:05 +00005330 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00005331}
5332
Douglas Gregor333489b2009-03-27 23:10:48 +00005333/// \brief Build the type that describes a C++ typename specifier,
5334/// e.g., "typename T::type".
5335QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005336Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5337 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005338 SourceLocation KeywordLoc, SourceRange NNSRange,
5339 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005340 CXXScopeSpec SS;
5341 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005342 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005343
John McCall0b66eb32010-05-01 00:40:08 +00005344 DeclContext *Ctx = computeDeclContext(SS);
5345 if (!Ctx) {
5346 // If the nested-name-specifier is dependent and couldn't be
5347 // resolved to a type, build a typename type.
5348 assert(NNS->isDependent());
5349 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005350 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005351
John McCall0b66eb32010-05-01 00:40:08 +00005352 // If the nested-name-specifier refers to the current instantiation,
5353 // the "typename" keyword itself is superfluous. In C++03, the
5354 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5355 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00005356 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005357
John McCall0b66eb32010-05-01 00:40:08 +00005358 if (RequireCompleteDeclContext(SS, Ctx))
5359 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005360
5361 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005362 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005363 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005364 unsigned DiagID = 0;
5365 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005366 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005367 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005368 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005369 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005370
5371 case LookupResult::NotFoundInCurrentInstantiation:
5372 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005373 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005374
5375 case LookupResult::Found:
Douglas Gregorf7d77712010-06-16 22:31:08 +00005376 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005377 // We found a type. Build an ElaboratedType, since the
5378 // typename-specifier was just sugar.
5379 return Context.getElaboratedType(ETK_Typename, NNS,
5380 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005381 }
5382
5383 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005384 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005385 break;
5386
John McCalle61f2ba2009-11-18 02:36:19 +00005387 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005388 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005389 return QualType();
5390
Douglas Gregor333489b2009-03-27 23:10:48 +00005391 case LookupResult::FoundOverloaded:
5392 DiagID = diag::err_typename_nested_not_type;
5393 Referenced = *Result.begin();
5394 break;
5395
John McCall6538c932009-10-10 05:48:19 +00005396 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005397 return QualType();
5398 }
5399
5400 // If we get here, it's because name lookup did not find a
5401 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005402 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5403 IILoc);
5404 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005405 if (Referenced)
5406 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5407 << Name;
5408 return QualType();
5409}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005410
5411namespace {
5412 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005413 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005414 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005415 SourceLocation Loc;
5416 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005417
Douglas Gregor15acfb92009-08-06 16:20:37 +00005418 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005419 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5420
Mike Stump11289f42009-09-09 15:08:12 +00005421 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005422 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005423 DeclarationName Entity)
5424 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005425 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005426
5427 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005428 /// transformed.
5429 ///
5430 /// For the purposes of type reconstruction, a type has already been
5431 /// transformed if it is NULL or if it is not dependent.
5432 bool AlreadyTransformed(QualType T) {
5433 return T.isNull() || !T->isDependentType();
5434 }
Mike Stump11289f42009-09-09 15:08:12 +00005435
5436 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005437 /// rebuilt.
5438 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005439
Douglas Gregor15acfb92009-08-06 16:20:37 +00005440 /// \brief Returns the name of the entity whose type is being rebuilt.
5441 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005442
Douglas Gregoref6ab412009-10-27 06:26:26 +00005443 /// \brief Sets the "base" location and entity when that
5444 /// information is known based on another transformation.
5445 void setBase(SourceLocation Loc, DeclarationName Entity) {
5446 this->Loc = Loc;
5447 this->Entity = Entity;
5448 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00005449 };
5450}
5451
Douglas Gregor15acfb92009-08-06 16:20:37 +00005452/// \brief Rebuilds a type within the context of the current instantiation.
5453///
Mike Stump11289f42009-09-09 15:08:12 +00005454/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005455/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005456/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005457/// partial specialization thereof). This routine will rebuild that type now
5458/// that we have entered the declarator's scope, which may produce different
5459/// canonical types, e.g.,
5460///
5461/// \code
5462/// template<typename T>
5463/// struct X {
5464/// typedef T* pointer;
5465/// pointer data();
5466/// };
5467///
5468/// template<typename T>
5469/// typename X<T>::pointer X<T>::data() { ... }
5470/// \endcode
5471///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005472/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005473/// since we do not know that we can look into X<T> when we parsed the type.
5474/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005475/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005476/// as the canonical type of T*, allowing the return types of the out-of-line
5477/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005478TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5479 SourceLocation Loc,
5480 DeclarationName Name) {
5481 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005482 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005483
Douglas Gregor15acfb92009-08-06 16:20:37 +00005484 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5485 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005486}
Douglas Gregorbe999392009-09-15 16:23:51 +00005487
John McCalldadc5752010-08-24 06:29:42 +00005488ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00005489 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5490 DeclarationName());
5491 return Rebuilder.TransformExpr(E);
5492}
5493
John McCall99b2fe52010-04-29 23:50:39 +00005494bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5495 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005496
5497 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5498 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5499 DeclarationName());
5500 NestedNameSpecifier *Rebuilt =
5501 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005502 if (!Rebuilt) return true;
5503
5504 SS.setScopeRep(Rebuilt);
5505 return false;
John McCall2408e322010-04-27 00:57:59 +00005506}
5507
Douglas Gregorbe999392009-09-15 16:23:51 +00005508/// \brief Produces a formatted string that describes the binding of
5509/// template parameters to template arguments.
5510std::string
5511Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5512 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005513 // FIXME: For variadic templates, we'll need to get the structured list.
5514 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5515 Args.flat_size());
5516}
5517
5518std::string
5519Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5520 const TemplateArgument *Args,
5521 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005522 std::string Result;
5523
Douglas Gregore62e6a02009-11-11 19:13:48 +00005524 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005525 return Result;
5526
5527 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005528 if (I >= NumArgs)
5529 break;
5530
Douglas Gregorbe999392009-09-15 16:23:51 +00005531 if (I == 0)
5532 Result += "[with ";
5533 else
5534 Result += ", ";
5535
5536 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5537 Result += Id->getName();
5538 } else {
5539 Result += '$';
5540 Result += llvm::utostr(I);
5541 }
5542
5543 Result += " = ";
5544
5545 switch (Args[I].getKind()) {
5546 case TemplateArgument::Null:
5547 Result += "<no value>";
5548 break;
5549
5550 case TemplateArgument::Type: {
5551 std::string TypeStr;
5552 Args[I].getAsType().getAsStringInternal(TypeStr,
5553 Context.PrintingPolicy);
5554 Result += TypeStr;
5555 break;
5556 }
5557
5558 case TemplateArgument::Declaration: {
5559 bool Unnamed = true;
5560 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5561 if (ND->getDeclName()) {
5562 Unnamed = false;
5563 Result += ND->getNameAsString();
5564 }
5565 }
5566
5567 if (Unnamed) {
5568 Result += "<anonymous>";
5569 }
5570 break;
5571 }
5572
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005573 case TemplateArgument::Template: {
5574 std::string Str;
5575 llvm::raw_string_ostream OS(Str);
5576 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5577 Result += OS.str();
5578 break;
5579 }
5580
Douglas Gregorbe999392009-09-15 16:23:51 +00005581 case TemplateArgument::Integral: {
5582 Result += Args[I].getAsIntegral()->toString(10);
5583 break;
5584 }
5585
5586 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005587 // FIXME: This is non-optimal, since we're regurgitating the
5588 // expression we were given.
5589 std::string Str;
5590 {
5591 llvm::raw_string_ostream OS(Str);
5592 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5593 Context.PrintingPolicy);
5594 }
5595 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005596 break;
5597 }
5598
5599 case TemplateArgument::Pack:
5600 // FIXME: Format template argument packs
5601 Result += "<template argument pack>";
5602 break;
5603 }
5604 }
5605
5606 Result += ']';
5607 return Result;
5608}