blob: 2cbf3073a4679e920c6faab52f9c90055856b285 [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
John McCall83024632010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000013#include "clang/Sema/Lookup.h"
John McCallcc14d1f2010-08-24 08:50:51 +000014#include "clang/Sema/Scope.h"
John McCallde6836a2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000016#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000017#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000019#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000020#include "clang/AST/ExprCXX.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000021#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000022#include "clang/AST/DeclTemplate.h"
John McCall8b0666c2010-08-20 18:27:03 +000023#include "clang/Sema/DeclSpec.h"
24#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000025#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000026#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000027#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000028using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000029using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000030
Douglas Gregorb7bfe792009-09-02 22:59:36 +000031/// \brief Determine whether the declaration found is acceptable as the name
32/// of a template and, if so, return that template declaration. Otherwise,
33/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000034static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
35 NamedDecl *Orig) {
36 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000037
Douglas Gregorb7bfe792009-09-02 22:59:36 +000038 if (isa<TemplateDecl>(D))
John McCalle9cccd82010-06-16 08:42:20 +000039 return Orig;
Mike Stump11289f42009-09-09 15:08:12 +000040
Douglas Gregorb7bfe792009-09-02 22:59:36 +000041 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
42 // C++ [temp.local]p1:
43 // Like normal (non-template) classes, class templates have an
44 // injected-class-name (Clause 9). The injected-class-name
45 // can be used with or without a template-argument-list. When
46 // it is used without a template-argument-list, it is
47 // equivalent to the injected-class-name followed by the
48 // template-parameters of the class template enclosed in
49 // <>. When it is used with a template-argument-list, it
50 // refers to the specified class template specialization,
51 // which could be the current specialization or another
52 // specialization.
53 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000054 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000055 if (Record->getDescribedClassTemplate())
56 return Record->getDescribedClassTemplate();
57
58 if (ClassTemplateSpecializationDecl *Spec
59 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
60 return Spec->getSpecializedTemplate();
61 }
Mike Stump11289f42009-09-09 15:08:12 +000062
Douglas Gregorb7bfe792009-09-02 22:59:36 +000063 return 0;
64 }
Mike Stump11289f42009-09-09 15:08:12 +000065
Douglas Gregorb7bfe792009-09-02 22:59:36 +000066 return 0;
67}
68
John McCalle66edc12009-11-24 19:00:30 +000069static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor41f90302010-04-12 20:54:26 +000070 // The set of class templates we've already seen.
71 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000072 LookupResult::Filter filter = R.makeFilter();
73 while (filter.hasNext()) {
74 NamedDecl *Orig = filter.next();
John McCalle9cccd82010-06-16 08:42:20 +000075 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
John McCalle66edc12009-11-24 19:00:30 +000076 if (!Repl)
77 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +000078 else if (Repl != Orig) {
79
80 // C++ [temp.local]p3:
81 // A lookup that finds an injected-class-name (10.2) can result in an
82 // ambiguity in certain cases (for example, if it is found in more than
83 // one base class). If all of the injected-class-names that are found
84 // refer to specializations of the same class template, and if the name
85 // is followed by a template-argument-list, the reference refers to the
86 // class template itself and not a specialization thereof, and is not
87 // ambiguous.
88 //
89 // FIXME: Will we eventually have to do the same for alias templates?
90 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
91 if (!ClassTemplates.insert(ClassTmpl)) {
92 filter.erase();
93 continue;
94 }
John McCallbd8062d2010-08-13 07:02:08 +000095
96 // FIXME: we promote access to public here as a workaround to
97 // the fact that LookupResult doesn't let us remember that we
98 // found this template through a particular injected class name,
99 // which means we end up doing nasty things to the invariants.
100 // Pretending that access is public is *much* safer.
101 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000102 }
John McCalle66edc12009-11-24 19:00:30 +0000103 }
104 filter.done();
105}
106
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000107TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000108 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000109 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000110 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000111 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000112 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000113 TemplateTy &TemplateResult,
114 bool &MemberOfUnknownSpecialization) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000115 assert(getLangOptions().CPlusPlus && "No template names in C!");
116
Douglas Gregor3cf81312009-11-03 23:16:33 +0000117 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000118 MemberOfUnknownSpecialization = false;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000119
120 switch (Name.getKind()) {
121 case UnqualifiedId::IK_Identifier:
122 TName = DeclarationName(Name.Identifier);
123 break;
124
125 case UnqualifiedId::IK_OperatorFunctionId:
126 TName = Context.DeclarationNames.getCXXOperatorName(
127 Name.OperatorFunctionId.Operator);
128 break;
129
Alexis Hunted0530f2009-11-28 08:58:14 +0000130 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000131 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
132 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000133
Douglas Gregor3cf81312009-11-03 23:16:33 +0000134 default:
135 return TNK_Non_template;
136 }
Mike Stump11289f42009-09-09 15:08:12 +0000137
John McCallba7bf592010-08-24 05:47:05 +0000138 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000139
Douglas Gregorff18cc12009-12-31 08:11:17 +0000140 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
141 LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000142 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
143 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000144 if (R.empty()) return TNK_Non_template;
145 if (R.isAmbiguous()) {
146 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000147 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000148
149 // FIXME: we might have ambiguous templates, in which case we
150 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000151 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000152 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000153
John McCalld28ae272009-12-02 08:04:21 +0000154 TemplateName Template;
155 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000156
John McCalld28ae272009-12-02 08:04:21 +0000157 unsigned ResultCount = R.end() - R.begin();
158 if (ResultCount > 1) {
159 // We assume that we'll preserve the qualifier from a function
160 // template name in other ways.
161 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
162 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000163
164 // We'll do this lookup again later.
165 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000166 } else {
John McCalld28ae272009-12-02 08:04:21 +0000167 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
168
169 if (SS.isSet() && !SS.isInvalid()) {
170 NestedNameSpecifier *Qualifier
171 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000172 Template = Context.getQualifiedTemplateName(Qualifier,
173 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000174 } else {
175 Template = TemplateName(TD);
176 }
177
John McCalldcc71402010-08-13 02:23:42 +0000178 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000179 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000180
181 // We'll do this lookup again later.
182 R.suppressDiagnostics();
183 } else {
John McCalld28ae272009-12-02 08:04:21 +0000184 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
185 TemplateKind = TNK_Type_template;
186 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000187 }
Mike Stump11289f42009-09-09 15:08:12 +0000188
John McCalld28ae272009-12-02 08:04:21 +0000189 TemplateResult = TemplateTy::make(Template);
190 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000191}
192
Douglas Gregor18473f32010-01-12 21:28:44 +0000193bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
194 SourceLocation IILoc,
195 Scope *S,
196 const CXXScopeSpec *SS,
197 TemplateTy &SuggestedTemplate,
198 TemplateNameKind &SuggestedKind) {
199 // We can't recover unless there's a dependent scope specifier preceding the
200 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000201 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000202 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
203 computeDeclContext(*SS))
204 return false;
205
206 // The code is missing a 'template' keyword prior to the dependent template
207 // name.
208 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
209 Diag(IILoc, diag::err_template_kw_missing)
210 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000211 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor18473f32010-01-12 21:28:44 +0000212 SuggestedTemplate
213 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
214 SuggestedKind = TNK_Dependent_template_name;
215 return true;
216}
217
John McCalle66edc12009-11-24 19:00:30 +0000218void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000219 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000220 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000221 bool EnteringContext,
222 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000223 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000224 MemberOfUnknownSpecialization = false;
John McCalle66edc12009-11-24 19:00:30 +0000225 DeclContext *LookupCtx = 0;
226 bool isDependent = false;
227 if (!ObjectType.isNull()) {
228 // This nested-name-specifier occurs in a member access expression, e.g.,
229 // x->B::f, and we are looking into the type of the object.
230 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
231 LookupCtx = computeDeclContext(ObjectType);
232 isDependent = ObjectType->isDependentType();
233 assert((isDependent || !ObjectType->isIncompleteType()) &&
234 "Caller should have completed object type");
235 } else if (SS.isSet()) {
236 // This nested-name-specifier occurs after another nested-name-specifier,
237 // so long into the context associated with the prior nested-name-specifier.
238 LookupCtx = computeDeclContext(SS, EnteringContext);
239 isDependent = isDependentScopeSpecifier(SS);
240
241 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000242 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000243 return;
244 }
245
246 bool ObjectTypeSearchedInScope = false;
247 if (LookupCtx) {
248 // Perform "qualified" name lookup into the declaration context we
249 // computed, which is either the type of the base of a member access
250 // expression or the declaration context associated with a prior
251 // nested-name-specifier.
252 LookupQualifiedName(Found, LookupCtx);
253
254 if (!ObjectType.isNull() && Found.empty()) {
255 // C++ [basic.lookup.classref]p1:
256 // In a class member access expression (5.2.5), if the . or -> token is
257 // immediately followed by an identifier followed by a <, the
258 // identifier must be looked up to determine whether the < is the
259 // beginning of a template argument list (14.2) or a less-than operator.
260 // The identifier is first looked up in the class of the object
261 // expression. If the identifier is not found, it is then looked up in
262 // the context of the entire postfix-expression and shall name a class
263 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000264 if (S) LookupName(Found, S);
265 ObjectTypeSearchedInScope = true;
266 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000267 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000268 // We cannot look into a dependent object type or nested nme
269 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000270 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000271 return;
272 } else {
273 // Perform unqualified name lookup in the current scope.
274 LookupName(Found, S);
275 }
276
Douglas Gregorc119dd52010-01-12 17:06:20 +0000277 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000278 // If we did not find any names, attempt to correct any typos.
279 DeclarationName Name = Found.getLookupName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000280 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregorc048c522010-06-29 19:27:42 +0000281 false, CTC_CXXCasts)) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000282 FilterAcceptableTemplateNames(Context, Found);
John McCalle9cccd82010-06-16 08:42:20 +0000283 if (!Found.empty()) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000284 if (LookupCtx)
285 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
286 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000287 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000288 Found.getLookupName().getAsString());
289 else
290 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
291 << Name << Found.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +0000292 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000293 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000294 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
295 Diag(Template->getLocation(), diag::note_previous_decl)
296 << Template->getDeclName();
John McCalle9cccd82010-06-16 08:42:20 +0000297 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000298 } else {
299 Found.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +0000300 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000301 }
302 }
303
John McCalle66edc12009-11-24 19:00:30 +0000304 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000305 if (Found.empty()) {
306 if (isDependent)
307 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000308 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000309 }
John McCalle66edc12009-11-24 19:00:30 +0000310
311 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
312 // C++ [basic.lookup.classref]p1:
313 // [...] If the lookup in the class of the object expression finds a
314 // template, the name is also looked up in the context of the entire
315 // postfix-expression and [...]
316 //
317 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
318 LookupOrdinaryName);
319 LookupName(FoundOuter, S);
320 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor41f90302010-04-12 20:54:26 +0000321
John McCalle66edc12009-11-24 19:00:30 +0000322 if (FoundOuter.empty()) {
323 // - if the name is not found, the name found in the class of the
324 // object expression is used, otherwise
325 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
326 // - if the name is found in the context of the entire
327 // postfix-expression and does not name a class template, the name
328 // found in the class of the object expression is used, otherwise
John McCalle9cccd82010-06-16 08:42:20 +0000329 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000330 // - if the name found is a class template, it must refer to the same
331 // entity as the one found in the class of the object expression,
332 // otherwise the program is ill-formed.
333 if (!Found.isSingleResult() ||
334 Found.getFoundDecl()->getCanonicalDecl()
335 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
336 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000337 diag::ext_nested_name_member_ref_lookup_ambiguous)
338 << Found.getLookupName()
339 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000340 Diag(Found.getRepresentativeDecl()->getLocation(),
341 diag::note_ambig_member_ref_object_type)
342 << ObjectType;
343 Diag(FoundOuter.getFoundDecl()->getLocation(),
344 diag::note_ambig_member_ref_scope);
345
346 // Recover by taking the template that we found in the object
347 // expression's type.
348 }
349 }
350 }
351}
352
John McCallcd4b4772009-12-02 03:53:29 +0000353/// ActOnDependentIdExpression - Handle a dependent id-expression that
354/// was just parsed. This is only possible with an explicit scope
355/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000356ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000357Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000358 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000359 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000360 const TemplateArgumentListInfo *TemplateArgs) {
361 NestedNameSpecifier *Qualifier
362 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall87fe5d52010-05-20 01:18:31 +0000363
364 DeclContext *DC = getFunctionLevelDeclContext();
John McCalle66edc12009-11-24 19:00:30 +0000365
John McCallcd4b4772009-12-02 03:53:29 +0000366 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000367 isa<CXXMethodDecl>(DC) &&
368 cast<CXXMethodDecl>(DC)->isInstance()) {
369 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCallcd4b4772009-12-02 03:53:29 +0000370
John McCalle66edc12009-11-24 19:00:30 +0000371 // Since the 'this' expression is synthesized, we don't need to
372 // perform the double-lookup check.
373 NamedDecl *FirstQualifierInScope = 0;
374
John McCall2d74de92009-12-01 22:10:20 +0000375 return Owned(CXXDependentScopeMemberExpr::Create(Context,
376 /*This*/ 0, ThisType,
377 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000378 /*Op*/ SourceLocation(),
379 Qualifier, SS.getRange(),
380 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000381 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000382 TemplateArgs));
383 }
384
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000385 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000386}
387
John McCalldadc5752010-08-24 06:29:42 +0000388ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000389Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000390 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000391 const TemplateArgumentListInfo *TemplateArgs) {
392 return Owned(DependentScopeDeclRefExpr::Create(Context,
393 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
394 SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000395 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000396 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000397}
398
Douglas Gregor5101c242008-12-05 18:15:24 +0000399/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
400/// that the template parameter 'PrevDecl' is being shadowed by a new
401/// declaration at location Loc. Returns true to indicate that this is
402/// an error, and false otherwise.
403bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000404 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000405
406 // Microsoft Visual C++ permits template parameters to be shadowed.
407 if (getLangOptions().Microsoft)
408 return false;
409
410 // C++ [temp.local]p4:
411 // A template-parameter shall not be redeclared within its
412 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000413 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000414 << cast<NamedDecl>(PrevDecl)->getDeclName();
415 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
416 return true;
417}
418
Douglas Gregor463421d2009-03-03 04:44:36 +0000419/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000420/// the parameter D to reference the templated declaration and return a pointer
421/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000422TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
423 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
424 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000425 return Temp;
426 }
427 return 0;
428}
429
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000430static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
431 const ParsedTemplateArgument &Arg) {
432
433 switch (Arg.getKind()) {
434 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000435 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000436 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
437 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000438 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000439 return TemplateArgumentLoc(TemplateArgument(T), DI);
440 }
441
442 case ParsedTemplateArgument::NonType: {
443 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
444 return TemplateArgumentLoc(TemplateArgument(E), E);
445 }
446
447 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000448 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000449 return TemplateArgumentLoc(TemplateArgument(Template),
450 Arg.getScopeSpec().getRange(),
451 Arg.getLocation());
452 }
453 }
454
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000455 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000456 return TemplateArgumentLoc();
457}
458
459/// \brief Translates template arguments as provided by the parser
460/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000461void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
462 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000463 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000464 TemplateArgs.addArgument(translateTemplateArgument(*this,
465 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000466}
467
Douglas Gregor5101c242008-12-05 18:15:24 +0000468/// ActOnTypeParameter - Called when a C++ template type parameter
469/// (e.g., "typename T") has been parsed. Typename specifies whether
470/// the keyword "typename" was used to declare the type parameter
471/// (otherwise, "class" was used), and KeyLoc is the location of the
472/// "class" or "typename" keyword. ParamName is the name of the
473/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregor2ebcae12010-06-16 15:23:05 +0000474/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000475/// If the type parameter has a default argument, it will be added
476/// later via ActOnTypeParameterDefault.
John McCall48871652010-08-21 09:40:31 +0000477Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
478 SourceLocation EllipsisLoc,
479 SourceLocation KeyLoc,
480 IdentifierInfo *ParamName,
481 SourceLocation ParamNameLoc,
482 unsigned Depth, unsigned Position,
483 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000484 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000485 assert(S->isTemplateParamScope() &&
486 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000487 bool Invalid = false;
488
489 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000490 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000491 LookupOrdinaryName,
492 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000493 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000494 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000495 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000496 }
497
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000498 SourceLocation Loc = ParamNameLoc;
499 if (!ParamName)
500 Loc = KeyLoc;
501
Douglas Gregor5101c242008-12-05 18:15:24 +0000502 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000503 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
504 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000505 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000506 if (Invalid)
507 Param->setInvalidDecl();
508
509 if (ParamName) {
510 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000511 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000512 IdResolver.AddDecl(Param);
513 }
514
Douglas Gregordc13ded2010-07-01 00:00:45 +0000515 // Handle the default argument, if provided.
516 if (DefaultArg) {
517 TypeSourceInfo *DefaultTInfo;
518 GetTypeFromParser(DefaultArg, &DefaultTInfo);
519
520 assert(DefaultTInfo && "expected source information for type");
521
522 // C++0x [temp.param]p9:
523 // A default template-argument may be specified for any kind of
524 // template-parameter that is not a template parameter pack.
525 if (Ellipsis) {
526 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
John McCall48871652010-08-21 09:40:31 +0000527 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000528 }
529
530 // Check the template argument itself.
531 if (CheckTemplateArgument(Param, DefaultTInfo)) {
532 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000533 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000534 }
535
536 Param->setDefaultArgument(DefaultTInfo, false);
537 }
538
John McCall48871652010-08-21 09:40:31 +0000539 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000540}
541
Douglas Gregor463421d2009-03-03 04:44:36 +0000542/// \brief Check that the type of a non-type template parameter is
543/// well-formed.
544///
545/// \returns the (possibly-promoted) parameter type if valid;
546/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000547QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000548Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000549 // We don't allow variably-modified types as the type of non-type template
550 // parameters.
551 if (T->isVariablyModifiedType()) {
552 Diag(Loc, diag::err_variably_modified_nontype_template_param)
553 << T;
554 return QualType();
555 }
556
Douglas Gregor463421d2009-03-03 04:44:36 +0000557 // C++ [temp.param]p4:
558 //
559 // A non-type template-parameter shall have one of the following
560 // (optionally cv-qualified) types:
561 //
562 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000563 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000564 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000565 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000566 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000567 T->isReferenceType() ||
568 // -- pointer to member.
569 T->isMemberPointerType() ||
570 // If T is a dependent type, we can't do the check now, so we
571 // assume that it is well-formed.
572 T->isDependentType())
573 return T;
574 // C++ [temp.param]p8:
575 //
576 // A non-type template-parameter of type "array of T" or
577 // "function returning T" is adjusted to be of type "pointer to
578 // T" or "pointer to function returning T", respectively.
579 else if (T->isArrayType())
580 // FIXME: Keep the type prior to promotion?
581 return Context.getArrayDecayedType(T);
582 else if (T->isFunctionType())
583 // FIXME: Keep the type prior to promotion?
584 return Context.getPointerType(T);
Douglas Gregor959d5a02010-05-22 16:17:30 +0000585
Douglas Gregor463421d2009-03-03 04:44:36 +0000586 Diag(Loc, diag::err_template_nontype_parm_bad_type)
587 << T;
588
589 return QualType();
590}
591
John McCall48871652010-08-21 09:40:31 +0000592Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
593 unsigned Depth,
594 unsigned Position,
595 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000596 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000597 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
598 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000599
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000600 assert(S->isTemplateParamScope() &&
601 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000602 bool Invalid = false;
603
604 IdentifierInfo *ParamName = D.getIdentifier();
605 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000606 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000607 LookupOrdinaryName,
608 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000609 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000610 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000611 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000612 }
613
Douglas Gregor463421d2009-03-03 04:44:36 +0000614 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000615 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000616 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000617 Invalid = true;
618 }
Douglas Gregor81338792009-02-10 17:43:50 +0000619
Douglas Gregor5101c242008-12-05 18:15:24 +0000620 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000621 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
622 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000623 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000624 if (Invalid)
625 Param->setInvalidDecl();
626
627 if (D.getIdentifier()) {
628 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000629 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000630 IdResolver.AddDecl(Param);
631 }
Douglas Gregordc13ded2010-07-01 00:00:45 +0000632
633 // Check the well-formedness of the default template argument, if provided.
John McCallb268a282010-08-23 23:25:46 +0000634 if (Default) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000635 TemplateArgument Converted;
636 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
637 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000638 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000639 }
640
John McCallb268a282010-08-23 23:25:46 +0000641 Param->setDefaultArgument(Default, false);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000642 }
643
John McCall48871652010-08-21 09:40:31 +0000644 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000645}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000646
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000647/// ActOnTemplateTemplateParameter - Called when a C++ template template
648/// parameter (e.g. T in template <template <typename> class T> class array)
649/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000650Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
651 SourceLocation TmpLoc,
652 TemplateParamsTy *Params,
653 IdentifierInfo *Name,
654 SourceLocation NameLoc,
655 unsigned Depth,
656 unsigned Position,
657 SourceLocation EqualLoc,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000658 const ParsedTemplateArgument &Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000659 assert(S->isTemplateParamScope() &&
660 "Template template parameter not in template parameter scope!");
661
662 // Construct the parameter object.
663 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000664 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
665 TmpLoc, Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000666 (TemplateParameterList*)Params);
667
Douglas Gregordc13ded2010-07-01 00:00:45 +0000668 // If the template template parameter has a name, then link the identifier
669 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000670 if (Name) {
John McCall48871652010-08-21 09:40:31 +0000671 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000672 IdResolver.AddDecl(Param);
673 }
674
Douglas Gregordc13ded2010-07-01 00:00:45 +0000675 if (!Default.isInvalid()) {
676 // Check only that we have a template template argument. We don't want to
677 // try to check well-formedness now, because our template template parameter
678 // might have dependent types in its template parameters, which we wouldn't
679 // be able to match now.
680 //
681 // If none of the template template parameter's template arguments mention
682 // other template parameters, we could actually perform more checking here.
683 // However, it isn't worth doing.
684 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
685 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
686 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
687 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000688 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000689 }
690
691 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000692 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000693
John McCall48871652010-08-21 09:40:31 +0000694 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000695}
696
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000697/// ActOnTemplateParameterList - Builds a TemplateParameterList that
698/// contains the template parameters in Params/NumParams.
699Sema::TemplateParamsTy *
700Sema::ActOnTemplateParameterList(unsigned Depth,
701 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000702 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000703 SourceLocation LAngleLoc,
John McCall48871652010-08-21 09:40:31 +0000704 Decl **Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000705 SourceLocation RAngleLoc) {
706 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000707 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000708
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000709 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000710 (NamedDecl**)Params, NumParams,
711 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000712}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000713
John McCall3e11ebe2010-03-15 10:12:16 +0000714static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
715 if (SS.isSet())
716 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
717 SS.getRange());
718}
719
John McCallfaf5fb42010-08-26 23:41:50 +0000720DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000721Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000722 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000723 IdentifierInfo *Name, SourceLocation NameLoc,
724 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000725 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000726 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000727 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000728 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000729 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000730 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000731
732 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000733 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000734 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000735
Abramo Bagnara6150c882010-05-11 21:36:43 +0000736 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
737 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000738
739 // There is no such thing as an unnamed class template.
740 if (!Name) {
741 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000742 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000743 }
744
745 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000746 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000747 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000748 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000749 if (SS.isNotEmpty() && !SS.isInvalid()) {
750 SemanticContext = computeDeclContext(SS, true);
751 if (!SemanticContext) {
752 // FIXME: Produce a reasonable diagnostic here
753 return true;
754 }
Mike Stump11289f42009-09-09 15:08:12 +0000755
John McCall0b66eb32010-05-01 00:40:08 +0000756 if (RequireCompleteDeclContext(SS, SemanticContext))
757 return true;
758
John McCall27b18f82009-11-17 02:14:36 +0000759 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000760 } else {
761 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000762 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000763 }
Mike Stump11289f42009-09-09 15:08:12 +0000764
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000765 if (Previous.isAmbiguous())
766 return true;
767
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000768 NamedDecl *PrevDecl = 0;
769 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000770 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000771
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000772 // If there is a previous declaration with the same name, check
773 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000774 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000775 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000776
777 // We may have found the injected-class-name of a class template,
778 // class template partial specialization, or class template specialization.
779 // In these cases, grab the template that is being defined or specialized.
780 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
781 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
782 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
783 PrevClassTemplate
784 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
785 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
786 PrevClassTemplate
787 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
788 ->getSpecializedTemplate();
789 }
790 }
791
John McCalld43784f2009-12-18 11:25:59 +0000792 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000793 // C++ [namespace.memdef]p3:
794 // [...] When looking for a prior declaration of a class or a function
795 // declared as a friend, and when the name of the friend class or
796 // function is neither a qualified name nor a template-id, scopes outside
797 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000798 if (!SS.isSet()) {
799 DeclContext *OutermostContext = CurContext;
800 while (!OutermostContext->isFileContext())
801 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000802
Douglas Gregorb74b1032010-04-18 17:37:40 +0000803 if (PrevDecl &&
804 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
805 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
806 SemanticContext = PrevDecl->getDeclContext();
807 } else {
808 // Declarations in outer scopes don't matter. However, the outermost
809 // context we computed is the semantic context for our new
810 // declaration.
811 PrevDecl = PrevClassTemplate = 0;
812 SemanticContext = OutermostContext;
813 }
John McCall90d3bb92009-12-17 23:21:11 +0000814 }
Douglas Gregorb74b1032010-04-18 17:37:40 +0000815
John McCall90d3bb92009-12-17 23:21:11 +0000816 if (CurContext->isDependentContext()) {
817 // If this is a dependent context, we don't want to link the friend
818 // class template to the template in scope, because that would perform
819 // checking of the template parameter lists that can't be performed
820 // until the outer context is instantiated.
821 PrevDecl = PrevClassTemplate = 0;
822 }
823 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
824 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000825
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000826 if (PrevClassTemplate) {
827 // Ensure that the template parameter lists are compatible.
828 if (!TemplateParameterListsAreEqual(TemplateParams,
829 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000830 /*Complain=*/true,
831 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000832 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000833
834 // C++ [temp.class]p4:
835 // In a redeclaration, partial specialization, explicit
836 // specialization or explicit instantiation of a class template,
837 // the class-key shall agree in kind with the original class
838 // template declaration (7.1.5.3).
839 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000840 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000841 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000842 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000843 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000844 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000845 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000846 }
847
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000848 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000849 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000850 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000851 Diag(NameLoc, diag::err_redefinition) << Name;
852 Diag(Def->getLocation(), diag::note_previous_definition);
853 // FIXME: Would it make sense to try to "forget" the previous
854 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000855 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000856 }
857 }
858 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
859 // Maybe we will complain about the shadowed template parameter.
860 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
861 // Just pretend that we didn't see the previous declaration.
862 PrevDecl = 0;
863 } else if (PrevDecl) {
864 // C++ [temp]p5:
865 // A class template shall not have the same name as any other
866 // template, class, function, object, enumeration, enumerator,
867 // namespace, or type in the same scope (3.3), except as specified
868 // in (14.5.4).
869 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
870 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000871 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000872 }
873
Douglas Gregordba32632009-02-10 19:49:53 +0000874 // Check the template parameter list of this declaration, possibly
875 // merging in the template parameter list from the previous class
876 // template declaration.
877 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000878 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
879 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000880 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000881
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000882 if (SS.isSet()) {
883 // If the name of the template was qualified, we must be defining the
884 // template out-of-line.
885 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
886 !(TUK == TUK_Friend && CurContext->isDependentContext()))
887 Diag(NameLoc, diag::err_member_def_does_not_match)
888 << Name << SemanticContext << SS.getRange();
889 }
890
Mike Stump11289f42009-09-09 15:08:12 +0000891 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000892 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000893 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000894 PrevClassTemplate->getTemplatedDecl() : 0,
895 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000896 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000897
898 ClassTemplateDecl *NewTemplate
899 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
900 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000901 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000902 NewClass->setDescribedClassTemplate(NewTemplate);
903
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000904 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000905 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +0000906 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000907 assert(T->isDependentType() && "Class template type is not dependent?");
908 (void)T;
909
Douglas Gregorcf915552009-10-13 16:30:37 +0000910 // If we are providing an explicit specialization of a member that is a
911 // class template, make a note of that.
912 if (PrevClassTemplate &&
913 PrevClassTemplate->getInstantiatedFromMemberTemplate())
914 PrevClassTemplate->setMemberSpecialization();
915
Anders Carlsson137108d2009-03-26 01:24:28 +0000916 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000917 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000918 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000919
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000920 // Set the lexical context of these templates
921 NewClass->setLexicalDeclContext(CurContext);
922 NewTemplate->setLexicalDeclContext(CurContext);
923
John McCall9bb74a52009-07-31 02:45:11 +0000924 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000925 NewClass->startDefinition();
926
927 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000928 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000929
John McCall27b5c252009-09-14 21:59:20 +0000930 if (TUK != TUK_Friend)
931 PushOnScopeChains(NewTemplate, S);
932 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000933 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000934 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000935 NewClass->setAccess(PrevClassTemplate->getAccess());
936 }
John McCall27b5c252009-09-14 21:59:20 +0000937
Douglas Gregor3dad8422009-09-26 06:47:28 +0000938 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
939 PrevClassTemplate != NULL);
940
John McCall27b5c252009-09-14 21:59:20 +0000941 // Friend templates are visible in fairly strange ways.
942 if (!CurContext->isDependentContext()) {
943 DeclContext *DC = SemanticContext->getLookupContext();
944 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
945 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
946 PushOnScopeChains(NewTemplate, EnclosingScope,
947 /* AddToContext = */ false);
948 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000949
950 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
951 NewClass->getLocation(),
952 NewTemplate,
953 /*FIXME:*/NewClass->getLocation());
954 Friend->setAccess(AS_public);
955 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000956 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000957
Douglas Gregordba32632009-02-10 19:49:53 +0000958 if (Invalid) {
959 NewTemplate->setInvalidDecl();
960 NewClass->setInvalidDecl();
961 }
John McCall48871652010-08-21 09:40:31 +0000962 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000963}
964
Douglas Gregored5731f2009-11-25 17:50:39 +0000965/// \brief Diagnose the presence of a default template argument on a
966/// template parameter, which is ill-formed in certain contexts.
967///
968/// \returns true if the default template argument should be dropped.
969static bool DiagnoseDefaultTemplateArgument(Sema &S,
970 Sema::TemplateParamListContext TPC,
971 SourceLocation ParamLoc,
972 SourceRange DefArgRange) {
973 switch (TPC) {
974 case Sema::TPC_ClassTemplate:
975 return false;
976
977 case Sema::TPC_FunctionTemplate:
978 // C++ [temp.param]p9:
979 // A default template-argument shall not be specified in a
980 // function template declaration or a function template
981 // definition [...]
982 // (This sentence is not in C++0x, per DR226).
983 if (!S.getLangOptions().CPlusPlus0x)
984 S.Diag(ParamLoc,
985 diag::err_template_parameter_default_in_function_template)
986 << DefArgRange;
987 return false;
988
989 case Sema::TPC_ClassTemplateMember:
990 // C++0x [temp.param]p9:
991 // A default template-argument shall not be specified in the
992 // template-parameter-lists of the definition of a member of a
993 // class template that appears outside of the member's class.
994 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
995 << DefArgRange;
996 return true;
997
998 case Sema::TPC_FriendFunctionTemplate:
999 // C++ [temp.param]p9:
1000 // A default template-argument shall not be specified in a
1001 // friend template declaration.
1002 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1003 << DefArgRange;
1004 return true;
1005
1006 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1007 // for friend function templates if there is only a single
1008 // declaration (and it is a definition). Strange!
1009 }
1010
1011 return false;
1012}
1013
Douglas Gregordba32632009-02-10 19:49:53 +00001014/// \brief Checks the validity of a template parameter list, possibly
1015/// considering the template parameter list from a previous
1016/// declaration.
1017///
1018/// If an "old" template parameter list is provided, it must be
1019/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1020/// template parameter list.
1021///
1022/// \param NewParams Template parameter list for a new template
1023/// declaration. This template parameter list will be updated with any
1024/// default arguments that are carried through from the previous
1025/// template parameter list.
1026///
1027/// \param OldParams If provided, template parameter list from a
1028/// previous declaration of the same template. Default template
1029/// arguments will be merged from the old template parameter list to
1030/// the new template parameter list.
1031///
Douglas Gregored5731f2009-11-25 17:50:39 +00001032/// \param TPC Describes the context in which we are checking the given
1033/// template parameter list.
1034///
Douglas Gregordba32632009-02-10 19:49:53 +00001035/// \returns true if an error occurred, false otherwise.
1036bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001037 TemplateParameterList *OldParams,
1038 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001039 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001040
Douglas Gregordba32632009-02-10 19:49:53 +00001041 // C++ [temp.param]p10:
1042 // The set of default template-arguments available for use with a
1043 // template declaration or definition is obtained by merging the
1044 // default arguments from the definition (if in scope) and all
1045 // declarations in scope in the same way default function
1046 // arguments are (8.3.6).
1047 bool SawDefaultArgument = false;
1048 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001049
Anders Carlsson327865d2009-06-12 23:20:15 +00001050 bool SawParameterPack = false;
1051 SourceLocation ParameterPackLoc;
1052
Mike Stumpc89c8e32009-02-11 23:03:27 +00001053 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001054 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001055 if (OldParams)
1056 OldParam = OldParams->begin();
1057
1058 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1059 NewParamEnd = NewParams->end();
1060 NewParam != NewParamEnd; ++NewParam) {
1061 // Variables used to diagnose redundant default arguments
1062 bool RedundantDefaultArg = false;
1063 SourceLocation OldDefaultLoc;
1064 SourceLocation NewDefaultLoc;
1065
1066 // Variables used to diagnose missing default arguments
1067 bool MissingDefaultArg = false;
1068
Anders Carlsson327865d2009-06-12 23:20:15 +00001069 // C++0x [temp.param]p11:
1070 // If a template parameter of a class template is a template parameter pack,
1071 // it must be the last template parameter.
1072 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001073 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001074 diag::err_template_param_pack_must_be_last_template_parameter);
1075 Invalid = true;
1076 }
1077
Douglas Gregordba32632009-02-10 19:49:53 +00001078 if (TemplateTypeParmDecl *NewTypeParm
1079 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001080 // Check the presence of a default argument here.
1081 if (NewTypeParm->hasDefaultArgument() &&
1082 DiagnoseDefaultTemplateArgument(*this, TPC,
1083 NewTypeParm->getLocation(),
1084 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001085 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001086 NewTypeParm->removeDefaultArgument();
1087
1088 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001089 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001090 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001091
Anders Carlsson327865d2009-06-12 23:20:15 +00001092 if (NewTypeParm->isParameterPack()) {
1093 assert(!NewTypeParm->hasDefaultArgument() &&
1094 "Parameter packs can't have a default argument!");
1095 SawParameterPack = true;
1096 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001097 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001098 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001099 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1100 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1101 SawDefaultArgument = true;
1102 RedundantDefaultArg = true;
1103 PreviousDefaultArgLoc = NewDefaultLoc;
1104 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1105 // Merge the default argument from the old declaration to the
1106 // new declaration.
1107 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001108 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001109 true);
1110 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1111 } else if (NewTypeParm->hasDefaultArgument()) {
1112 SawDefaultArgument = true;
1113 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1114 } else if (SawDefaultArgument)
1115 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001116 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001117 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001118 // Check the presence of a default argument here.
1119 if (NewNonTypeParm->hasDefaultArgument() &&
1120 DiagnoseDefaultTemplateArgument(*this, TPC,
1121 NewNonTypeParm->getLocation(),
1122 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001123 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001124 }
1125
Mike Stump12b8ce12009-08-04 21:02:39 +00001126 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001127 NonTypeTemplateParmDecl *OldNonTypeParm
1128 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001129 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001130 NewNonTypeParm->hasDefaultArgument()) {
1131 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1132 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1133 SawDefaultArgument = true;
1134 RedundantDefaultArg = true;
1135 PreviousDefaultArgLoc = NewDefaultLoc;
1136 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1137 // Merge the default argument from the old declaration to the
1138 // new declaration.
1139 SawDefaultArgument = true;
1140 // FIXME: We need to create a new kind of "default argument"
1141 // expression that points to a previous template template
1142 // parameter.
1143 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001144 OldNonTypeParm->getDefaultArgument(),
1145 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001146 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1147 } else if (NewNonTypeParm->hasDefaultArgument()) {
1148 SawDefaultArgument = true;
1149 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1150 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001151 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001152 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001153 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001154 TemplateTemplateParmDecl *NewTemplateParm
1155 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001156 if (NewTemplateParm->hasDefaultArgument() &&
1157 DiagnoseDefaultTemplateArgument(*this, TPC,
1158 NewTemplateParm->getLocation(),
1159 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001160 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001161
1162 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001163 TemplateTemplateParmDecl *OldTemplateParm
1164 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001165 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001166 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001167 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1168 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001169 SawDefaultArgument = true;
1170 RedundantDefaultArg = true;
1171 PreviousDefaultArgLoc = NewDefaultLoc;
1172 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1173 // Merge the default argument from the old declaration to the
1174 // new declaration.
1175 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001176 // FIXME: We need to create a new kind of "default argument" expression
1177 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001178 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001179 OldTemplateParm->getDefaultArgument(),
1180 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001181 PreviousDefaultArgLoc
1182 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001183 } else if (NewTemplateParm->hasDefaultArgument()) {
1184 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001185 PreviousDefaultArgLoc
1186 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001187 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001188 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001189 }
1190
1191 if (RedundantDefaultArg) {
1192 // C++ [temp.param]p12:
1193 // A template-parameter shall not be given default arguments
1194 // by two different declarations in the same scope.
1195 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1196 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1197 Invalid = true;
1198 } else if (MissingDefaultArg) {
1199 // C++ [temp.param]p11:
1200 // If a template-parameter has a default template-argument,
1201 // all subsequent template-parameters shall have a default
1202 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001203 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001204 diag::err_template_param_default_arg_missing);
1205 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1206 Invalid = true;
1207 }
1208
1209 // If we have an old template parameter list that we're merging
1210 // in, move on to the next parameter.
1211 if (OldParams)
1212 ++OldParam;
1213 }
1214
1215 return Invalid;
1216}
Douglas Gregord32e0282009-02-09 23:23:08 +00001217
Mike Stump11289f42009-09-09 15:08:12 +00001218/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001219/// specifier, returning the template parameter list that applies to the
1220/// name.
1221///
1222/// \param DeclStartLoc the start of the declaration that has a scope
1223/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001224///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001225/// \param SS the scope specifier that will be matched to the given template
1226/// parameter lists. This scope specifier precedes a qualified name that is
1227/// being declared.
1228///
1229/// \param ParamLists the template parameter lists, from the outermost to the
1230/// innermost template parameter lists.
1231///
1232/// \param NumParamLists the number of template parameter lists in ParamLists.
1233///
John McCalle820e5e2010-04-13 20:37:33 +00001234/// \param IsFriend Whether to apply the slightly different rules for
1235/// matching template parameters to scope specifiers in friend
1236/// declarations.
1237///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001238/// \param IsExplicitSpecialization will be set true if the entity being
1239/// declared is an explicit specialization, false otherwise.
1240///
Mike Stump11289f42009-09-09 15:08:12 +00001241/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001242/// name that is preceded by the scope specifier @p SS. This template
1243/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001244/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001245/// template specialization), or may be NULL (if we were's declaring isn't
1246/// itself a template).
1247TemplateParameterList *
1248Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1249 const CXXScopeSpec &SS,
1250 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001251 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001252 bool IsFriend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001253 bool &IsExplicitSpecialization,
1254 bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001255 IsExplicitSpecialization = false;
1256
Douglas Gregord8d297c2009-07-21 23:53:31 +00001257 // Find the template-ids that occur within the nested-name-specifier. These
1258 // template-ids will match up with the template parameter lists.
1259 llvm::SmallVector<const TemplateSpecializationType *, 4>
1260 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001261 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1262 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001263 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1264 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001265 const Type *T = NNS->getAsType();
1266 if (!T) break;
1267
1268 // C++0x [temp.expl.spec]p17:
1269 // A member or a member template may be nested within many
1270 // enclosing class templates. In an explicit specialization for
1271 // such a member, the member declaration shall be preceded by a
1272 // template<> for each enclosing class template that is
1273 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001274 //
1275 // Following the existing practice of GNU and EDG, we allow a typedef of a
1276 // template specialization type.
1277 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1278 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001279
Mike Stump11289f42009-09-09 15:08:12 +00001280 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001281 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001282 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1283 if (!Template)
1284 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001285
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001286 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001287 ClassTemplateSpecializationDecl *SpecDecl
1288 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1289 // If the nested name specifier refers to an explicit specialization,
1290 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001291 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1292 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001293 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001294 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001295 }
Mike Stump11289f42009-09-09 15:08:12 +00001296
Douglas Gregord8d297c2009-07-21 23:53:31 +00001297 TemplateIdsInSpecifier.push_back(SpecType);
1298 }
1299 }
Mike Stump11289f42009-09-09 15:08:12 +00001300
Douglas Gregord8d297c2009-07-21 23:53:31 +00001301 // Reverse the list of template-ids in the scope specifier, so that we can
1302 // more easily match up the template-ids and the template parameter lists.
1303 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001304
Douglas Gregord8d297c2009-07-21 23:53:31 +00001305 SourceLocation FirstTemplateLoc = DeclStartLoc;
1306 if (NumParamLists)
1307 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001308
Douglas Gregord8d297c2009-07-21 23:53:31 +00001309 // Match the template-ids found in the specifier to the template parameter
1310 // lists.
1311 unsigned Idx = 0;
1312 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1313 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001314 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1315 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001316 if (Idx >= NumParamLists) {
1317 // We have a template-id without a corresponding template parameter
1318 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001319
1320 // ...which is fine if this is a friend declaration.
1321 if (IsFriend) {
1322 IsExplicitSpecialization = true;
1323 break;
1324 }
1325
Douglas Gregord8d297c2009-07-21 23:53:31 +00001326 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001327 // FIXME: the location information here isn't great.
1328 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001329 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001330 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001331 << SS.getRange();
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001332 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001333 } else {
1334 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1335 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001336 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001337 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001338 }
1339 return 0;
1340 }
Mike Stump11289f42009-09-09 15:08:12 +00001341
Douglas Gregord8d297c2009-07-21 23:53:31 +00001342 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001343 if (DependentTemplateId) {
John McCall2408e322010-04-27 00:57:59 +00001344 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00001345
John McCall2408e322010-04-27 00:57:59 +00001346 // Are there cases in (e.g.) friends where this won't match?
1347 if (const InjectedClassNameType *Injected
1348 = TemplateId->getAs<InjectedClassNameType>()) {
1349 CXXRecordDecl *Record = Injected->getDecl();
1350 if (ClassTemplatePartialSpecializationDecl *Partial =
1351 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1352 ExpectedTemplateParams = Partial->getTemplateParameters();
1353 else
1354 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1355 ->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001356 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001357
John McCall2408e322010-04-27 00:57:59 +00001358 if (ExpectedTemplateParams)
1359 TemplateParameterListsAreEqual(ParamLists[Idx],
1360 ExpectedTemplateParams,
1361 true, TPL_TemplateMatch);
1362
Douglas Gregored5731f2009-11-25 17:50:39 +00001363 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001364 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001365 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001366 diag::err_template_param_list_matches_nontemplate)
1367 << TemplateId
1368 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001369 else
1370 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001371 }
Mike Stump11289f42009-09-09 15:08:12 +00001372
Douglas Gregord8d297c2009-07-21 23:53:31 +00001373 // If there were at least as many template-ids as there were template
1374 // parameter lists, then there are no template parameter lists remaining for
1375 // the declaration itself.
Douglas Gregor5be1eb82010-08-20 03:26:10 +00001376 if (Idx >= NumParamLists)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001377 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001378
Douglas Gregord8d297c2009-07-21 23:53:31 +00001379 // If there were too many template parameter lists, complain about that now.
1380 if (Idx != NumParamLists - 1) {
1381 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001382 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001383 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001384 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1385 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001386 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1387 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001388
1389 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1390 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1391 diag::note_explicit_template_spec_does_not_need_header)
1392 << ExplicitSpecializationsInSpecifier.back();
1393 ExplicitSpecializationsInSpecifier.pop_back();
1394 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001395
1396 // We have a template parameter list with no corresponding scope, which
1397 // means that the resulting template declaration can't be instantiated
1398 // properly (we'll end up with dependent nodes when we shouldn't).
1399 if (!isExplicitSpecHeader)
1400 Invalid = true;
1401
Douglas Gregord8d297c2009-07-21 23:53:31 +00001402 ++Idx;
1403 }
1404 }
Mike Stump11289f42009-09-09 15:08:12 +00001405
Douglas Gregord8d297c2009-07-21 23:53:31 +00001406 // Return the last template parameter list, which corresponds to the
1407 // entity being declared.
1408 return ParamLists[NumParamLists - 1];
1409}
1410
Douglas Gregordc572a32009-03-30 22:58:21 +00001411QualType Sema::CheckTemplateIdType(TemplateName Name,
1412 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001413 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001414 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001415 if (!Template) {
1416 // The template name does not resolve to a template, so we just
1417 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001418 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001419 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001420
Douglas Gregorc40290e2009-03-09 23:48:35 +00001421 // Check that the template argument list is well-formed for this
1422 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001423 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001424 TemplateArgs.size());
1425 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001426 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001427 return QualType();
1428
Mike Stump11289f42009-09-09 15:08:12 +00001429 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001430 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001431 "Converted template argument list is too short!");
1432
1433 QualType CanonType;
1434
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001435 if (Name.isDependent() ||
1436 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001437 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001438 // This class template specialization is a dependent
1439 // type. Therefore, its canonical type is another class template
1440 // specialization type that contains all of the converted
1441 // arguments in canonical form. This ensures that, e.g., A<T> and
1442 // A<T, T> have identical types when A is declared as:
1443 //
1444 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001445 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001446 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001447 Converted.getFlatArguments(),
1448 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001449
Douglas Gregora8e02e72009-07-28 23:00:59 +00001450 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001451 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001452 // In the future, we need to teach getTemplateSpecializationType to only
1453 // build the canonical type and return that to us.
1454 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001455
1456 // This might work out to be a current instantiation, in which
1457 // case the canonical type needs to be the InjectedClassNameType.
1458 //
1459 // TODO: in theory this could be a simple hashtable lookup; most
1460 // changes to CurContext don't change the set of current
1461 // instantiations.
1462 if (isa<ClassTemplateDecl>(Template)) {
1463 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1464 // If we get out to a namespace, we're done.
1465 if (Ctx->isFileContext()) break;
1466
1467 // If this isn't a record, keep looking.
1468 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1469 if (!Record) continue;
1470
1471 // Look for one of the two cases with InjectedClassNameTypes
1472 // and check whether it's the same template.
1473 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1474 !Record->getDescribedClassTemplate())
1475 continue;
1476
1477 // Fetch the injected class name type and check whether its
1478 // injected type is equal to the type we just built.
1479 QualType ICNT = Context.getTypeDeclType(Record);
1480 QualType Injected = cast<InjectedClassNameType>(ICNT)
1481 ->getInjectedSpecializationType();
1482
1483 if (CanonType != Injected->getCanonicalTypeInternal())
1484 continue;
1485
1486 // If so, the canonical type of this TST is the injected
1487 // class name type of the record we just found.
1488 assert(ICNT.isCanonical());
1489 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00001490 break;
1491 }
1492 }
Mike Stump11289f42009-09-09 15:08:12 +00001493 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001494 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001495 // Find the class template specialization declaration that
1496 // corresponds to these arguments.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001497 void *InsertPos = 0;
1498 ClassTemplateSpecializationDecl *Decl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001499 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
1500 Converted.flatSize(), InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001501 if (!Decl) {
1502 // This is the first time we have referenced this class template
1503 // specialization. Create the canonical declaration and add it to
1504 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001505 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001506 ClassTemplate->getTemplatedDecl()->getTagKind(),
1507 ClassTemplate->getDeclContext(),
1508 ClassTemplate->getLocation(),
1509 ClassTemplate,
1510 Converted, 0);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001511 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001512 Decl->setLexicalDeclContext(CurContext);
1513 }
1514
1515 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001516 assert(isa<RecordType>(CanonType) &&
1517 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001518 }
Mike Stump11289f42009-09-09 15:08:12 +00001519
Douglas Gregorc40290e2009-03-09 23:48:35 +00001520 // Build the fully-sugared type for this class template
1521 // specialization, which refers back to the class template
1522 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00001523 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001524}
1525
John McCallfaf5fb42010-08-26 23:41:50 +00001526TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001527Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001528 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001529 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001530 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001531 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001532
Douglas Gregorc40290e2009-03-09 23:48:35 +00001533 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001534 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001535 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001536
John McCall6b51f282009-11-23 01:53:49 +00001537 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001538 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001539
1540 if (Result.isNull())
1541 return true;
1542
John McCallbcd03502009-12-07 02:54:59 +00001543 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001544 TemplateSpecializationTypeLoc TL
1545 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1546 TL.setTemplateNameLoc(TemplateLoc);
1547 TL.setLAngleLoc(LAngleLoc);
1548 TL.setRAngleLoc(RAngleLoc);
1549 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1550 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1551
John McCallba7bf592010-08-24 05:47:05 +00001552 return CreateParsedType(Result, DI);
John McCalld8fe9af2009-09-08 17:47:29 +00001553}
John McCall06f6fe8d2009-09-04 01:14:41 +00001554
John McCallfaf5fb42010-08-26 23:41:50 +00001555TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1556 TagUseKind TUK,
1557 TypeSpecifierType TagSpec,
1558 SourceLocation TagLoc) {
John McCalld8fe9af2009-09-08 17:47:29 +00001559 if (TypeResult.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00001560 return ::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001561
John McCall0ad16662009-10-29 08:12:44 +00001562 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001563 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001564 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001565
John McCalld8fe9af2009-09-08 17:47:29 +00001566 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001567 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001568
John McCalld8fe9af2009-09-08 17:47:29 +00001569 if (const RecordType *RT = Type->getAs<RecordType>()) {
1570 RecordDecl *D = RT->getDecl();
1571
1572 IdentifierInfo *Id = D->getIdentifier();
1573 assert(Id && "templated class must have an identifier");
1574
1575 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1576 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001577 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001578 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001579 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001580 }
1581 }
1582
Abramo Bagnara6150c882010-05-11 21:36:43 +00001583 ElaboratedTypeKeyword Keyword
1584 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1585 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001586
John McCallba7bf592010-08-24 05:47:05 +00001587 return ParsedType::make(ElabType);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001588}
1589
John McCalldadc5752010-08-24 06:29:42 +00001590ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001591 LookupResult &R,
1592 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001593 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001594 // FIXME: Can we do any checking at this point? I guess we could check the
1595 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001596 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001597 // though.
John McCalle66edc12009-11-24 19:00:30 +00001598
1599 // These should be filtered out by our callers.
1600 assert(!R.empty() && "empty lookup results when building templateid");
1601 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1602
1603 NestedNameSpecifier *Qualifier = 0;
1604 SourceRange QualifierRange;
1605 if (SS.isSet()) {
1606 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1607 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001608 }
John McCall58cc69d2010-01-27 01:50:18 +00001609
1610 // We don't want lookup warnings at this point.
1611 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001612
John McCalle66edc12009-11-24 19:00:30 +00001613 bool Dependent
1614 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1615 &TemplateArgs);
1616 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001617 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001618 Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001619 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001620 RequiresADL, TemplateArgs,
1621 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001622
1623 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001624}
1625
John McCalle66edc12009-11-24 19:00:30 +00001626// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00001627ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001628Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001629 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +00001630 const TemplateArgumentListInfo &TemplateArgs) {
1631 DeclContext *DC;
1632 if (!(DC = computeDeclContext(SS, false)) ||
1633 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001634 RequireCompleteDeclContext(SS, DC))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001635 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001636
Douglas Gregor786123d2010-05-21 23:18:07 +00001637 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001638 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00001639 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1640 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00001641
John McCalle66edc12009-11-24 19:00:30 +00001642 if (R.isAmbiguous())
1643 return ExprError();
1644
1645 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001646 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1647 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001648 return ExprError();
1649 }
1650
1651 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001652 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1653 << (NestedNameSpecifier*) SS.getScopeRep()
1654 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001655 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1656 return ExprError();
1657 }
1658
1659 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001660}
1661
Douglas Gregorb67535d2009-03-31 00:43:58 +00001662/// \brief Form a dependent template name.
1663///
1664/// This action forms a dependent template name given the template
1665/// name and its (presumably dependent) scope specifier. For
1666/// example, given "MetaFun::template apply", the scope specifier \p
1667/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1668/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregorbb119652010-06-16 23:00:59 +00001669TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1670 SourceLocation TemplateKWLoc,
1671 CXXScopeSpec &SS,
1672 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00001673 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00001674 bool EnteringContext,
1675 TemplateTy &Result) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00001676 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1677 !getLangOptions().CPlusPlus0x)
1678 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1679 << FixItHint::CreateRemoval(TemplateKWLoc);
1680
Douglas Gregor9abe2372010-01-19 16:01:07 +00001681 DeclContext *LookupCtx = 0;
1682 if (SS.isSet())
1683 LookupCtx = computeDeclContext(SS, EnteringContext);
1684 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00001685 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00001686 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001687 // C++0x [temp.names]p5:
1688 // If a name prefixed by the keyword template is not the name of
1689 // a template, the program is ill-formed. [Note: the keyword
1690 // template may not be applied to non-template members of class
1691 // templates. -end note ] [ Note: as is the case with the
1692 // typename prefix, the template prefix is allowed in cases
1693 // where it is not strictly necessary; i.e., when the
1694 // nested-name-specifier or the expression on the left of the ->
1695 // or . is not dependent on a template-parameter, or the use
1696 // does not appear in the scope of a template. -end note]
1697 //
1698 // Note: C++03 was more strict here, because it banned the use of
1699 // the "template" keyword prior to a template-name that was not a
1700 // dependent name. C++ DR468 relaxed this requirement (the
1701 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00001702 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00001703 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001704 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1705 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00001706 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001707 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1708 isa<CXXRecordDecl>(LookupCtx) &&
1709 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregorbb119652010-06-16 23:00:59 +00001710 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00001711 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001712 Diag(Name.getSourceRange().getBegin(),
1713 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001714 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001715 << Name.getSourceRange()
1716 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001717 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00001718 } else {
1719 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00001720 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001721 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001722 }
1723
Mike Stump11289f42009-09-09 15:08:12 +00001724 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001725 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001726
1727 switch (Name.getKind()) {
1728 case UnqualifiedId::IK_Identifier:
Douglas Gregorbb119652010-06-16 23:00:59 +00001729 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1730 Name.Identifier));
1731 return TNK_Dependent_template_name;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001732
Douglas Gregor71395fa2009-11-04 00:56:37 +00001733 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00001734 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00001735 Name.OperatorFunctionId.Operator));
Douglas Gregorbb119652010-06-16 23:00:59 +00001736 return TNK_Dependent_template_name;
Alexis Hunted0530f2009-11-28 08:58:14 +00001737
1738 case UnqualifiedId::IK_LiteralOperatorId:
1739 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1740
Douglas Gregor3cf81312009-11-03 23:16:33 +00001741 default:
1742 break;
1743 }
1744
1745 Diag(Name.getSourceRange().getBegin(),
1746 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001747 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001748 << Name.getSourceRange()
1749 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001750 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001751}
1752
Mike Stump11289f42009-09-09 15:08:12 +00001753bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001754 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001755 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001756 const TemplateArgument &Arg = AL.getArgument();
1757
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001758 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001759 switch(Arg.getKind()) {
1760 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001761 // C++ [temp.arg.type]p1:
1762 // A template-argument for a template-parameter which is a
1763 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001764 break;
1765 case TemplateArgument::Template: {
1766 // We have a template type parameter but the template argument
1767 // is a template without any arguments.
1768 SourceRange SR = AL.getSourceRange();
1769 TemplateName Name = Arg.getAsTemplate();
1770 Diag(SR.getBegin(), diag::err_template_missing_args)
1771 << Name << SR;
1772 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1773 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001774
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001775 return true;
1776 }
1777 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001778 // We have a template type parameter but the template argument
1779 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001780 SourceRange SR = AL.getSourceRange();
1781 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001782 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001783
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001784 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001785 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001786 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001787
John McCallbcd03502009-12-07 02:54:59 +00001788 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001789 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001790
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001791 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001792 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001793 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001794 return false;
1795}
1796
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001797/// \brief Substitute template arguments into the default template argument for
1798/// the given template type parameter.
1799///
1800/// \param SemaRef the semantic analysis object for which we are performing
1801/// the substitution.
1802///
1803/// \param Template the template that we are synthesizing template arguments
1804/// for.
1805///
1806/// \param TemplateLoc the location of the template name that started the
1807/// template-id we are checking.
1808///
1809/// \param RAngleLoc the location of the right angle bracket ('>') that
1810/// terminates the template-id.
1811///
1812/// \param Param the template template parameter whose default we are
1813/// substituting into.
1814///
1815/// \param Converted the list of template arguments provided for template
1816/// parameters that precede \p Param in the template parameter list.
1817///
1818/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001819static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001820SubstDefaultTemplateArgument(Sema &SemaRef,
1821 TemplateDecl *Template,
1822 SourceLocation TemplateLoc,
1823 SourceLocation RAngleLoc,
1824 TemplateTypeParmDecl *Param,
1825 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001826 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001827
1828 // If the argument type is dependent, instantiate it now based
1829 // on the previously-computed template arguments.
1830 if (ArgType->getType()->isDependentType()) {
1831 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1832 /*TakeArgs=*/false);
1833
1834 MultiLevelTemplateArgumentList AllTemplateArgs
1835 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1836
1837 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1838 Template, Converted.getFlatArguments(),
1839 Converted.flatSize(),
1840 SourceRange(TemplateLoc, RAngleLoc));
1841
1842 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1843 Param->getDefaultArgumentLoc(),
1844 Param->getDeclName());
1845 }
1846
1847 return ArgType;
1848}
1849
1850/// \brief Substitute template arguments into the default template argument for
1851/// the given non-type template parameter.
1852///
1853/// \param SemaRef the semantic analysis object for which we are performing
1854/// the substitution.
1855///
1856/// \param Template the template that we are synthesizing template arguments
1857/// for.
1858///
1859/// \param TemplateLoc the location of the template name that started the
1860/// template-id we are checking.
1861///
1862/// \param RAngleLoc the location of the right angle bracket ('>') that
1863/// terminates the template-id.
1864///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001865/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001866/// substituting into.
1867///
1868/// \param Converted the list of template arguments provided for template
1869/// parameters that precede \p Param in the template parameter list.
1870///
1871/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00001872static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001873SubstDefaultTemplateArgument(Sema &SemaRef,
1874 TemplateDecl *Template,
1875 SourceLocation TemplateLoc,
1876 SourceLocation RAngleLoc,
1877 NonTypeTemplateParmDecl *Param,
1878 TemplateArgumentListBuilder &Converted) {
1879 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1880 /*TakeArgs=*/false);
1881
1882 MultiLevelTemplateArgumentList AllTemplateArgs
1883 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1884
1885 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1886 Template, Converted.getFlatArguments(),
1887 Converted.flatSize(),
1888 SourceRange(TemplateLoc, RAngleLoc));
1889
1890 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1891}
1892
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001893/// \brief Substitute template arguments into the default template argument for
1894/// the given template template parameter.
1895///
1896/// \param SemaRef the semantic analysis object for which we are performing
1897/// the substitution.
1898///
1899/// \param Template the template that we are synthesizing template arguments
1900/// for.
1901///
1902/// \param TemplateLoc the location of the template name that started the
1903/// template-id we are checking.
1904///
1905/// \param RAngleLoc the location of the right angle bracket ('>') that
1906/// terminates the template-id.
1907///
1908/// \param Param the template template parameter whose default we are
1909/// substituting into.
1910///
1911/// \param Converted the list of template arguments provided for template
1912/// parameters that precede \p Param in the template parameter list.
1913///
1914/// \returns the substituted template argument, or NULL if an error occurred.
1915static TemplateName
1916SubstDefaultTemplateArgument(Sema &SemaRef,
1917 TemplateDecl *Template,
1918 SourceLocation TemplateLoc,
1919 SourceLocation RAngleLoc,
1920 TemplateTemplateParmDecl *Param,
1921 TemplateArgumentListBuilder &Converted) {
1922 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1923 /*TakeArgs=*/false);
1924
1925 MultiLevelTemplateArgumentList AllTemplateArgs
1926 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1927
1928 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1929 Template, Converted.getFlatArguments(),
1930 Converted.flatSize(),
1931 SourceRange(TemplateLoc, RAngleLoc));
1932
1933 return SemaRef.SubstTemplateName(
1934 Param->getDefaultArgument().getArgument().getAsTemplate(),
1935 Param->getDefaultArgument().getTemplateNameLoc(),
1936 AllTemplateArgs);
1937}
1938
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001939/// \brief If the given template parameter has a default template
1940/// argument, substitute into that default template argument and
1941/// return the corresponding template argument.
1942TemplateArgumentLoc
1943Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1944 SourceLocation TemplateLoc,
1945 SourceLocation RAngleLoc,
1946 Decl *Param,
1947 TemplateArgumentListBuilder &Converted) {
1948 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1949 if (!TypeParm->hasDefaultArgument())
1950 return TemplateArgumentLoc();
1951
John McCallbcd03502009-12-07 02:54:59 +00001952 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001953 TemplateLoc,
1954 RAngleLoc,
1955 TypeParm,
1956 Converted);
1957 if (DI)
1958 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1959
1960 return TemplateArgumentLoc();
1961 }
1962
1963 if (NonTypeTemplateParmDecl *NonTypeParm
1964 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1965 if (!NonTypeParm->hasDefaultArgument())
1966 return TemplateArgumentLoc();
1967
John McCalldadc5752010-08-24 06:29:42 +00001968 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001969 TemplateLoc,
1970 RAngleLoc,
1971 NonTypeParm,
1972 Converted);
1973 if (Arg.isInvalid())
1974 return TemplateArgumentLoc();
1975
1976 Expr *ArgE = Arg.takeAs<Expr>();
1977 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1978 }
1979
1980 TemplateTemplateParmDecl *TempTempParm
1981 = cast<TemplateTemplateParmDecl>(Param);
1982 if (!TempTempParm->hasDefaultArgument())
1983 return TemplateArgumentLoc();
1984
1985 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1986 TemplateLoc,
1987 RAngleLoc,
1988 TempTempParm,
1989 Converted);
1990 if (TName.isNull())
1991 return TemplateArgumentLoc();
1992
1993 return TemplateArgumentLoc(TemplateArgument(TName),
1994 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1995 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1996}
1997
Douglas Gregorda0fb532009-11-11 19:31:23 +00001998/// \brief Check that the given template argument corresponds to the given
1999/// template parameter.
2000bool Sema::CheckTemplateArgument(NamedDecl *Param,
2001 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002002 TemplateDecl *Template,
2003 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002004 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002005 TemplateArgumentListBuilder &Converted,
2006 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00002007 // Check template type parameters.
2008 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002009 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002010
Douglas Gregoreebed722009-11-11 19:41:09 +00002011 // Check non-type template parameters.
2012 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00002013 // Do substitution on the type of the non-type template parameter
2014 // with the template arguments we've seen thus far.
2015 QualType NTTPType = NTTP->getType();
2016 if (NTTPType->isDependentType()) {
2017 // Do substitution on the type of the non-type template parameter.
2018 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2019 NTTP, Converted.getFlatArguments(),
2020 Converted.flatSize(),
2021 SourceRange(TemplateLoc, RAngleLoc));
2022
2023 TemplateArgumentList TemplateArgs(Context, Converted,
2024 /*TakeArgs=*/false);
2025 NTTPType = SubstType(NTTPType,
2026 MultiLevelTemplateArgumentList(TemplateArgs),
2027 NTTP->getLocation(),
2028 NTTP->getDeclName());
2029 // If that worked, check the non-type template parameter type
2030 // for validity.
2031 if (!NTTPType.isNull())
2032 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2033 NTTP->getLocation());
2034 if (NTTPType.isNull())
2035 return true;
2036 }
2037
2038 switch (Arg.getArgument().getKind()) {
2039 case TemplateArgument::Null:
2040 assert(false && "Should never see a NULL template argument here");
2041 return true;
2042
2043 case TemplateArgument::Expression: {
2044 Expr *E = Arg.getArgument().getAsExpr();
2045 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002046 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002047 return true;
2048
2049 Converted.Append(Result);
2050 break;
2051 }
2052
2053 case TemplateArgument::Declaration:
2054 case TemplateArgument::Integral:
2055 // We've already checked this template argument, so just copy
2056 // it to the list of converted arguments.
2057 Converted.Append(Arg.getArgument());
2058 break;
2059
2060 case TemplateArgument::Template:
2061 // We were given a template template argument. It may not be ill-formed;
2062 // see below.
2063 if (DependentTemplateName *DTN
2064 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2065 // We have a template argument such as \c T::template X, which we
2066 // parsed as a template template argument. However, since we now
2067 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002068 // template name into an expression.
2069
2070 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2071 Arg.getTemplateNameLoc());
2072
John McCalle66edc12009-11-24 19:00:30 +00002073 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2074 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002075 Arg.getTemplateQualifierRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002076 NameInfo);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002077
2078 TemplateArgument Result;
2079 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2080 return true;
2081
2082 Converted.Append(Result);
2083 break;
2084 }
2085
2086 // We have a template argument that actually does refer to a class
2087 // template, template alias, or template template parameter, and
2088 // therefore cannot be a non-type template argument.
2089 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2090 << Arg.getSourceRange();
2091
2092 Diag(Param->getLocation(), diag::note_template_param_here);
2093 return true;
2094
2095 case TemplateArgument::Type: {
2096 // We have a non-type template parameter but the template
2097 // argument is a type.
2098
2099 // C++ [temp.arg]p2:
2100 // In a template-argument, an ambiguity between a type-id and
2101 // an expression is resolved to a type-id, regardless of the
2102 // form of the corresponding template-parameter.
2103 //
2104 // We warn specifically about this case, since it can be rather
2105 // confusing for users.
2106 QualType T = Arg.getArgument().getAsType();
2107 SourceRange SR = Arg.getSourceRange();
2108 if (T->isFunctionType())
2109 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2110 else
2111 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2112 Diag(Param->getLocation(), diag::note_template_param_here);
2113 return true;
2114 }
2115
2116 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002117 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002118 break;
2119 }
2120
2121 return false;
2122 }
2123
2124
2125 // Check template template parameters.
2126 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2127
2128 // Substitute into the template parameter list of the template
2129 // template parameter, since previously-supplied template arguments
2130 // may appear within the template template parameter.
2131 {
2132 // Set up a template instantiation context.
2133 LocalInstantiationScope Scope(*this);
2134 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2135 TempParm, Converted.getFlatArguments(),
2136 Converted.flatSize(),
2137 SourceRange(TemplateLoc, RAngleLoc));
2138
2139 TemplateArgumentList TemplateArgs(Context, Converted,
2140 /*TakeArgs=*/false);
2141 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2142 SubstDecl(TempParm, CurContext,
2143 MultiLevelTemplateArgumentList(TemplateArgs)));
2144 if (!TempParm)
2145 return true;
2146
2147 // FIXME: TempParam is leaked.
2148 }
2149
2150 switch (Arg.getArgument().getKind()) {
2151 case TemplateArgument::Null:
2152 assert(false && "Should never see a NULL template argument here");
2153 return true;
2154
2155 case TemplateArgument::Template:
2156 if (CheckTemplateArgument(TempParm, Arg))
2157 return true;
2158
2159 Converted.Append(Arg.getArgument());
2160 break;
2161
2162 case TemplateArgument::Expression:
2163 case TemplateArgument::Type:
2164 // We have a template template parameter but the template
2165 // argument does not refer to a template.
2166 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2167 return true;
2168
2169 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002170 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002171 "Declaration argument with template template parameter");
2172 break;
2173 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002174 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002175 "Integral argument with template template parameter");
2176 break;
2177
2178 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002179 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002180 break;
2181 }
2182
2183 return false;
2184}
2185
Douglas Gregord32e0282009-02-09 23:23:08 +00002186/// \brief Check that the given template argument list is well-formed
2187/// for specializing the given template.
2188bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2189 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002190 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002191 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002192 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002193 TemplateParameterList *Params = Template->getTemplateParameters();
2194 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002195 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002196 bool Invalid = false;
2197
John McCall6b51f282009-11-23 01:53:49 +00002198 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2199
Mike Stump11289f42009-09-09 15:08:12 +00002200 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002201 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002202
Anders Carlsson15201f12009-06-13 02:08:00 +00002203 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002204 (NumArgs < Params->getMinRequiredArguments() &&
2205 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002206 // FIXME: point at either the first arg beyond what we can handle,
2207 // or the '>', depending on whether we have too many or too few
2208 // arguments.
2209 SourceRange Range;
2210 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002211 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002212 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2213 << (NumArgs > NumParams)
2214 << (isa<ClassTemplateDecl>(Template)? 0 :
2215 isa<FunctionTemplateDecl>(Template)? 1 :
2216 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2217 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002218 Diag(Template->getLocation(), diag::note_template_decl_here)
2219 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002220 Invalid = true;
2221 }
Mike Stump11289f42009-09-09 15:08:12 +00002222
2223 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002224 // [...] The type and form of each template-argument specified in
2225 // a template-id shall match the type and form specified for the
2226 // corresponding parameter declared by the template in its
2227 // template-parameter-list.
2228 unsigned ArgIdx = 0;
2229 for (TemplateParameterList::iterator Param = Params->begin(),
2230 ParamEnd = Params->end();
2231 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002232 if (ArgIdx > NumArgs && PartialTemplateArgs)
2233 break;
Mike Stump11289f42009-09-09 15:08:12 +00002234
Douglas Gregoreebed722009-11-11 19:41:09 +00002235 // If we have a template parameter pack, check every remaining template
2236 // argument against that template parameter pack.
2237 if ((*Param)->isTemplateParameterPack()) {
2238 Converted.BeginPack();
2239 for (; ArgIdx < NumArgs; ++ArgIdx) {
2240 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2241 TemplateLoc, RAngleLoc, Converted)) {
2242 Invalid = true;
2243 break;
2244 }
2245 }
2246 Converted.EndPack();
2247 continue;
2248 }
2249
Douglas Gregor84d49a22009-11-11 21:54:23 +00002250 if (ArgIdx < NumArgs) {
2251 // Check the template argument we were given.
2252 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2253 TemplateLoc, RAngleLoc, Converted))
2254 return true;
2255
2256 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002257 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002258
Douglas Gregor84d49a22009-11-11 21:54:23 +00002259 // We have a default template argument that we will use.
2260 TemplateArgumentLoc Arg;
2261
2262 // Retrieve the default template argument from the template
2263 // parameter. For each kind of template parameter, we substitute the
2264 // template arguments provided thus far and any "outer" template arguments
2265 // (when the template parameter was part of a nested template) into
2266 // the default argument.
2267 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2268 if (!TTP->hasDefaultArgument()) {
2269 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2270 break;
2271 }
2272
John McCallbcd03502009-12-07 02:54:59 +00002273 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002274 Template,
2275 TemplateLoc,
2276 RAngleLoc,
2277 TTP,
2278 Converted);
2279 if (!ArgType)
2280 return true;
2281
2282 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2283 ArgType);
2284 } else if (NonTypeTemplateParmDecl *NTTP
2285 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2286 if (!NTTP->hasDefaultArgument()) {
2287 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2288 break;
2289 }
2290
John McCalldadc5752010-08-24 06:29:42 +00002291 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002292 TemplateLoc,
2293 RAngleLoc,
2294 NTTP,
2295 Converted);
2296 if (E.isInvalid())
2297 return true;
2298
2299 Expr *Ex = E.takeAs<Expr>();
2300 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2301 } else {
2302 TemplateTemplateParmDecl *TempParm
2303 = cast<TemplateTemplateParmDecl>(*Param);
2304
2305 if (!TempParm->hasDefaultArgument()) {
2306 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2307 break;
2308 }
2309
2310 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2311 TemplateLoc,
2312 RAngleLoc,
2313 TempParm,
2314 Converted);
2315 if (Name.isNull())
2316 return true;
2317
2318 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2319 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2320 TempParm->getDefaultArgument().getTemplateNameLoc());
2321 }
2322
2323 // Introduce an instantiation record that describes where we are using
2324 // the default template argument.
2325 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2326 Converted.getFlatArguments(),
2327 Converted.flatSize(),
2328 SourceRange(TemplateLoc, RAngleLoc));
2329
2330 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002331 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002332 RAngleLoc, Converted))
2333 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002334 }
2335
2336 return Invalid;
2337}
2338
2339/// \brief Check a template argument against its corresponding
2340/// template type parameter.
2341///
2342/// This routine implements the semantics of C++ [temp.arg.type]. It
2343/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002344bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002345 TypeSourceInfo *ArgInfo) {
2346 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002347 QualType Arg = ArgInfo->getType();
2348
Douglas Gregord32e0282009-02-09 23:23:08 +00002349 // C++ [temp.arg.type]p2:
2350 // A local type, a type with no linkage, an unnamed type or a type
2351 // compounded from any of these types shall not be used as a
2352 // template-argument for a template type-parameter.
2353 //
Douglas Gregor959d5a02010-05-22 16:17:30 +00002354 // FIXME: Perform the unnamed type check.
2355 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002356 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002357 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002358 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002359 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002360 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002361 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002362 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall0ad16662009-10-29 08:12:44 +00002363 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2364 << QualType(Tag, 0) << SR;
2365 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002366 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002367 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002368 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2369 return true;
Douglas Gregor959d5a02010-05-22 16:17:30 +00002370 } else if (Arg->isVariablyModifiedType()) {
2371 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2372 << Arg;
2373 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002374 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002375 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002376 }
2377
2378 return false;
2379}
2380
Douglas Gregorccb07762009-02-11 19:52:55 +00002381/// \brief Checks whether the given template argument is the address
2382/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002383static bool
2384CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2385 NonTypeTemplateParmDecl *Param,
2386 QualType ParamType,
2387 Expr *ArgIn,
2388 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002389 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002390 Expr *Arg = ArgIn;
2391 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002392
2393 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002394 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002395 Arg = Cast->getSubExpr();
2396
2397 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002398 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002399 // A template-argument for a non-type, non-template
2400 // template-parameter shall be one of: [...]
2401 //
2402 // -- the address of an object or function with external
2403 // linkage, including function templates and function
2404 // template-ids but excluding non-static class members,
2405 // expressed as & id-expression where the & is optional if
2406 // the name refers to a function or array, or if the
2407 // corresponding template-parameter is a reference; or
2408 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002409
Douglas Gregorccb07762009-02-11 19:52:55 +00002410 // Ignore (and complain about) any excess parentheses.
2411 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2412 if (!Invalid) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002413 S.Diag(Arg->getSourceRange().getBegin(),
2414 diag::err_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002415 << Arg->getSourceRange();
2416 Invalid = true;
2417 }
2418
2419 Arg = Parens->getSubExpr();
2420 }
2421
Douglas Gregorb242683d2010-04-01 18:32:35 +00002422 bool AddressTaken = false;
2423 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002424 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00002425 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002426 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002427 AddressTaken = true;
2428 AddrOpLoc = UnOp->getOperatorLoc();
2429 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002430 } else
2431 DRE = dyn_cast<DeclRefExpr>(Arg);
2432
Douglas Gregorb242683d2010-04-01 18:32:35 +00002433 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002434 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2435 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002436 S.Diag(Param->getLocation(), diag::note_template_param_here);
2437 return true;
2438 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002439
2440 // Stop checking the precise nature of the argument if it is value dependent,
2441 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002442 if (Arg->isValueDependent()) {
2443 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002444 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002445 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002446
Douglas Gregorb242683d2010-04-01 18:32:35 +00002447 if (!isa<ValueDecl>(DRE->getDecl())) {
2448 S.Diag(Arg->getSourceRange().getBegin(),
2449 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002450 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002451 S.Diag(Param->getLocation(), diag::note_template_param_here);
2452 return true;
2453 }
2454
2455 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002456
2457 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002458 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2459 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002460 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002461 S.Diag(Param->getLocation(), diag::note_template_param_here);
2462 return true;
2463 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002464
2465 // Cannot refer to non-static member functions
2466 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002467 if (!Method->isStatic()) {
2468 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002469 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002470 S.Diag(Param->getLocation(), diag::note_template_param_here);
2471 return true;
2472 }
Mike Stump11289f42009-09-09 15:08:12 +00002473
Douglas Gregorccb07762009-02-11 19:52:55 +00002474 // Functions must have external linkage.
2475 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002476 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002477 S.Diag(Arg->getSourceRange().getBegin(),
2478 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002479 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002480 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002481 << true;
2482 return true;
2483 }
2484
2485 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002486 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002487
Douglas Gregorb242683d2010-04-01 18:32:35 +00002488 // If the template parameter has pointer type, the function decays.
2489 if (ParamType->isPointerType() && !AddressTaken)
2490 ArgType = S.Context.getPointerType(Func->getType());
2491 else if (AddressTaken && ParamType->isReferenceType()) {
2492 // If we originally had an address-of operator, but the
2493 // parameter has reference type, complain and (if things look
2494 // like they will work) drop the address-of operator.
2495 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2496 ParamType.getNonReferenceType())) {
2497 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2498 << ParamType;
2499 S.Diag(Param->getLocation(), diag::note_template_param_here);
2500 return true;
2501 }
2502
2503 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2504 << ParamType
2505 << FixItHint::CreateRemoval(AddrOpLoc);
2506 S.Diag(Param->getLocation(), diag::note_template_param_here);
2507
2508 ArgType = Func->getType();
2509 }
2510 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002511 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002512 S.Diag(Arg->getSourceRange().getBegin(),
2513 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002514 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002515 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002516 << true;
2517 return true;
2518 }
2519
Douglas Gregorb242683d2010-04-01 18:32:35 +00002520 // A value of reference type is not an object.
2521 if (Var->getType()->isReferenceType()) {
2522 S.Diag(Arg->getSourceRange().getBegin(),
2523 diag::err_template_arg_reference_var)
2524 << Var->getType() << Arg->getSourceRange();
2525 S.Diag(Param->getLocation(), diag::note_template_param_here);
2526 return true;
2527 }
2528
Douglas Gregorccb07762009-02-11 19:52:55 +00002529 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002530 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002531
2532 // If the template parameter has pointer type, we must have taken
2533 // the address of this object.
2534 if (ParamType->isReferenceType()) {
2535 if (AddressTaken) {
2536 // If we originally had an address-of operator, but the
2537 // parameter has reference type, complain and (if things look
2538 // like they will work) drop the address-of operator.
2539 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2540 ParamType.getNonReferenceType())) {
2541 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2542 << ParamType;
2543 S.Diag(Param->getLocation(), diag::note_template_param_here);
2544 return true;
2545 }
2546
2547 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2548 << ParamType
2549 << FixItHint::CreateRemoval(AddrOpLoc);
2550 S.Diag(Param->getLocation(), diag::note_template_param_here);
2551
2552 ArgType = Var->getType();
2553 }
2554 } else if (!AddressTaken && ParamType->isPointerType()) {
2555 if (Var->getType()->isArrayType()) {
2556 // Array-to-pointer decay.
2557 ArgType = S.Context.getArrayDecayedType(Var->getType());
2558 } else {
2559 // If the template parameter has pointer type but the address of
2560 // this object was not taken, complain and (possibly) recover by
2561 // taking the address of the entity.
2562 ArgType = S.Context.getPointerType(Var->getType());
2563 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2564 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2565 << ParamType;
2566 S.Diag(Param->getLocation(), diag::note_template_param_here);
2567 return true;
2568 }
2569
2570 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2571 << ParamType
2572 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2573
2574 S.Diag(Param->getLocation(), diag::note_template_param_here);
2575 }
2576 }
2577 } else {
2578 // We found something else, but we don't know specifically what it is.
2579 S.Diag(Arg->getSourceRange().getBegin(),
2580 diag::err_template_arg_not_object_or_func)
2581 << Arg->getSourceRange();
2582 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2583 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002584 }
Mike Stump11289f42009-09-09 15:08:12 +00002585
Douglas Gregorb242683d2010-04-01 18:32:35 +00002586 if (ParamType->isPointerType() &&
2587 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2588 S.IsQualificationConversion(ArgType, ParamType)) {
2589 // For pointer-to-object types, qualification conversions are
2590 // permitted.
2591 } else {
2592 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2593 if (!ParamRef->getPointeeType()->isFunctionType()) {
2594 // C++ [temp.arg.nontype]p5b3:
2595 // For a non-type template-parameter of type reference to
2596 // object, no conversions apply. The type referred to by the
2597 // reference may be more cv-qualified than the (otherwise
2598 // identical) type of the template- argument. The
2599 // template-parameter is bound directly to the
2600 // template-argument, which shall be an lvalue.
2601
2602 // FIXME: Other qualifiers?
2603 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2604 unsigned ArgQuals = ArgType.getCVRQualifiers();
2605
2606 if ((ParamQuals | ArgQuals) != ParamQuals) {
2607 S.Diag(Arg->getSourceRange().getBegin(),
2608 diag::err_template_arg_ref_bind_ignores_quals)
2609 << ParamType << Arg->getType()
2610 << Arg->getSourceRange();
2611 S.Diag(Param->getLocation(), diag::note_template_param_here);
2612 return true;
2613 }
2614 }
2615 }
2616
2617 // At this point, the template argument refers to an object or
2618 // function with external linkage. We now need to check whether the
2619 // argument and parameter types are compatible.
2620 if (!S.Context.hasSameUnqualifiedType(ArgType,
2621 ParamType.getNonReferenceType())) {
2622 // We can't perform this conversion or binding.
2623 if (ParamType->isReferenceType())
2624 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2625 << ParamType << Arg->getType() << Arg->getSourceRange();
2626 else
2627 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2628 << Arg->getType() << ParamType << Arg->getSourceRange();
2629 S.Diag(Param->getLocation(), diag::note_template_param_here);
2630 return true;
2631 }
2632 }
2633
2634 // Create the template argument.
2635 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002636 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002637 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002638}
2639
2640/// \brief Checks whether the given template argument is a pointer to
2641/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002642bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2643 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002644 bool Invalid = false;
2645
2646 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002647 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002648 Arg = Cast->getSubExpr();
2649
2650 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002651 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002652 // A template-argument for a non-type, non-template
2653 // template-parameter shall be one of: [...]
2654 //
2655 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002656 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002657
2658 // Ignore (and complain about) any excess parentheses.
2659 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2660 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002661 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002662 diag::err_template_arg_extra_parens)
2663 << Arg->getSourceRange();
2664 Invalid = true;
2665 }
2666
2667 Arg = Parens->getSubExpr();
2668 }
2669
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002670 // A pointer-to-member constant written &Class::member.
2671 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00002672 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002673 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2674 if (DRE && !DRE->getQualifier())
2675 DRE = 0;
2676 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002677 }
2678 // A constant of pointer-to-member type.
2679 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2680 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2681 if (VD->getType()->isMemberPointerType()) {
2682 if (isa<NonTypeTemplateParmDecl>(VD) ||
2683 (isa<VarDecl>(VD) &&
2684 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2685 if (Arg->isTypeDependent() || Arg->isValueDependent())
2686 Converted = TemplateArgument(Arg->Retain());
2687 else
2688 Converted = TemplateArgument(VD->getCanonicalDecl());
2689 return Invalid;
2690 }
2691 }
2692 }
2693
2694 DRE = 0;
2695 }
2696
Douglas Gregorccb07762009-02-11 19:52:55 +00002697 if (!DRE)
2698 return Diag(Arg->getSourceRange().getBegin(),
2699 diag::err_template_arg_not_pointer_to_member_form)
2700 << Arg->getSourceRange();
2701
2702 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2703 assert((isa<FieldDecl>(DRE->getDecl()) ||
2704 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2705 "Only non-static member pointers can make it here");
2706
2707 // Okay: this is the address of a non-static member, and therefore
2708 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002709 if (Arg->isTypeDependent() || Arg->isValueDependent())
2710 Converted = TemplateArgument(Arg->Retain());
2711 else
2712 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002713 return Invalid;
2714 }
2715
2716 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002717 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002718 diag::err_template_arg_not_pointer_to_member_form)
2719 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002720 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002721 diag::note_template_arg_refers_here);
2722 return true;
2723}
2724
Douglas Gregord32e0282009-02-09 23:23:08 +00002725/// \brief Check a template argument against its corresponding
2726/// non-type template parameter.
2727///
Douglas Gregor463421d2009-03-03 04:44:36 +00002728/// This routine implements the semantics of C++ [temp.arg.nontype].
2729/// It returns true if an error occurred, and false otherwise. \p
2730/// InstantiatedParamType is the type of the non-type template
2731/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002732///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002733/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002734bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002735 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002736 TemplateArgument &Converted,
2737 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002738 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2739
Douglas Gregor86560402009-02-10 23:36:10 +00002740 // If either the parameter has a dependent type or the argument is
2741 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002742 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2743 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002744 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002745 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002746 }
Douglas Gregor86560402009-02-10 23:36:10 +00002747
2748 // C++ [temp.arg.nontype]p5:
2749 // The following conversions are performed on each expression used
2750 // as a non-type template-argument. If a non-type
2751 // template-argument cannot be converted to the type of the
2752 // corresponding template-parameter then the program is
2753 // ill-formed.
2754 //
2755 // -- for a non-type template-parameter of integral or
2756 // enumeration type, integral promotions (4.5) and integral
2757 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002758 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002759 QualType ArgType = Arg->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +00002760 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002761 // C++ [temp.arg.nontype]p1:
2762 // A template-argument for a non-type, non-template
2763 // template-parameter shall be one of:
2764 //
2765 // -- an integral constant-expression of integral or enumeration
2766 // type; or
2767 // -- the name of a non-type template-parameter; or
2768 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002769 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00002770 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002771 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002772 diag::err_template_arg_not_integral_or_enumeral)
2773 << ArgType << Arg->getSourceRange();
2774 Diag(Param->getLocation(), diag::note_template_param_here);
2775 return true;
2776 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002777 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002778 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2779 << ArgType << Arg->getSourceRange();
2780 return true;
2781 }
2782
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002783 // From here on out, all we care about are the unqualified forms
2784 // of the parameter and argument types.
2785 ParamType = ParamType.getUnqualifiedType();
2786 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00002787
2788 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002789 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002790 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002791 } else if (CTAK == CTAK_Deduced) {
2792 // C++ [temp.deduct.type]p17:
2793 // If, in the declaration of a function template with a non-type
2794 // template-parameter, the non-type template- parameter is used
2795 // in an expression in the function parameter-list and, if the
2796 // corresponding template-argument is deduced, the
2797 // template-argument type shall match the type of the
2798 // template-parameter exactly, except that a template-argument
2799 // deduced from an array bound may be of any integral type.
2800 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2801 << ArgType << ParamType;
2802 Diag(Param->getLocation(), diag::note_template_param_here);
2803 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00002804 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2805 !ParamType->isEnumeralType()) {
2806 // This is an integral promotion or conversion.
John McCalle3027922010-08-25 11:45:40 +00002807 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002808 } else {
2809 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002810 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002811 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002812 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002813 Diag(Param->getLocation(), diag::note_template_param_here);
2814 return true;
2815 }
2816
Douglas Gregor52aba872009-03-14 00:20:21 +00002817 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002818 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002819 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002820
2821 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002822 llvm::APSInt OldValue = Value;
2823
2824 // Coerce the template argument's value to the value it will have
2825 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002826 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002827 if (Value.getBitWidth() != AllowedBits)
2828 Value.extOrTrunc(AllowedBits);
2829 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002830
2831 // Complain if an unsigned parameter received a negative value.
2832 if (IntegerType->isUnsignedIntegerType()
2833 && (OldValue.isSigned() && OldValue.isNegative())) {
2834 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2835 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2836 << Arg->getSourceRange();
2837 Diag(Param->getLocation(), diag::note_template_param_here);
2838 }
2839
2840 // Complain if we overflowed the template parameter's type.
2841 unsigned RequiredBits;
2842 if (IntegerType->isUnsignedIntegerType())
2843 RequiredBits = OldValue.getActiveBits();
2844 else if (OldValue.isUnsigned())
2845 RequiredBits = OldValue.getActiveBits() + 1;
2846 else
2847 RequiredBits = OldValue.getMinSignedBits();
2848 if (RequiredBits > AllowedBits) {
2849 Diag(Arg->getSourceRange().getBegin(),
2850 diag::warn_template_arg_too_large)
2851 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2852 << Arg->getSourceRange();
2853 Diag(Param->getLocation(), diag::note_template_param_here);
2854 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002855 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002856
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002857 // Add the value of this argument to the list of converted
2858 // arguments. We use the bitwidth and signedness of the template
2859 // parameter.
2860 if (Arg->isValueDependent()) {
2861 // The argument is value-dependent. Create a new
2862 // TemplateArgument with the converted expression.
2863 Converted = TemplateArgument(Arg);
2864 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002865 }
2866
John McCall0ad16662009-10-29 08:12:44 +00002867 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002868 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002869 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002870 return false;
2871 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002872
John McCall16df1e52010-03-30 21:47:33 +00002873 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2874
Douglas Gregorb242683d2010-04-01 18:32:35 +00002875 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2876 // from a template argument of type std::nullptr_t to a non-type
2877 // template parameter of type pointer to object, pointer to
2878 // function, or pointer-to-member, respectively.
2879 if (ArgType->isNullPtrType() &&
2880 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2881 Converted = TemplateArgument((NamedDecl *)0);
2882 return false;
2883 }
2884
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002885 // Handle pointer-to-function, reference-to-function, and
2886 // pointer-to-member-function all in (roughly) the same way.
2887 if (// -- For a non-type template-parameter of type pointer to
2888 // function, only the function-to-pointer conversion (4.3) is
2889 // applied. If the template-argument represents a set of
2890 // overloaded functions (or a pointer to such), the matching
2891 // function is selected from the set (13.4).
2892 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002893 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002894 // -- For a non-type template-parameter of type reference to
2895 // function, no conversions apply. If the template-argument
2896 // represents a set of overloaded functions, the matching
2897 // function is selected from the set (13.4).
2898 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002899 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002900 // -- For a non-type template-parameter of type pointer to
2901 // member function, no conversions apply. If the
2902 // template-argument represents a set of overloaded member
2903 // functions, the matching member function is selected from
2904 // the set (13.4).
2905 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002906 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002907 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002908
Douglas Gregor064fdb22010-04-14 23:11:21 +00002909 if (Arg->getType() == Context.OverloadTy) {
2910 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2911 true,
2912 FoundResult)) {
2913 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2914 return true;
2915
2916 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2917 ArgType = Arg->getType();
2918 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00002919 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002920 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002921
Douglas Gregorb242683d2010-04-01 18:32:35 +00002922 if (!ParamType->isMemberPointerType())
2923 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2924 ParamType,
2925 Arg, Converted);
2926
2927 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCalle3027922010-08-25 11:45:40 +00002928 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb242683d2010-04-01 18:32:35 +00002929 } else if (!Context.hasSameUnqualifiedType(ArgType,
2930 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002931 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002932 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002933 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002934 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002935 Diag(Param->getLocation(), diag::note_template_param_here);
2936 return true;
2937 }
Mike Stump11289f42009-09-09 15:08:12 +00002938
Douglas Gregorb242683d2010-04-01 18:32:35 +00002939 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002940 }
2941
Chris Lattner696197c2009-02-20 21:37:53 +00002942 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002943 // -- for a non-type template-parameter of type pointer to
2944 // object, qualification conversions (4.4) and the
2945 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002946 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00002947 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002948 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002949
Douglas Gregorb242683d2010-04-01 18:32:35 +00002950 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2951 ParamType,
2952 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00002953 }
Mike Stump11289f42009-09-09 15:08:12 +00002954
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002955 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002956 // -- For a non-type template-parameter of type reference to
2957 // object, no conversions apply. The type referred to by the
2958 // reference may be more cv-qualified than the (otherwise
2959 // identical) type of the template-argument. The
2960 // template-parameter is bound directly to the
2961 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00002962 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002963 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002964
Douglas Gregor064fdb22010-04-14 23:11:21 +00002965 if (Arg->getType() == Context.OverloadTy) {
2966 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2967 ParamRefType->getPointeeType(),
2968 true,
2969 FoundResult)) {
2970 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2971 return true;
2972
2973 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2974 ArgType = Arg->getType();
2975 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00002976 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002977 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002978
Douglas Gregorb242683d2010-04-01 18:32:35 +00002979 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2980 ParamType,
2981 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002982 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002983
2984 // -- For a non-type template-parameter of type pointer to data
2985 // member, qualification conversions (4.4) are applied.
2986 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2987
Douglas Gregor1515f762009-02-11 18:22:40 +00002988 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002989 // Types match exactly: nothing more to do here.
2990 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCalle3027922010-08-25 11:45:40 +00002991 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor0e558532009-02-11 16:16:59 +00002992 } else {
2993 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002994 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002995 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002996 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002997 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002998 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002999 }
3000
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00003001 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00003002}
3003
3004/// \brief Check a template argument against its corresponding
3005/// template template parameter.
3006///
3007/// This routine implements the semantics of C++ [temp.arg.template].
3008/// It returns true if an error occurred, and false otherwise.
3009bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003010 const TemplateArgumentLoc &Arg) {
3011 TemplateName Name = Arg.getArgument().getAsTemplate();
3012 TemplateDecl *Template = Name.getAsTemplateDecl();
3013 if (!Template) {
3014 // Any dependent template name is fine.
3015 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3016 return false;
3017 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003018
3019 // C++ [temp.arg.template]p1:
3020 // A template-argument for a template template-parameter shall be
3021 // the name of a class template, expressed as id-expression. Only
3022 // primary class templates are considered when matching the
3023 // template template argument with the corresponding parameter;
3024 // partial specializations are not considered even if their
3025 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003026 //
3027 // Note that we also allow template template parameters here, which
3028 // will happen when we are dealing with, e.g., class template
3029 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003030 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003031 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003032 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003033 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003034 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003035 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003036 << Template;
3037 }
3038
3039 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3040 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003041 true,
3042 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003043 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003044}
3045
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003046/// \brief Given a non-type template argument that refers to a
3047/// declaration and the type of its corresponding non-type template
3048/// parameter, produce an expression that properly refers to that
3049/// declaration.
John McCalldadc5752010-08-24 06:29:42 +00003050ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003051Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3052 QualType ParamType,
3053 SourceLocation Loc) {
3054 assert(Arg.getKind() == TemplateArgument::Declaration &&
3055 "Only declaration template arguments permitted here");
3056 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3057
3058 if (VD->getDeclContext()->isRecord() &&
3059 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3060 // If the value is a class member, we might have a pointer-to-member.
3061 // Determine whether the non-type template template parameter is of
3062 // pointer-to-member type. If so, we need to build an appropriate
3063 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3064 // would refer to the member itself.
3065 if (ParamType->isMemberPointerType()) {
3066 QualType ClassType
3067 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3068 NestedNameSpecifier *Qualifier
John McCallb268a282010-08-23 23:25:46 +00003069 = NestedNameSpecifier::Create(Context, 0, false,
3070 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003071 CXXScopeSpec SS;
3072 SS.setScopeRep(Qualifier);
John McCalldadc5752010-08-24 06:29:42 +00003073 ExprResult RefExpr = BuildDeclRefExpr(VD,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003074 VD->getType().getNonReferenceType(),
3075 Loc,
3076 &SS);
3077 if (RefExpr.isInvalid())
3078 return ExprError();
3079
John McCalle3027922010-08-25 11:45:40 +00003080 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003081
3082 // We might need to perform a trailing qualification conversion, since
3083 // the element type on the parameter could be more qualified than the
3084 // element type in the expression we constructed.
3085 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3086 ParamType.getUnqualifiedType())) {
3087 Expr *RefE = RefExpr.takeAs<Expr>();
John McCalle3027922010-08-25 11:45:40 +00003088 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003089 RefExpr = Owned(RefE);
3090 }
3091
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003092 assert(!RefExpr.isInvalid() &&
3093 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003094 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003095 return move(RefExpr);
3096 }
3097 }
3098
3099 QualType T = VD->getType().getNonReferenceType();
3100 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003101 // When the non-type template parameter is a pointer, take the
3102 // address of the declaration.
John McCalldadc5752010-08-24 06:29:42 +00003103 ExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003104 if (RefExpr.isInvalid())
3105 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003106
3107 if (T->isFunctionType() || T->isArrayType()) {
3108 // Decay functions and arrays.
3109 Expr *RefE = (Expr *)RefExpr.get();
3110 DefaultFunctionArrayConversion(RefE);
3111 if (RefE != RefExpr.get()) {
3112 RefExpr.release();
3113 RefExpr = Owned(RefE);
3114 }
3115
3116 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003117 }
3118
Douglas Gregorb242683d2010-04-01 18:32:35 +00003119 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00003120 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003121 }
3122
3123 // If the non-type template parameter has reference type, qualify the
3124 // resulting declaration reference with the extra qualifiers on the
3125 // type that the reference refers to.
3126 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3127 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3128
3129 return BuildDeclRefExpr(VD, T, Loc);
3130}
3131
3132/// \brief Construct a new expression that refers to the given
3133/// integral template argument with the given source-location
3134/// information.
3135///
3136/// This routine takes care of the mapping from an integral template
3137/// argument (which may have any integral type) to the appropriate
3138/// literal value.
John McCalldadc5752010-08-24 06:29:42 +00003139ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003140Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3141 SourceLocation Loc) {
3142 assert(Arg.getKind() == TemplateArgument::Integral &&
3143 "Operation is only value for integral template arguments");
3144 QualType T = Arg.getIntegralType();
3145 if (T->isCharType() || T->isWideCharType())
3146 return Owned(new (Context) CharacterLiteral(
3147 Arg.getAsIntegral()->getZExtValue(),
3148 T->isWideCharType(),
3149 T,
3150 Loc));
3151 if (T->isBooleanType())
3152 return Owned(new (Context) CXXBoolLiteralExpr(
3153 Arg.getAsIntegral()->getBoolValue(),
3154 T,
3155 Loc));
3156
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003157 return Owned(IntegerLiteral::Create(Context, *Arg.getAsIntegral(), T, Loc));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003158}
3159
3160
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003161/// \brief Determine whether the given template parameter lists are
3162/// equivalent.
3163///
Mike Stump11289f42009-09-09 15:08:12 +00003164/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003165/// source code as part of a new template declaration.
3166///
3167/// \param Old The old template parameter list, typically found via
3168/// name lookup of the template declared with this template parameter
3169/// list.
3170///
3171/// \param Complain If true, this routine will produce a diagnostic if
3172/// the template parameter lists are not equivalent.
3173///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003174/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003175///
3176/// \param TemplateArgLoc If this source location is valid, then we
3177/// are actually checking the template parameter list of a template
3178/// argument (New) against the template parameter list of its
3179/// corresponding template template parameter (Old). We produce
3180/// slightly different diagnostics in this scenario.
3181///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003182/// \returns True if the template parameter lists are equal, false
3183/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003184bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003185Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3186 TemplateParameterList *Old,
3187 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003188 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003189 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003190 if (Old->size() != New->size()) {
3191 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003192 unsigned NextDiag = diag::err_template_param_list_different_arity;
3193 if (TemplateArgLoc.isValid()) {
3194 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3195 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003196 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003197 Diag(New->getTemplateLoc(), NextDiag)
3198 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003199 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003200 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003201 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003202 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003203 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3204 }
3205
3206 return false;
3207 }
3208
3209 for (TemplateParameterList::iterator OldParm = Old->begin(),
3210 OldParmEnd = Old->end(), NewParm = New->begin();
3211 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3212 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003213 if (Complain) {
3214 unsigned NextDiag = diag::err_template_param_different_kind;
3215 if (TemplateArgLoc.isValid()) {
3216 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3217 NextDiag = diag::note_template_param_different_kind;
3218 }
3219 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003220 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003221 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003222 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003223 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003224 return false;
3225 }
3226
Douglas Gregor2e87ca22010-06-04 08:34:32 +00003227 if (TemplateTypeParmDecl *OldTTP
3228 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3229 // Template type parameters are equivalent if either both are template
3230 // type parameter packs or neither are (since we know we're at the same
3231 // index).
3232 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3233 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3234 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3235 // allow one to match a template parameter pack in the template
3236 // parameter list of a template template parameter to one or more
3237 // template parameters in the template parameter list of the
3238 // corresponding template template argument.
3239 if (Complain) {
3240 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3241 if (TemplateArgLoc.isValid()) {
3242 Diag(TemplateArgLoc,
3243 diag::err_template_arg_template_params_mismatch);
3244 NextDiag = diag::note_template_parameter_pack_non_pack;
3245 }
3246 Diag(NewTTP->getLocation(), NextDiag)
3247 << 0 << NewTTP->isParameterPack();
3248 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3249 << 0 << OldTTP->isParameterPack();
3250 }
3251 return false;
3252 }
Mike Stump11289f42009-09-09 15:08:12 +00003253 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003254 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3255 // The types of non-type template parameters must agree.
3256 NonTypeTemplateParmDecl *NewNTTP
3257 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003258
3259 // If we are matching a template template argument to a template
3260 // template parameter and one of the non-type template parameter types
3261 // is dependent, then we must wait until template instantiation time
3262 // to actually compare the arguments.
3263 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3264 (OldNTTP->getType()->isDependentType() ||
3265 NewNTTP->getType()->isDependentType()))
3266 continue;
3267
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003268 if (Context.getCanonicalType(OldNTTP->getType()) !=
3269 Context.getCanonicalType(NewNTTP->getType())) {
3270 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003271 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3272 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003273 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003274 diag::err_template_arg_template_params_mismatch);
3275 NextDiag = diag::note_template_nontype_parm_different_type;
3276 }
3277 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003278 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003279 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003280 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003281 diag::note_template_nontype_parm_prev_declaration)
3282 << OldNTTP->getType();
3283 }
3284 return false;
3285 }
3286 } else {
3287 // The template parameter lists of template template
3288 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003289 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003290 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003291 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003292 = cast<TemplateTemplateParmDecl>(*OldParm);
3293 TemplateTemplateParmDecl *NewTTP
3294 = cast<TemplateTemplateParmDecl>(*NewParm);
3295 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3296 OldTTP->getTemplateParameters(),
3297 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003298 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003299 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003300 return false;
3301 }
3302 }
3303
3304 return true;
3305}
3306
3307/// \brief Check whether a template can be declared within this scope.
3308///
3309/// If the template declaration is valid in this scope, returns
3310/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003311bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003312Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003313 // Find the nearest enclosing declaration scope.
3314 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3315 (S->getFlags() & Scope::TemplateParamScope) != 0)
3316 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003317
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003318 // C++ [temp]p2:
3319 // A template-declaration can appear only as a namespace scope or
3320 // class scope declaration.
3321 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003322 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3323 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003324 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003325 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003326
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003327 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003328 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003329
3330 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3331 return false;
3332
Mike Stump11289f42009-09-09 15:08:12 +00003333 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003334 diag::err_template_outside_namespace_or_class_scope)
3335 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003336}
Douglas Gregor67a65642009-02-17 23:15:12 +00003337
Douglas Gregor54888652009-10-07 00:13:32 +00003338/// \brief Determine what kind of template specialization the given declaration
3339/// is.
3340static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3341 if (!D)
3342 return TSK_Undeclared;
3343
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003344 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3345 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003346 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3347 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003348 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3349 return Var->getTemplateSpecializationKind();
3350
Douglas Gregor54888652009-10-07 00:13:32 +00003351 return TSK_Undeclared;
3352}
3353
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003354/// \brief Check whether a specialization is well-formed in the current
3355/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003356///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003357/// This routine determines whether a template specialization can be declared
3358/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003359///
3360/// \param S the semantic analysis object for which this check is being
3361/// performed.
3362///
3363/// \param Specialized the entity being specialized or instantiated, which
3364/// may be a kind of template (class template, function template, etc.) or
3365/// a member of a class template (member function, static data member,
3366/// member class).
3367///
3368/// \param PrevDecl the previous declaration of this entity, if any.
3369///
3370/// \param Loc the location of the explicit specialization or instantiation of
3371/// this entity.
3372///
3373/// \param IsPartialSpecialization whether this is a partial specialization of
3374/// a class template.
3375///
Douglas Gregor54888652009-10-07 00:13:32 +00003376/// \returns true if there was an error that we cannot recover from, false
3377/// otherwise.
3378static bool CheckTemplateSpecializationScope(Sema &S,
3379 NamedDecl *Specialized,
3380 NamedDecl *PrevDecl,
3381 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003382 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003383 // Keep these "kind" numbers in sync with the %select statements in the
3384 // various diagnostics emitted by this routine.
3385 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003386 bool isTemplateSpecialization = false;
3387 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003388 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003389 isTemplateSpecialization = true;
3390 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003391 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003392 isTemplateSpecialization = true;
3393 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003394 EntityKind = 3;
3395 else if (isa<VarDecl>(Specialized))
3396 EntityKind = 4;
3397 else if (isa<RecordDecl>(Specialized))
3398 EntityKind = 5;
3399 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003400 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3401 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003402 return true;
3403 }
3404
Douglas Gregorf47b9112009-02-25 22:02:03 +00003405 // C++ [temp.expl.spec]p2:
3406 // An explicit specialization shall be declared in the namespace
3407 // of which the template is a member, or, for member templates, in
3408 // the namespace of which the enclosing class or enclosing class
3409 // template is a member. An explicit specialization of a member
3410 // function, member class or static data member of a class
3411 // template shall be declared in the namespace of which the class
3412 // template is a member. Such a declaration may also be a
3413 // definition. If the declaration is not a definition, the
3414 // specialization may be defined later in the name- space in which
3415 // the explicit specialization was declared, or in a namespace
3416 // that encloses the one in which the explicit specialization was
3417 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003418 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3419 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003420 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003421 return true;
3422 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003423
Douglas Gregor40fb7442009-10-07 17:30:37 +00003424 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3425 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003426 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003427 return true;
3428 }
3429
Douglas Gregore4b05162009-10-07 17:21:34 +00003430 // C++ [temp.class.spec]p6:
3431 // A class template partial specialization may be declared or redeclared
3432 // in any namespace scope in which its definition may be defined (14.5.1
3433 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003434 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003435 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003436 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003437 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003438 if ((!PrevDecl ||
3439 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3440 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3441 // There is no prior declaration of this entity, so this
3442 // specialization must be in the same context as the template
3443 // itself.
3444 if (!DC->Equals(SpecializedContext)) {
3445 if (isa<TranslationUnitDecl>(SpecializedContext))
3446 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3447 << EntityKind << Specialized;
3448 else if (isa<NamespaceDecl>(SpecializedContext))
3449 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3450 << EntityKind << Specialized
3451 << cast<NamedDecl>(SpecializedContext);
3452
3453 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3454 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003455 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003456 }
Douglas Gregor54888652009-10-07 00:13:32 +00003457
3458 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003459 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003460 // Note that HandleDeclarator() performs this check for explicit
3461 // specializations of function templates, static data members, and member
3462 // functions, so we skip the check here for those kinds of entities.
3463 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003464 // Should we refactor that check, so that it occurs later?
3465 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003466 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3467 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003468 if (isa<TranslationUnitDecl>(SpecializedContext))
3469 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3470 << EntityKind << Specialized;
3471 else if (isa<NamespaceDecl>(SpecializedContext))
3472 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3473 << EntityKind << Specialized
3474 << cast<NamedDecl>(SpecializedContext);
3475
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003476 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003477 }
Douglas Gregor54888652009-10-07 00:13:32 +00003478
3479 // FIXME: check for specialization-after-instantiation errors and such.
3480
Douglas Gregorf47b9112009-02-25 22:02:03 +00003481 return false;
3482}
Douglas Gregor54888652009-10-07 00:13:32 +00003483
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003484/// \brief Check the non-type template arguments of a class template
3485/// partial specialization according to C++ [temp.class.spec]p9.
3486///
Douglas Gregor09a30232009-06-12 22:08:06 +00003487/// \param TemplateParams the template parameters of the primary class
3488/// template.
3489///
3490/// \param TemplateArg the template arguments of the class template
3491/// partial specialization.
3492///
3493/// \param MirrorsPrimaryTemplate will be set true if the class
3494/// template partial specialization arguments are identical to the
3495/// implicit template arguments of the primary template. This is not
3496/// necessarily an error (C++0x), and it is left to the caller to diagnose
3497/// this condition when it is an error.
3498///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003499/// \returns true if there was an error, false otherwise.
3500bool Sema::CheckClassTemplatePartialSpecializationArgs(
3501 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003502 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003503 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003504 // FIXME: the interface to this function will have to change to
3505 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003506 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003507
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003508 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003509
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003510 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003511 // Determine whether the template argument list of the partial
3512 // specialization is identical to the implicit argument list of
3513 // the primary template. The caller may need to diagnostic this as
3514 // an error per C++ [temp.class.spec]p9b3.
3515 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003516 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003517 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3518 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003519 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003520 MirrorsPrimaryTemplate = false;
3521 } else if (TemplateTemplateParmDecl *TTP
3522 = dyn_cast<TemplateTemplateParmDecl>(
3523 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003524 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003525 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003526 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003527 if (!ArgDecl ||
3528 ArgDecl->getIndex() != TTP->getIndex() ||
3529 ArgDecl->getDepth() != TTP->getDepth())
3530 MirrorsPrimaryTemplate = false;
3531 }
3532 }
3533
Mike Stump11289f42009-09-09 15:08:12 +00003534 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003535 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003536 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003537 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003538 }
3539
Anders Carlsson40c1d492009-06-13 18:20:51 +00003540 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003541 if (!ArgExpr) {
3542 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003543 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003544 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003545
3546 // C++ [temp.class.spec]p8:
3547 // A non-type argument is non-specialized if it is the name of a
3548 // non-type parameter. All other non-type arguments are
3549 // specialized.
3550 //
3551 // Below, we check the two conditions that only apply to
3552 // specialized non-type arguments, so skip any non-specialized
3553 // arguments.
3554 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003555 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003556 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003557 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003558 (Param->getIndex() != NTTP->getIndex() ||
3559 Param->getDepth() != NTTP->getDepth()))
3560 MirrorsPrimaryTemplate = false;
3561
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003562 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003563 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003564
3565 // C++ [temp.class.spec]p9:
3566 // Within the argument list of a class template partial
3567 // specialization, the following restrictions apply:
3568 // -- A partially specialized non-type argument expression
3569 // shall not involve a template parameter of the partial
3570 // specialization except when the argument expression is a
3571 // simple identifier.
3572 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003573 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003574 diag::err_dependent_non_type_arg_in_partial_spec)
3575 << ArgExpr->getSourceRange();
3576 return true;
3577 }
3578
3579 // -- The type of a template parameter corresponding to a
3580 // specialized non-type argument shall not be dependent on a
3581 // parameter of the specialization.
3582 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003583 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003584 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3585 << Param->getType()
3586 << ArgExpr->getSourceRange();
3587 Diag(Param->getLocation(), diag::note_template_param_here);
3588 return true;
3589 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003590
3591 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003592 }
3593
3594 return false;
3595}
3596
Douglas Gregorc854c662010-02-26 06:03:23 +00003597/// \brief Retrieve the previous declaration of the given declaration.
3598static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3599 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3600 return VD->getPreviousDeclaration();
3601 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3602 return FD->getPreviousDeclaration();
3603 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3604 return TD->getPreviousDeclaration();
3605 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3606 return TD->getPreviousDeclaration();
3607 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3608 return FTD->getPreviousDeclaration();
3609 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3610 return CTD->getPreviousDeclaration();
3611 return 0;
3612}
3613
John McCall48871652010-08-21 09:40:31 +00003614DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003615Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3616 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003617 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003618 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003619 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003620 SourceLocation TemplateNameLoc,
3621 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003622 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003623 SourceLocation RAngleLoc,
3624 AttributeList *Attr,
3625 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003626 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003627
Douglas Gregor67a65642009-02-17 23:15:12 +00003628 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003629 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003630 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003631 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3632
3633 if (!ClassTemplate) {
3634 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3635 << (Name.getAsTemplateDecl() &&
3636 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3637 return true;
3638 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003639
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003640 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003641 bool isPartialSpecialization = false;
3642
Douglas Gregorf47b9112009-02-25 22:02:03 +00003643 // Check the validity of the template headers that introduce this
3644 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003645 // FIXME: We probably shouldn't complain about these headers for
3646 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003647 bool Invalid = false;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003648 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003649 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3650 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003651 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003652 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003653 isExplicitSpecialization,
3654 Invalid);
3655 if (Invalid)
3656 return true;
3657
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003658 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3659 if (TemplateParams)
3660 --NumMatchedTemplateParamLists;
3661
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003662 if (TemplateParams && TemplateParams->size() > 0) {
3663 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003664
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003665 // C++ [temp.class.spec]p10:
3666 // The template parameter list of a specialization shall not
3667 // contain default template argument values.
3668 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3669 Decl *Param = TemplateParams->getParam(I);
3670 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3671 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003672 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003673 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003674 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003675 }
3676 } else if (NonTypeTemplateParmDecl *NTTP
3677 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3678 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003679 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003680 diag::err_default_arg_in_partial_spec)
3681 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003682 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003683 }
3684 } else {
3685 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003686 if (TTP->hasDefaultArgument()) {
3687 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003688 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003689 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003690 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00003691 }
3692 }
3693 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003694 } else if (TemplateParams) {
3695 if (TUK == TUK_Friend)
3696 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003697 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003698 SourceRange(TemplateParams->getTemplateLoc(),
3699 TemplateParams->getRAngleLoc()))
3700 << SourceRange(LAngleLoc, RAngleLoc);
3701 else
3702 isExplicitSpecialization = true;
3703 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003704 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003705 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003706 isExplicitSpecialization = true;
3707 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003708
Douglas Gregor67a65642009-02-17 23:15:12 +00003709 // Check that the specialization uses the same tag kind as the
3710 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003711 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3712 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00003713 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003714 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003715 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003716 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003717 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003718 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003719 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003720 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003721 diag::note_previous_use);
3722 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3723 }
3724
Douglas Gregorc40290e2009-03-09 23:48:35 +00003725 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003726 TemplateArgumentListInfo TemplateArgs;
3727 TemplateArgs.setLAngleLoc(LAngleLoc);
3728 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003729 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003730
Douglas Gregor67a65642009-02-17 23:15:12 +00003731 // Check that the template argument list is well-formed for this
3732 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003733 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3734 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003735 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3736 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003737 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003738
Mike Stump11289f42009-09-09 15:08:12 +00003739 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003740 ClassTemplate->getTemplateParameters()->size()) &&
3741 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003742
Douglas Gregor2373c592009-05-31 09:31:02 +00003743 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003744 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00003745 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003746 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003747 if (CheckClassTemplatePartialSpecializationArgs(
3748 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003749 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003750 return true;
3751
Douglas Gregor09a30232009-06-12 22:08:06 +00003752 if (MirrorsPrimaryTemplate) {
3753 // C++ [temp.class.spec]p9b3:
3754 //
Mike Stump11289f42009-09-09 15:08:12 +00003755 // -- The argument list of the specialization shall not be identical
3756 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003757 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003758 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003759 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003760 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003761 ClassTemplate->getIdentifier(),
3762 TemplateNameLoc,
3763 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003764 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003765 AS_none);
3766 }
3767
Douglas Gregor2208a292009-09-26 20:57:03 +00003768 // FIXME: Diagnose friend partial specializations
3769
Douglas Gregor92354b62010-02-09 00:37:32 +00003770 if (!Name.isDependent() &&
3771 !TemplateSpecializationType::anyDependentTemplateArguments(
3772 TemplateArgs.getArgumentArray(),
3773 TemplateArgs.size())) {
3774 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3775 << ClassTemplate->getDeclName();
3776 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00003777 }
3778 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003779
Douglas Gregor67a65642009-02-17 23:15:12 +00003780 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003781 ClassTemplateSpecializationDecl *PrevDecl = 0;
3782
3783 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003784 // FIXME: Template parameter list matters, too
Douglas Gregor2373c592009-05-31 09:31:02 +00003785 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003786 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
3787 Converted.flatSize(),
3788 InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00003789 else
3790 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003791 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
3792 Converted.flatSize(), InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003793
3794 ClassTemplateSpecializationDecl *Specialization = 0;
3795
Douglas Gregorf47b9112009-02-25 22:02:03 +00003796 // Check whether we can declare a class template specialization in
3797 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003798 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003799 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003800 TemplateNameLoc,
3801 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003802 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003803
Douglas Gregor15301382009-07-30 17:40:51 +00003804 // The canonical type
3805 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003806 if (PrevDecl &&
3807 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003808 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003809 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003810 // arguments was referenced but not declared, or we're only
3811 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003812 // declaration node as our own, updating its source location to
3813 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003814 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003815 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003816 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003817 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003818 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003819 // Build the canonical type that describes the converted template
3820 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003821 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3822 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003823 Converted.getFlatArguments(),
3824 Converted.flatSize());
3825
Douglas Gregor2373c592009-05-31 09:31:02 +00003826 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003827 ClassTemplatePartialSpecializationDecl *PrevPartial
3828 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00003829 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003830 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump11289f42009-09-09 15:08:12 +00003831 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00003832 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00003833 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003834 TemplateNameLoc,
3835 TemplateParams,
3836 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003837 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003838 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003839 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00003840 PrevPartial,
3841 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00003842 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00003843 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003844 Partial->setTemplateParameterListsInfo(Context,
3845 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003846 (TemplateParameterList**) TemplateParameterLists.release());
3847 }
Douglas Gregor2373c592009-05-31 09:31:02 +00003848
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003849 if (!PrevPartial)
3850 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00003851 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003852
Douglas Gregor21610382009-10-29 00:04:11 +00003853 // If we are providing an explicit specialization of a member class
3854 // template specialization, make a note of that.
3855 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3856 PrevPartial->setMemberSpecialization();
3857
Douglas Gregor91772d12009-06-13 00:26:55 +00003858 // Check that all of the template parameters of the class template
3859 // partial specialization are deducible from the template
3860 // arguments. If not, this class template partial specialization
3861 // will never be used.
3862 llvm::SmallVector<bool, 8> DeducibleParams;
3863 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003864 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003865 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003866 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003867 unsigned NumNonDeducible = 0;
3868 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3869 if (!DeducibleParams[I])
3870 ++NumNonDeducible;
3871
3872 if (NumNonDeducible) {
3873 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3874 << (NumNonDeducible > 1)
3875 << SourceRange(TemplateNameLoc, RAngleLoc);
3876 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3877 if (!DeducibleParams[I]) {
3878 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3879 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003880 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003881 diag::note_partial_spec_unused_parameter)
3882 << Param->getDeclName();
3883 else
Mike Stump11289f42009-09-09 15:08:12 +00003884 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003885 diag::note_partial_spec_unused_parameter)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003886 << "<anonymous>";
Douglas Gregor91772d12009-06-13 00:26:55 +00003887 }
3888 }
3889 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003890 } else {
3891 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003892 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003893 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00003894 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00003895 ClassTemplate->getDeclContext(),
3896 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003897 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003898 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003899 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00003900 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00003901 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003902 Specialization->setTemplateParameterListsInfo(Context,
3903 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003904 (TemplateParameterList**) TemplateParameterLists.release());
3905 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003906
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003907 if (!PrevDecl)
3908 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00003909
3910 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003911 }
3912
Douglas Gregor06db9f52009-10-12 20:18:28 +00003913 // C++ [temp.expl.spec]p6:
3914 // If a template, a member template or the member of a class template is
3915 // explicitly specialized then that specialization shall be declared
3916 // before the first use of that specialization that would cause an implicit
3917 // instantiation to take place, in every translation unit in which such a
3918 // use occurs; no diagnostic is required.
3919 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003920 bool Okay = false;
3921 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3922 // Is there any previous explicit specialization declaration?
3923 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3924 Okay = true;
3925 break;
3926 }
3927 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003928
Douglas Gregorc854c662010-02-26 06:03:23 +00003929 if (!Okay) {
3930 SourceRange Range(TemplateNameLoc, RAngleLoc);
3931 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3932 << Context.getTypeDeclType(Specialization) << Range;
3933
3934 Diag(PrevDecl->getPointOfInstantiation(),
3935 diag::note_instantiation_required_here)
3936 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003937 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003938 return true;
3939 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003940 }
3941
Douglas Gregor2208a292009-09-26 20:57:03 +00003942 // If this is not a friend, note that this is an explicit specialization.
3943 if (TUK != TUK_Friend)
3944 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003945
3946 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003947 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003948 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003949 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003950 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003951 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003952 Diag(Def->getLocation(), diag::note_previous_definition);
3953 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003954 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003955 }
3956 }
3957
Douglas Gregord56a91e2009-02-26 22:19:44 +00003958 // Build the fully-sugared type for this class template
3959 // specialization as the user wrote in the specialization
3960 // itself. This means that we'll pretty-print the type retrieved
3961 // from the specialization's declaration the way that the user
3962 // actually wrote the specialization, rather than formatting the
3963 // name based on the "canonical" representation used to store the
3964 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003965 TypeSourceInfo *WrittenTy
3966 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3967 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00003968 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003969 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregord890b732010-07-06 18:33:12 +00003970 if (TemplateParams)
3971 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnara8075c852010-06-12 07:44:57 +00003972 }
Douglas Gregorc40290e2009-03-09 23:48:35 +00003973 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003974
Douglas Gregor1e249f82009-02-25 22:18:32 +00003975 // C++ [temp.expl.spec]p9:
3976 // A template explicit specialization is in the scope of the
3977 // namespace in which the template was defined.
3978 //
3979 // We actually implement this paragraph where we set the semantic
3980 // context (in the creation of the ClassTemplateSpecializationDecl),
3981 // but we also maintain the lexical context where the actual
3982 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003983 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003984
Douglas Gregor67a65642009-02-17 23:15:12 +00003985 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003986 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003987 Specialization->startDefinition();
3988
Douglas Gregor2208a292009-09-26 20:57:03 +00003989 if (TUK == TUK_Friend) {
3990 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3991 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00003992 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00003993 /*FIXME:*/KWLoc);
3994 Friend->setAccess(AS_public);
3995 CurContext->addDecl(Friend);
3996 } else {
3997 // Add the specialization into its lexical context, so that it can
3998 // be seen when iterating through the list of declarations in that
3999 // context. However, specializations are not found by name lookup.
4000 CurContext->addDecl(Specialization);
4001 }
John McCall48871652010-08-21 09:40:31 +00004002 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00004003}
Douglas Gregor333489b2009-03-27 23:10:48 +00004004
John McCall48871652010-08-21 09:40:31 +00004005Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004006 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004007 Declarator &D) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004008 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4009}
4010
John McCall48871652010-08-21 09:40:31 +00004011Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004012 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004013 Declarator &D) {
Douglas Gregor17a7c122009-06-24 00:54:41 +00004014 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4015 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4016 "Not a function declarator!");
4017 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00004018
Douglas Gregor17a7c122009-06-24 00:54:41 +00004019 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004020 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004021 }
Mike Stump11289f42009-09-09 15:08:12 +00004022
Douglas Gregor17a7c122009-06-24 00:54:41 +00004023 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004024
John McCall48871652010-08-21 09:40:31 +00004025 Decl *DP = HandleDeclarator(ParentScope, D,
4026 move(TemplateParameterLists),
4027 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004028 if (FunctionTemplateDecl *FunctionTemplate
John McCall48871652010-08-21 09:40:31 +00004029 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump11289f42009-09-09 15:08:12 +00004030 return ActOnStartOfFunctionDef(FnBodyScope,
John McCall48871652010-08-21 09:40:31 +00004031 FunctionTemplate->getTemplatedDecl());
4032 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4033 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4034 return 0;
Douglas Gregor17a7c122009-06-24 00:54:41 +00004035}
4036
John McCall4f7ced62010-02-11 01:33:53 +00004037/// \brief Strips various properties off an implicit instantiation
4038/// that has just been explicitly specialized.
4039static void StripImplicitInstantiation(NamedDecl *D) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004040 D->dropAttrs();
John McCall4f7ced62010-02-11 01:33:53 +00004041
4042 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4043 FD->setInlineSpecified(false);
4044 }
4045}
4046
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004047/// \brief Diagnose cases where we have an explicit template specialization
4048/// before/after an explicit template instantiation, producing diagnostics
4049/// for those cases where they are required and determining whether the
4050/// new specialization/instantiation will have any effect.
4051///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004052/// \param NewLoc the location of the new explicit specialization or
4053/// instantiation.
4054///
4055/// \param NewTSK the kind of the new explicit specialization or instantiation.
4056///
4057/// \param PrevDecl the previous declaration of the entity.
4058///
4059/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4060///
4061/// \param PrevPointOfInstantiation if valid, indicates where the previus
4062/// declaration was instantiated (either implicitly or explicitly).
4063///
Abramo Bagnara8075c852010-06-12 07:44:57 +00004064/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004065/// specialization or instantiation has no effect and should be ignored.
4066///
4067/// \returns true if there was an error that should prevent the introduction of
4068/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004069bool
4070Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4071 TemplateSpecializationKind NewTSK,
4072 NamedDecl *PrevDecl,
4073 TemplateSpecializationKind PrevTSK,
4074 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004075 bool &HasNoEffect) {
4076 HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004077
4078 switch (NewTSK) {
4079 case TSK_Undeclared:
4080 case TSK_ImplicitInstantiation:
4081 assert(false && "Don't check implicit instantiations here");
4082 return false;
4083
4084 case TSK_ExplicitSpecialization:
4085 switch (PrevTSK) {
4086 case TSK_Undeclared:
4087 case TSK_ExplicitSpecialization:
4088 // Okay, we're just specializing something that is either already
4089 // explicitly specialized or has merely been mentioned without any
4090 // instantiation.
4091 return false;
4092
4093 case TSK_ImplicitInstantiation:
4094 if (PrevPointOfInstantiation.isInvalid()) {
4095 // The declaration itself has not actually been instantiated, so it is
4096 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004097 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004098 return false;
4099 }
4100 // Fall through
4101
4102 case TSK_ExplicitInstantiationDeclaration:
4103 case TSK_ExplicitInstantiationDefinition:
4104 assert((PrevTSK == TSK_ImplicitInstantiation ||
4105 PrevPointOfInstantiation.isValid()) &&
4106 "Explicit instantiation without point of instantiation?");
4107
4108 // C++ [temp.expl.spec]p6:
4109 // If a template, a member template or the member of a class template
4110 // is explicitly specialized then that specialization shall be declared
4111 // before the first use of that specialization that would cause an
4112 // implicit instantiation to take place, in every translation unit in
4113 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004114 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4115 // Is there any previous explicit specialization declaration?
4116 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4117 return false;
4118 }
4119
Douglas Gregor1d957a32009-10-27 18:42:08 +00004120 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004121 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004122 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004123 << (PrevTSK != TSK_ImplicitInstantiation);
4124
4125 return true;
4126 }
4127 break;
4128
4129 case TSK_ExplicitInstantiationDeclaration:
4130 switch (PrevTSK) {
4131 case TSK_ExplicitInstantiationDeclaration:
4132 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00004133 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004134 return false;
4135
4136 case TSK_Undeclared:
4137 case TSK_ImplicitInstantiation:
4138 // We're explicitly instantiating something that may have already been
4139 // implicitly instantiated; that's fine.
4140 return false;
4141
4142 case TSK_ExplicitSpecialization:
4143 // C++0x [temp.explicit]p4:
4144 // For a given set of template parameters, if an explicit instantiation
4145 // of a template appears after a declaration of an explicit
4146 // specialization for that template, the explicit instantiation has no
4147 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00004148 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004149 return false;
4150
4151 case TSK_ExplicitInstantiationDefinition:
4152 // C++0x [temp.explicit]p10:
4153 // If an entity is the subject of both an explicit instantiation
4154 // declaration and an explicit instantiation definition in the same
4155 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004156 Diag(NewLoc,
4157 diag::err_explicit_instantiation_declaration_after_definition);
4158 Diag(PrevPointOfInstantiation,
4159 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004160 assert(PrevPointOfInstantiation.isValid() &&
4161 "Explicit instantiation without point of instantiation?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00004162 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004163 return false;
4164 }
4165 break;
4166
4167 case TSK_ExplicitInstantiationDefinition:
4168 switch (PrevTSK) {
4169 case TSK_Undeclared:
4170 case TSK_ImplicitInstantiation:
4171 // We're explicitly instantiating something that may have already been
4172 // implicitly instantiated; that's fine.
4173 return false;
4174
4175 case TSK_ExplicitSpecialization:
4176 // C++ DR 259, C++0x [temp.explicit]p4:
4177 // For a given set of template parameters, if an explicit
4178 // instantiation of a template appears after a declaration of
4179 // an explicit specialization for that template, the explicit
4180 // instantiation has no effect.
4181 //
4182 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004183 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004184 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004185 if (!getLangOptions().CPlusPlus0x) {
4186 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004187 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004188 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004189 diag::note_previous_template_specialization);
4190 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004191 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004192 return false;
4193
4194 case TSK_ExplicitInstantiationDeclaration:
4195 // We're explicity instantiating a definition for something for which we
4196 // were previously asked to suppress instantiations. That's fine.
4197 return false;
4198
4199 case TSK_ExplicitInstantiationDefinition:
4200 // C++0x [temp.spec]p5:
4201 // For a given template and a given set of template-arguments,
4202 // - an explicit instantiation definition shall appear at most once
4203 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004204 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004205 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004206 Diag(PrevPointOfInstantiation,
4207 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004208 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004209 return false;
4210 }
4211 break;
4212 }
4213
4214 assert(false && "Missing specialization/instantiation case?");
4215
4216 return false;
4217}
4218
John McCallb9c78482010-04-08 09:05:18 +00004219/// \brief Perform semantic analysis for the given dependent function
4220/// template specialization. The only possible way to get a dependent
4221/// function template specialization is with a friend declaration,
4222/// like so:
4223///
4224/// template <class T> void foo(T);
4225/// template <class T> class A {
4226/// friend void foo<>(T);
4227/// };
4228///
4229/// There really isn't any useful analysis we can do here, so we
4230/// just store the information.
4231bool
4232Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4233 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4234 LookupResult &Previous) {
4235 // Remove anything from Previous that isn't a function template in
4236 // the correct context.
4237 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4238 LookupResult::Filter F = Previous.makeFilter();
4239 while (F.hasNext()) {
4240 NamedDecl *D = F.next()->getUnderlyingDecl();
4241 if (!isa<FunctionTemplateDecl>(D) ||
4242 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4243 F.erase();
4244 }
4245 F.done();
4246
4247 // Should this be diagnosed here?
4248 if (Previous.empty()) return true;
4249
4250 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4251 ExplicitTemplateArgs);
4252 return false;
4253}
4254
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004255/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004256/// specialization.
4257///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004258/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004259/// explicit function template specialization. On successful completion,
4260/// the function declaration \p FD will become a function template
4261/// specialization.
4262///
4263/// \param FD the function declaration, which will be updated to become a
4264/// function template specialization.
4265///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004266/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4267/// if any. Note that this may be valid info even when 0 arguments are
4268/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4269/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004270///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004271/// \param PrevDecl the set of declarations that may be specialized by
4272/// this function specialization.
4273bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004274Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004275 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004276 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004277 // The set of function template specializations that could match this
4278 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004279 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004280
4281 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00004282 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4283 I != E; ++I) {
4284 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4285 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004286 // Only consider templates found within the same semantic lookup scope as
4287 // FD.
4288 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4289 continue;
4290
4291 // C++ [temp.expl.spec]p11:
4292 // A trailing template-argument can be left unspecified in the
4293 // template-id naming an explicit function template specialization
4294 // provided it can be deduced from the function argument type.
4295 // Perform template argument deduction to determine whether we may be
4296 // specializing this template.
4297 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004298 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004299 FunctionDecl *Specialization = 0;
4300 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004301 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004302 FD->getType(),
4303 Specialization,
4304 Info)) {
4305 // FIXME: Template argument deduction failed; record why it failed, so
4306 // that we can provide nifty diagnostics.
4307 (void)TDK;
4308 continue;
4309 }
4310
4311 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004312 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004313 }
4314 }
4315
Douglas Gregor5de279c2009-09-26 03:41:46 +00004316 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004317 UnresolvedSetIterator Result
4318 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4319 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004320 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004321 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004322 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004323 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004324 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004325 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004326 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004327
4328 // Ignore access information; it doesn't figure into redeclaration checking.
4329 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004330 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004331
4332 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004333 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004334
4335 // If this is a friend declaration, then we're not really declaring
4336 // an explicit specialization.
4337 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004338
Douglas Gregor54888652009-10-07 00:13:32 +00004339 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004340 if (!isFriend &&
4341 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004342 Specialization->getPrimaryTemplate(),
4343 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004344 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004345 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004346
4347 // C++ [temp.expl.spec]p6:
4348 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004349 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004350 // before the first use of that specialization that would cause an implicit
4351 // instantiation to take place, in every translation unit in which such a
4352 // use occurs; no diagnostic is required.
4353 FunctionTemplateSpecializationInfo *SpecInfo
4354 = Specialization->getTemplateSpecializationInfo();
4355 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004356
Abramo Bagnara8075c852010-06-12 07:44:57 +00004357 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00004358 if (!isFriend &&
4359 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004360 TSK_ExplicitSpecialization,
4361 Specialization,
4362 SpecInfo->getTemplateSpecializationKind(),
4363 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004364 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004365 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004366
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004367 // Mark the prior declaration as an explicit specialization, so that later
4368 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004369 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00004370 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004371 MarkUnusedFileScopedDecl(Specialization);
4372 }
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004373
4374 // Turn the given function declaration into a function template
4375 // specialization, with the template arguments from the previous
4376 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004377 // Take copies of (semantic and syntactic) template argument lists.
4378 const TemplateArgumentList* TemplArgs = new (Context)
4379 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4380 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4381 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004382 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004383 TemplArgs, /*InsertPos=*/0,
4384 SpecInfo->getTemplateSpecializationKind(),
4385 TemplArgsAsWritten);
4386
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004387 // The "previous declaration" for this function template specialization is
4388 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004389 Previous.clear();
4390 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004391 return false;
4392}
4393
Douglas Gregor86d142a2009-10-08 07:24:58 +00004394/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004395/// specialization.
4396///
4397/// This routine performs all of the semantic analysis required for an
4398/// explicit member function specialization. On successful completion,
4399/// the function declaration \p FD will become a member function
4400/// specialization.
4401///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004402/// \param Member the member declaration, which will be updated to become a
4403/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004404///
John McCall1f82f242009-11-18 22:49:29 +00004405/// \param Previous the set of declarations, one of which may be specialized
4406/// by this function specialization; the set will be modified to contain the
4407/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004408bool
John McCall1f82f242009-11-18 22:49:29 +00004409Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004410 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004411
Douglas Gregor86d142a2009-10-08 07:24:58 +00004412 // Try to find the member we are instantiating.
4413 NamedDecl *Instantiation = 0;
4414 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004415 MemberSpecializationInfo *MSInfo = 0;
4416
John McCall1f82f242009-11-18 22:49:29 +00004417 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004418 // Nowhere to look anyway.
4419 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004420 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4421 I != E; ++I) {
4422 NamedDecl *D = (*I)->getUnderlyingDecl();
4423 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004424 if (Context.hasSameType(Function->getType(), Method->getType())) {
4425 Instantiation = Method;
4426 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004427 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004428 break;
4429 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004430 }
4431 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004432 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004433 VarDecl *PrevVar;
4434 if (Previous.isSingleResult() &&
4435 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004436 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004437 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004438 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004439 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004440 }
4441 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004442 CXXRecordDecl *PrevRecord;
4443 if (Previous.isSingleResult() &&
4444 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4445 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004446 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004447 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004448 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004449 }
4450
4451 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004452 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004453 // specializations are always out-of-line, the caller will complain about
4454 // this mismatch later.
4455 return false;
4456 }
John McCalle820e5e2010-04-13 20:37:33 +00004457
4458 // If this is a friend, just bail out here before we start turning
4459 // things into explicit specializations.
4460 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4461 // Preserve instantiation information.
4462 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4463 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4464 cast<CXXMethodDecl>(InstantiatedFrom),
4465 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4466 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4467 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4468 cast<CXXRecordDecl>(InstantiatedFrom),
4469 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4470 }
4471
4472 Previous.clear();
4473 Previous.addDecl(Instantiation);
4474 return false;
4475 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004476
Douglas Gregor86d142a2009-10-08 07:24:58 +00004477 // Make sure that this is a specialization of a member.
4478 if (!InstantiatedFrom) {
4479 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4480 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004481 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4482 return true;
4483 }
4484
Douglas Gregor06db9f52009-10-12 20:18:28 +00004485 // C++ [temp.expl.spec]p6:
4486 // If a template, a member template or the member of a class template is
4487 // explicitly specialized then that spe- cialization shall be declared
4488 // before the first use of that specialization that would cause an implicit
4489 // instantiation to take place, in every translation unit in which such a
4490 // use occurs; no diagnostic is required.
4491 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004492
Abramo Bagnara8075c852010-06-12 07:44:57 +00004493 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00004494 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4495 TSK_ExplicitSpecialization,
4496 Instantiation,
4497 MSInfo->getTemplateSpecializationKind(),
4498 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004499 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004500 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004501
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004502 // Check the scope of this explicit specialization.
4503 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004504 InstantiatedFrom,
4505 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004506 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004507 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004508
Douglas Gregor86d142a2009-10-08 07:24:58 +00004509 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004510 // the original declaration to note that it is an explicit specialization
4511 // (if it was previously an implicit instantiation). This latter step
4512 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004513 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004514 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4515 if (InstantiationFunction->getTemplateSpecializationKind() ==
4516 TSK_ImplicitInstantiation) {
4517 InstantiationFunction->setTemplateSpecializationKind(
4518 TSK_ExplicitSpecialization);
4519 InstantiationFunction->setLocation(Member->getLocation());
4520 }
4521
Douglas Gregor86d142a2009-10-08 07:24:58 +00004522 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4523 cast<CXXMethodDecl>(InstantiatedFrom),
4524 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004525 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004526 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004527 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4528 if (InstantiationVar->getTemplateSpecializationKind() ==
4529 TSK_ImplicitInstantiation) {
4530 InstantiationVar->setTemplateSpecializationKind(
4531 TSK_ExplicitSpecialization);
4532 InstantiationVar->setLocation(Member->getLocation());
4533 }
4534
Douglas Gregor86d142a2009-10-08 07:24:58 +00004535 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4536 cast<VarDecl>(InstantiatedFrom),
4537 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004538 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004539 } else {
4540 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004541 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4542 if (InstantiationClass->getTemplateSpecializationKind() ==
4543 TSK_ImplicitInstantiation) {
4544 InstantiationClass->setTemplateSpecializationKind(
4545 TSK_ExplicitSpecialization);
4546 InstantiationClass->setLocation(Member->getLocation());
4547 }
4548
Douglas Gregor86d142a2009-10-08 07:24:58 +00004549 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004550 cast<CXXRecordDecl>(InstantiatedFrom),
4551 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004552 }
4553
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004554 // Save the caller the trouble of having to figure out which declaration
4555 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004556 Previous.clear();
4557 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004558 return false;
4559}
4560
Douglas Gregore47f5a72009-10-14 23:41:34 +00004561/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004562///
4563/// \returns true if a serious error occurs, false otherwise.
4564static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00004565 SourceLocation InstLoc,
4566 bool WasQualifiedName) {
4567 DeclContext *ExpectedContext
4568 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4569 DeclContext *CurContext = S.CurContext->getLookupContext();
4570
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004571 if (CurContext->isRecord()) {
4572 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4573 << D;
4574 return true;
4575 }
4576
Douglas Gregore47f5a72009-10-14 23:41:34 +00004577 // C++0x [temp.explicit]p2:
4578 // An explicit instantiation shall appear in an enclosing namespace of its
4579 // template.
4580 //
4581 // This is DR275, which we do not retroactively apply to C++98/03.
4582 if (S.getLangOptions().CPlusPlus0x &&
4583 !CurContext->Encloses(ExpectedContext)) {
4584 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004585 S.Diag(InstLoc,
4586 S.getLangOptions().CPlusPlus0x?
4587 diag::err_explicit_instantiation_out_of_scope
4588 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004589 << D << NS;
4590 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004591 S.Diag(InstLoc,
4592 S.getLangOptions().CPlusPlus0x?
4593 diag::err_explicit_instantiation_must_be_global
4594 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004595 << D;
4596 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004597 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004598 }
4599
4600 // C++0x [temp.explicit]p2:
4601 // If the name declared in the explicit instantiation is an unqualified
4602 // name, the explicit instantiation shall appear in the namespace where
4603 // its template is declared or, if that namespace is inline (7.3.1), any
4604 // namespace from its enclosing namespace set.
4605 if (WasQualifiedName)
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004606 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004607
4608 if (CurContext->Equals(ExpectedContext))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004609 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004610
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004611 S.Diag(InstLoc,
4612 S.getLangOptions().CPlusPlus0x?
4613 diag::err_explicit_instantiation_unqualified_wrong_namespace
4614 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004615 << D << ExpectedContext;
4616 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004617 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004618}
4619
4620/// \brief Determine whether the given scope specifier has a template-id in it.
4621static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4622 if (!SS.isSet())
4623 return false;
4624
4625 // C++0x [temp.explicit]p2:
4626 // If the explicit instantiation is for a member function, a member class
4627 // or a static data member of a class template specialization, the name of
4628 // the class template specialization in the qualified-id for the member
4629 // name shall be a simple-template-id.
4630 //
4631 // C++98 has the same restriction, just worded differently.
4632 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4633 NNS; NNS = NNS->getPrefix())
4634 if (Type *T = NNS->getAsType())
4635 if (isa<TemplateSpecializationType>(T))
4636 return true;
4637
4638 return false;
4639}
4640
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004641// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00004642DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004643Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004644 SourceLocation ExternLoc,
4645 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004646 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004647 SourceLocation KWLoc,
4648 const CXXScopeSpec &SS,
4649 TemplateTy TemplateD,
4650 SourceLocation TemplateNameLoc,
4651 SourceLocation LAngleLoc,
4652 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004653 SourceLocation RAngleLoc,
4654 AttributeList *Attr) {
4655 // Find the class template we're specializing
4656 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004657 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004658 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4659
4660 // Check that the specialization uses the same tag kind as the
4661 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004662 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4663 assert(Kind != TTK_Enum &&
4664 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004665 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004666 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004667 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004668 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004669 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004670 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004671 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004672 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004673 diag::note_previous_use);
4674 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4675 }
4676
Douglas Gregore47f5a72009-10-14 23:41:34 +00004677 // C++0x [temp.explicit]p2:
4678 // There are two forms of explicit instantiation: an explicit instantiation
4679 // definition and an explicit instantiation declaration. An explicit
4680 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004681 TemplateSpecializationKind TSK
4682 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4683 : TSK_ExplicitInstantiationDeclaration;
4684
Douglas Gregora1f49972009-05-13 00:25:59 +00004685 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004686 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004687 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004688
4689 // Check that the template argument list is well-formed for this
4690 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004691 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4692 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004693 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4694 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004695 return true;
4696
Mike Stump11289f42009-09-09 15:08:12 +00004697 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004698 ClassTemplate->getTemplateParameters()->size()) &&
4699 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004700
Douglas Gregora1f49972009-05-13 00:25:59 +00004701 // Find the class template specialization declaration that
4702 // corresponds to these arguments.
Douglas Gregora1f49972009-05-13 00:25:59 +00004703 void *InsertPos = 0;
4704 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004705 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4706 Converted.flatSize(), InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004707
Abramo Bagnara8075c852010-06-12 07:44:57 +00004708 TemplateSpecializationKind PrevDecl_TSK
4709 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4710
Douglas Gregor54888652009-10-07 00:13:32 +00004711 // C++0x [temp.explicit]p2:
4712 // [...] An explicit instantiation shall appear in an enclosing
4713 // namespace of its template. [...]
4714 //
4715 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004716 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4717 SS.isSet()))
4718 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004719
Douglas Gregora1f49972009-05-13 00:25:59 +00004720 ClassTemplateSpecializationDecl *Specialization = 0;
4721
Douglas Gregor0681a352009-11-25 06:01:46 +00004722 bool ReusedDecl = false;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004723 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004724 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00004725 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004726 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004727 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004728 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00004729 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00004730
Abramo Bagnara8075c852010-06-12 07:44:57 +00004731 // Even though HasNoEffect == true means that this explicit instantiation
4732 // has no effect on semantics, we go on to put its syntax in the AST.
4733
4734 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4735 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004736 // Since the only prior class template specialization with these
4737 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00004738 // declaration node as our own, updating the source location
4739 // for the template name to reflect our new declaration.
4740 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004741 Specialization = PrevDecl;
4742 Specialization->setLocation(TemplateNameLoc);
4743 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004744 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004745 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004746 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004747
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004748 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004749 // Create a new class template specialization declaration node for
4750 // this explicit specialization.
4751 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004752 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00004753 ClassTemplate->getDeclContext(),
4754 TemplateNameLoc,
4755 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004756 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004757 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004758
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004759 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00004760 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004761 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004762 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004763 }
4764
4765 // Build the fully-sugared type for this explicit instantiation as
4766 // the user wrote in the explicit instantiation itself. This means
4767 // that we'll pretty-print the type retrieved from the
4768 // specialization's declaration the way that the user actually wrote
4769 // the explicit instantiation, rather than formatting the name based
4770 // on the "canonical" representation used to store the template
4771 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004772 TypeSourceInfo *WrittenTy
4773 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4774 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004775 Context.getTypeDeclType(Specialization));
4776 Specialization->setTypeAsWritten(WrittenTy);
4777 TemplateArgsIn.release();
4778
Abramo Bagnara8075c852010-06-12 07:44:57 +00004779 // Set source locations for keywords.
4780 Specialization->setExternLoc(ExternLoc);
4781 Specialization->setTemplateKeywordLoc(TemplateLoc);
4782
4783 // Add the explicit instantiation into its lexical context. However,
4784 // since explicit instantiations are never found by name lookup, we
4785 // just put it into the declaration context directly.
4786 Specialization->setLexicalDeclContext(CurContext);
4787 CurContext->addDecl(Specialization);
4788
4789 // Syntax is now OK, so return if it has no other effect on semantics.
4790 if (HasNoEffect) {
4791 // Set the template specialization kind.
4792 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00004793 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00004794 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004795
4796 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004797 // A definition of a class template or class member template
4798 // shall be in scope at the point of the explicit instantiation of
4799 // the class template or class member template.
4800 //
4801 // This check comes when we actually try to perform the
4802 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004803 ClassTemplateSpecializationDecl *Def
4804 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004805 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004806 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004807 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004808 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00004809 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004810 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
4811 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004812
Douglas Gregor1d957a32009-10-27 18:42:08 +00004813 // Instantiate the members of this class template specialization.
4814 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004815 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004816 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004817 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4818
4819 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4820 // TSK_ExplicitInstantiationDefinition
4821 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4822 TSK == TSK_ExplicitInstantiationDefinition)
4823 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004824
Douglas Gregor12e49d32009-10-15 22:53:21 +00004825 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004826 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004827
Abramo Bagnara8075c852010-06-12 07:44:57 +00004828 // Set the template specialization kind.
4829 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00004830 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00004831}
4832
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004833// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00004834DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004835Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004836 SourceLocation ExternLoc,
4837 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004838 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004839 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004840 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004841 IdentifierInfo *Name,
4842 SourceLocation NameLoc,
4843 AttributeList *Attr) {
4844
Douglas Gregord6ab8742009-05-28 23:31:59 +00004845 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004846 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00004847 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00004848 KWLoc, SS, Name, NameLoc, Attr, AS_none,
4849 MultiTemplateParamsArg(*this, 0, 0),
4850 Owned, IsDependent);
John McCall7f41d982009-09-11 04:59:25 +00004851 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4852
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004853 if (!TagD)
4854 return true;
4855
John McCall48871652010-08-21 09:40:31 +00004856 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004857 if (Tag->isEnum()) {
4858 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4859 << Context.getTypeDeclType(Tag);
4860 return true;
4861 }
4862
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004863 if (Tag->isInvalidDecl())
4864 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004865
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004866 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4867 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4868 if (!Pattern) {
4869 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4870 << Context.getTypeDeclType(Record);
4871 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4872 return true;
4873 }
4874
Douglas Gregore47f5a72009-10-14 23:41:34 +00004875 // C++0x [temp.explicit]p2:
4876 // If the explicit instantiation is for a class or member class, the
4877 // elaborated-type-specifier in the declaration shall include a
4878 // simple-template-id.
4879 //
4880 // C++98 has the same restriction, just worded differently.
4881 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00004882 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004883 << Record << SS.getRange();
4884
4885 // C++0x [temp.explicit]p2:
4886 // There are two forms of explicit instantiation: an explicit instantiation
4887 // definition and an explicit instantiation declaration. An explicit
4888 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004889 TemplateSpecializationKind TSK
4890 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4891 : TSK_ExplicitInstantiationDeclaration;
4892
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004893 // C++0x [temp.explicit]p2:
4894 // [...] An explicit instantiation shall appear in an enclosing
4895 // namespace of its template. [...]
4896 //
4897 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004898 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004899
4900 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004901 CXXRecordDecl *PrevDecl
4902 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004903 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004904 PrevDecl = Record;
4905 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004906 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00004907 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004908 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004909 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004910 PrevDecl,
4911 MSInfo->getTemplateSpecializationKind(),
4912 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004913 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004914 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004915 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004916 return TagD;
4917 }
4918
Douglas Gregor12e49d32009-10-15 22:53:21 +00004919 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004920 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004921 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004922 // C++ [temp.explicit]p3:
4923 // A definition of a member class of a class template shall be in scope
4924 // at the point of an explicit instantiation of the member class.
4925 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004926 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004927 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004928 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4929 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004930 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4931 << Pattern;
4932 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004933 } else {
4934 if (InstantiateClass(NameLoc, Record, Def,
4935 getTemplateInstantiationArgs(Record),
4936 TSK))
4937 return true;
4938
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004939 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004940 if (!RecordDef)
4941 return true;
4942 }
4943 }
4944
4945 // Instantiate all of the members of the class.
4946 InstantiateClassMembers(NameLoc, RecordDef,
4947 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004948
Douglas Gregor88d292c2010-05-13 16:44:06 +00004949 if (TSK == TSK_ExplicitInstantiationDefinition)
4950 MarkVTableUsed(NameLoc, RecordDef, true);
4951
Mike Stump87c57ac2009-05-16 07:39:55 +00004952 // FIXME: We don't have any representation for explicit instantiations of
4953 // member classes. Such a representation is not needed for compilation, but it
4954 // should be available for clients that want to see all of the declarations in
4955 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004956 return TagD;
4957}
4958
John McCallfaf5fb42010-08-26 23:41:50 +00004959DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4960 SourceLocation ExternLoc,
4961 SourceLocation TemplateLoc,
4962 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004963 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004964 // TODO: check if/when DNInfo should replace Name.
4965 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4966 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00004967 if (!Name) {
4968 if (!D.isInvalidType())
4969 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4970 diag::err_explicit_instantiation_requires_name)
4971 << D.getDeclSpec().getSourceRange()
4972 << D.getSourceRange();
4973
4974 return true;
4975 }
4976
4977 // The scope passed in may not be a decl scope. Zip up the scope tree until
4978 // we find one that is.
4979 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4980 (S->getFlags() & Scope::TemplateParamScope) != 0)
4981 S = S->getParent();
4982
4983 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00004984 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
4985 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00004986 if (R.isNull())
4987 return true;
4988
4989 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4990 // Cannot explicitly instantiate a typedef.
4991 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4992 << Name;
4993 return true;
4994 }
4995
Douglas Gregor3c74d412009-10-14 20:14:33 +00004996 // C++0x [temp.explicit]p1:
4997 // [...] An explicit instantiation of a function template shall not use the
4998 // inline or constexpr specifiers.
4999 // Presumably, this also applies to member functions of class templates as
5000 // well.
5001 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5002 Diag(D.getDeclSpec().getInlineSpecLoc(),
5003 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00005004 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00005005
5006 // FIXME: check for constexpr specifier.
5007
Douglas Gregore47f5a72009-10-14 23:41:34 +00005008 // C++0x [temp.explicit]p2:
5009 // There are two forms of explicit instantiation: an explicit instantiation
5010 // definition and an explicit instantiation declaration. An explicit
5011 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00005012 TemplateSpecializationKind TSK
5013 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5014 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005015
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005016 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005017 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00005018
5019 if (!R->isFunctionType()) {
5020 // C++ [temp.explicit]p1:
5021 // A [...] static data member of a class template can be explicitly
5022 // instantiated from the member definition associated with its class
5023 // template.
John McCall27b18f82009-11-17 02:14:36 +00005024 if (Previous.isAmbiguous())
5025 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00005026
John McCall67c00872009-12-02 08:25:40 +00005027 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005028 if (!Prev || !Prev->isStaticDataMember()) {
5029 // We expect to see a data data member here.
5030 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5031 << Name;
5032 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5033 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005034 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005035 return true;
5036 }
5037
5038 if (!Prev->getInstantiatedFromStaticDataMember()) {
5039 // FIXME: Check for explicit specialization?
5040 Diag(D.getIdentifierLoc(),
5041 diag::err_explicit_instantiation_data_member_not_instantiated)
5042 << Prev;
5043 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5044 // FIXME: Can we provide a note showing where this was declared?
5045 return true;
5046 }
5047
Douglas Gregore47f5a72009-10-14 23:41:34 +00005048 // C++0x [temp.explicit]p2:
5049 // If the explicit instantiation is for a member function, a member class
5050 // or a static data member of a class template specialization, the name of
5051 // the class template specialization in the qualified-id for the member
5052 // name shall be a simple-template-id.
5053 //
5054 // C++98 has the same restriction, just worded differently.
5055 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5056 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005057 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005058 << Prev << D.getCXXScopeSpec().getRange();
5059
5060 // Check the scope of this explicit instantiation.
5061 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5062
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005063 // Verify that it is okay to explicitly instantiate here.
5064 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5065 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00005066 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005067 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005068 MSInfo->getTemplateSpecializationKind(),
5069 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005070 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005071 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005072 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005073 return (Decl*) 0;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005074
Douglas Gregor450f00842009-09-25 18:43:00 +00005075 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005076 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005077 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005078 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregor450f00842009-09-25 18:43:00 +00005079
5080 // FIXME: Create an ExplicitInstantiation node?
John McCall48871652010-08-21 09:40:31 +00005081 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005082 }
5083
Douglas Gregor0e876e02009-09-25 23:53:26 +00005084 // If the declarator is a template-id, translate the parser's template
5085 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005086 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005087 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005088 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5089 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005090 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5091 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005092 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5093 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005094 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005095 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005096 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005097 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005098 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005099
Douglas Gregor450f00842009-09-25 18:43:00 +00005100 // C++ [temp.explicit]p1:
5101 // A [...] function [...] can be explicitly instantiated from its template.
5102 // A member function [...] of a class template can be explicitly
5103 // instantiated from the member definition associated with its class
5104 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005105 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005106 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5107 P != PEnd; ++P) {
5108 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005109 if (!HasExplicitTemplateArgs) {
5110 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5111 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5112 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005113
John McCall58cc69d2010-01-27 01:50:18 +00005114 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005115 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5116 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005117 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005118 }
5119 }
5120
5121 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5122 if (!FunTmpl)
5123 continue;
5124
John McCallbc077cf2010-02-08 23:07:23 +00005125 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005126 FunctionDecl *Specialization = 0;
5127 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005128 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005129 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005130 R, Specialization, Info)) {
5131 // FIXME: Keep track of almost-matches?
5132 (void)TDK;
5133 continue;
5134 }
5135
John McCall58cc69d2010-01-27 01:50:18 +00005136 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005137 }
5138
5139 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005140 UnresolvedSetIterator Result
5141 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005142 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005143 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5144 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5145 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005146
John McCall58cc69d2010-01-27 01:50:18 +00005147 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005148 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005149
5150 // Ignore access control bits, we don't need them for redeclaration checking.
5151 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005152
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005153 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005154 Diag(D.getIdentifierLoc(),
5155 diag::err_explicit_instantiation_member_function_not_instantiated)
5156 << Specialization
5157 << (Specialization->getTemplateSpecializationKind() ==
5158 TSK_ExplicitSpecialization);
5159 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5160 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005161 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005162
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005163 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005164 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5165 PrevDecl = Specialization;
5166
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005167 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005168 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005169 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005170 PrevDecl,
5171 PrevDecl->getTemplateSpecializationKind(),
5172 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005173 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005174 return true;
5175
5176 // FIXME: We may still want to build some representation of this
5177 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00005178 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005179 return (Decl*) 0;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005180 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005181
5182 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005183
5184 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005185 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005186
Douglas Gregore47f5a72009-10-14 23:41:34 +00005187 // C++0x [temp.explicit]p2:
5188 // If the explicit instantiation is for a member function, a member class
5189 // or a static data member of a class template specialization, the name of
5190 // the class template specialization in the qualified-id for the member
5191 // name shall be a simple-template-id.
5192 //
5193 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005194 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005195 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005196 D.getCXXScopeSpec().isSet() &&
5197 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5198 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005199 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005200 << Specialization << D.getCXXScopeSpec().getRange();
5201
5202 CheckExplicitInstantiationScope(*this,
5203 FunTmpl? (NamedDecl *)FunTmpl
5204 : Specialization->getInstantiatedFromMemberFunction(),
5205 D.getIdentifierLoc(),
5206 D.getCXXScopeSpec().isSet());
5207
Douglas Gregor450f00842009-09-25 18:43:00 +00005208 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCall48871652010-08-21 09:40:31 +00005209 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005210}
5211
John McCallfaf5fb42010-08-26 23:41:50 +00005212TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005213Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5214 const CXXScopeSpec &SS, IdentifierInfo *Name,
5215 SourceLocation TagLoc, SourceLocation NameLoc) {
5216 // This has to hold, because SS is expected to be defined.
5217 assert(Name && "Expected a name in a dependent tag");
5218
5219 NestedNameSpecifier *NNS
5220 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5221 if (!NNS)
5222 return true;
5223
Abramo Bagnara6150c882010-05-11 21:36:43 +00005224 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005225
Douglas Gregorba41d012010-04-24 16:38:41 +00005226 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5227 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005228 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005229 return true;
5230 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005231
5232 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallba7bf592010-08-24 05:47:05 +00005233 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCall7f41d982009-09-11 04:59:25 +00005234}
5235
John McCallfaf5fb42010-08-26 23:41:50 +00005236TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005237Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5238 const CXXScopeSpec &SS, const IdentifierInfo &II,
5239 SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005240 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005241 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5242 if (!NNS)
5243 return true;
5244
Douglas Gregorf7d77712010-06-16 22:31:08 +00005245 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5246 !getLangOptions().CPlusPlus0x)
5247 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5248 << FixItHint::CreateRemoval(TypenameLoc);
5249
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005250 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005251 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005252 if (T.isNull())
5253 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005254
5255 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5256 if (isa<DependentNameType>(T)) {
5257 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005258 TL.setKeywordLoc(TypenameLoc);
5259 TL.setQualifierRange(SS.getRange());
5260 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005261 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005262 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005263 TL.setKeywordLoc(TypenameLoc);
5264 TL.setQualifierRange(SS.getRange());
5265 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005266 }
5267
John McCallba7bf592010-08-24 05:47:05 +00005268 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00005269}
5270
John McCallfaf5fb42010-08-26 23:41:50 +00005271TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005272Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5273 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallba7bf592010-08-24 05:47:05 +00005274 ParsedType Ty) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00005275 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5276 !getLangOptions().CPlusPlus0x)
5277 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5278 << FixItHint::CreateRemoval(TypenameLoc);
5279
John McCallf7bcc812010-05-28 23:32:21 +00005280 TypeSourceInfo *InnerTSI = 0;
5281 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCallf7bcc812010-05-28 23:32:21 +00005282
5283 assert(isa<TemplateSpecializationType>(T) &&
5284 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005285
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005286 if (computeDeclContext(SS, false)) {
5287 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005288 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005289 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005290
5291 // Push the inner type, preserving its source locations if possible.
5292 TypeLocBuilder Builder;
5293 if (InnerTSI)
5294 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5295 else
5296 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5297
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005298 /* Note: NNS already embedded in template specialization type T. */
5299 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCallf7bcc812010-05-28 23:32:21 +00005300 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5301 TL.setKeywordLoc(TypenameLoc);
5302 TL.setQualifierRange(SS.getRange());
5303
5304 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallba7bf592010-08-24 05:47:05 +00005305 return CreateParsedType(T, TSI);
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005306 }
Mike Stump11289f42009-09-09 15:08:12 +00005307
John McCallc392f372010-06-11 00:33:02 +00005308 // TODO: it's really silly that we make a template specialization
5309 // type earlier only to drop it again here.
5310 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5311 DependentTemplateName *DTN =
5312 TST->getTemplateName().getAsDependentTemplateName();
5313 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005314 assert(DTN->getQualifier()
5315 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5316 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5317 DTN->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00005318 DTN->getIdentifier(),
5319 TST->getNumArgs(),
5320 TST->getArgs());
John McCall99b2fe52010-04-29 23:50:39 +00005321 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCallc392f372010-06-11 00:33:02 +00005322 DependentTemplateSpecializationTypeLoc TL =
5323 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5324 if (InnerTSI) {
5325 TemplateSpecializationTypeLoc TSTL =
5326 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5327 TL.setLAngleLoc(TSTL.getLAngleLoc());
5328 TL.setRAngleLoc(TSTL.getRAngleLoc());
5329 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5330 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5331 } else {
5332 TL.initializeLocal(SourceLocation());
5333 }
John McCallf7bcc812010-05-28 23:32:21 +00005334 TL.setKeywordLoc(TypenameLoc);
5335 TL.setQualifierRange(SS.getRange());
John McCallba7bf592010-08-24 05:47:05 +00005336 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00005337}
5338
Douglas Gregor333489b2009-03-27 23:10:48 +00005339/// \brief Build the type that describes a C++ typename specifier,
5340/// e.g., "typename T::type".
5341QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005342Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5343 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005344 SourceLocation KeywordLoc, SourceRange NNSRange,
5345 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005346 CXXScopeSpec SS;
5347 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005348 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005349
John McCall0b66eb32010-05-01 00:40:08 +00005350 DeclContext *Ctx = computeDeclContext(SS);
5351 if (!Ctx) {
5352 // If the nested-name-specifier is dependent and couldn't be
5353 // resolved to a type, build a typename type.
5354 assert(NNS->isDependent());
5355 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005356 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005357
John McCall0b66eb32010-05-01 00:40:08 +00005358 // If the nested-name-specifier refers to the current instantiation,
5359 // the "typename" keyword itself is superfluous. In C++03, the
5360 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5361 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00005362 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005363
John McCall0b66eb32010-05-01 00:40:08 +00005364 if (RequireCompleteDeclContext(SS, Ctx))
5365 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005366
5367 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005368 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005369 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005370 unsigned DiagID = 0;
5371 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005372 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005373 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005374 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005375 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005376
5377 case LookupResult::NotFoundInCurrentInstantiation:
5378 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005379 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005380
5381 case LookupResult::Found:
Douglas Gregorf7d77712010-06-16 22:31:08 +00005382 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005383 // We found a type. Build an ElaboratedType, since the
5384 // typename-specifier was just sugar.
5385 return Context.getElaboratedType(ETK_Typename, NNS,
5386 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005387 }
5388
5389 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005390 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005391 break;
5392
John McCalle61f2ba2009-11-18 02:36:19 +00005393 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005394 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005395 return QualType();
5396
Douglas Gregor333489b2009-03-27 23:10:48 +00005397 case LookupResult::FoundOverloaded:
5398 DiagID = diag::err_typename_nested_not_type;
5399 Referenced = *Result.begin();
5400 break;
5401
John McCall6538c932009-10-10 05:48:19 +00005402 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005403 return QualType();
5404 }
5405
5406 // If we get here, it's because name lookup did not find a
5407 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005408 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5409 IILoc);
5410 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005411 if (Referenced)
5412 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5413 << Name;
5414 return QualType();
5415}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005416
5417namespace {
5418 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005419 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005420 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005421 SourceLocation Loc;
5422 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005423
Douglas Gregor15acfb92009-08-06 16:20:37 +00005424 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005425 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5426
Mike Stump11289f42009-09-09 15:08:12 +00005427 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005428 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005429 DeclarationName Entity)
5430 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005431 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005432
5433 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005434 /// transformed.
5435 ///
5436 /// For the purposes of type reconstruction, a type has already been
5437 /// transformed if it is NULL or if it is not dependent.
5438 bool AlreadyTransformed(QualType T) {
5439 return T.isNull() || !T->isDependentType();
5440 }
Mike Stump11289f42009-09-09 15:08:12 +00005441
5442 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005443 /// rebuilt.
5444 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005445
Douglas Gregor15acfb92009-08-06 16:20:37 +00005446 /// \brief Returns the name of the entity whose type is being rebuilt.
5447 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005448
Douglas Gregoref6ab412009-10-27 06:26:26 +00005449 /// \brief Sets the "base" location and entity when that
5450 /// information is known based on another transformation.
5451 void setBase(SourceLocation Loc, DeclarationName Entity) {
5452 this->Loc = Loc;
5453 this->Entity = Entity;
5454 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00005455 };
5456}
5457
Douglas Gregor15acfb92009-08-06 16:20:37 +00005458/// \brief Rebuilds a type within the context of the current instantiation.
5459///
Mike Stump11289f42009-09-09 15:08:12 +00005460/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005461/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005462/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005463/// partial specialization thereof). This routine will rebuild that type now
5464/// that we have entered the declarator's scope, which may produce different
5465/// canonical types, e.g.,
5466///
5467/// \code
5468/// template<typename T>
5469/// struct X {
5470/// typedef T* pointer;
5471/// pointer data();
5472/// };
5473///
5474/// template<typename T>
5475/// typename X<T>::pointer X<T>::data() { ... }
5476/// \endcode
5477///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005478/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005479/// since we do not know that we can look into X<T> when we parsed the type.
5480/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005481/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005482/// as the canonical type of T*, allowing the return types of the out-of-line
5483/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005484TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5485 SourceLocation Loc,
5486 DeclarationName Name) {
5487 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005488 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005489
Douglas Gregor15acfb92009-08-06 16:20:37 +00005490 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5491 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005492}
Douglas Gregorbe999392009-09-15 16:23:51 +00005493
John McCalldadc5752010-08-24 06:29:42 +00005494ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00005495 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5496 DeclarationName());
5497 return Rebuilder.TransformExpr(E);
5498}
5499
John McCall99b2fe52010-04-29 23:50:39 +00005500bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5501 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005502
5503 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5504 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5505 DeclarationName());
5506 NestedNameSpecifier *Rebuilt =
5507 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005508 if (!Rebuilt) return true;
5509
5510 SS.setScopeRep(Rebuilt);
5511 return false;
John McCall2408e322010-04-27 00:57:59 +00005512}
5513
Douglas Gregorbe999392009-09-15 16:23:51 +00005514/// \brief Produces a formatted string that describes the binding of
5515/// template parameters to template arguments.
5516std::string
5517Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5518 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005519 // FIXME: For variadic templates, we'll need to get the structured list.
5520 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5521 Args.flat_size());
5522}
5523
5524std::string
5525Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5526 const TemplateArgument *Args,
5527 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005528 std::string Result;
5529
Douglas Gregore62e6a02009-11-11 19:13:48 +00005530 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005531 return Result;
5532
5533 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005534 if (I >= NumArgs)
5535 break;
5536
Douglas Gregorbe999392009-09-15 16:23:51 +00005537 if (I == 0)
5538 Result += "[with ";
5539 else
5540 Result += ", ";
5541
5542 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5543 Result += Id->getName();
5544 } else {
5545 Result += '$';
5546 Result += llvm::utostr(I);
5547 }
5548
5549 Result += " = ";
5550
5551 switch (Args[I].getKind()) {
5552 case TemplateArgument::Null:
5553 Result += "<no value>";
5554 break;
5555
5556 case TemplateArgument::Type: {
5557 std::string TypeStr;
5558 Args[I].getAsType().getAsStringInternal(TypeStr,
5559 Context.PrintingPolicy);
5560 Result += TypeStr;
5561 break;
5562 }
5563
5564 case TemplateArgument::Declaration: {
5565 bool Unnamed = true;
5566 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5567 if (ND->getDeclName()) {
5568 Unnamed = false;
5569 Result += ND->getNameAsString();
5570 }
5571 }
5572
5573 if (Unnamed) {
5574 Result += "<anonymous>";
5575 }
5576 break;
5577 }
5578
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005579 case TemplateArgument::Template: {
5580 std::string Str;
5581 llvm::raw_string_ostream OS(Str);
5582 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5583 Result += OS.str();
5584 break;
5585 }
5586
Douglas Gregorbe999392009-09-15 16:23:51 +00005587 case TemplateArgument::Integral: {
5588 Result += Args[I].getAsIntegral()->toString(10);
5589 break;
5590 }
5591
5592 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005593 // FIXME: This is non-optimal, since we're regurgitating the
5594 // expression we were given.
5595 std::string Str;
5596 {
5597 llvm::raw_string_ostream OS(Str);
5598 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5599 Context.PrintingPolicy);
5600 }
5601 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005602 break;
5603 }
5604
5605 case TemplateArgument::Pack:
5606 // FIXME: Format template argument packs
5607 Result += "<template argument pack>";
5608 break;
5609 }
5610 }
5611
5612 Result += ']';
5613 return Result;
5614}