blob: 3c6ecaa53ea73d2e85e423c19b22a281b8449961 [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(),
Douglas Gregor713602b2010-08-31 17:01:39 +0000665 NameLoc.isInvalid()? TmpLoc : NameLoc,
666 Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000667 (TemplateParameterList*)Params);
668
Douglas Gregordc13ded2010-07-01 00:00:45 +0000669 // If the template template parameter has a name, then link the identifier
670 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000671 if (Name) {
John McCall48871652010-08-21 09:40:31 +0000672 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000673 IdResolver.AddDecl(Param);
674 }
675
Douglas Gregordc13ded2010-07-01 00:00:45 +0000676 if (!Default.isInvalid()) {
677 // Check only that we have a template template argument. We don't want to
678 // try to check well-formedness now, because our template template parameter
679 // might have dependent types in its template parameters, which we wouldn't
680 // be able to match now.
681 //
682 // If none of the template template parameter's template arguments mention
683 // other template parameters, we could actually perform more checking here.
684 // However, it isn't worth doing.
685 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
686 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
687 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
688 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000689 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000690 }
691
692 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000693 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000694
John McCall48871652010-08-21 09:40:31 +0000695 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000696}
697
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000698/// ActOnTemplateParameterList - Builds a TemplateParameterList that
699/// contains the template parameters in Params/NumParams.
700Sema::TemplateParamsTy *
701Sema::ActOnTemplateParameterList(unsigned Depth,
702 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000703 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000704 SourceLocation LAngleLoc,
John McCall48871652010-08-21 09:40:31 +0000705 Decl **Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000706 SourceLocation RAngleLoc) {
707 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000708 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000709
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000710 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000711 (NamedDecl**)Params, NumParams,
712 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000713}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000714
John McCall3e11ebe2010-03-15 10:12:16 +0000715static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
716 if (SS.isSet())
717 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
718 SS.getRange());
719}
720
John McCallfaf5fb42010-08-26 23:41:50 +0000721DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000722Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000723 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000724 IdentifierInfo *Name, SourceLocation NameLoc,
725 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000726 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000727 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000728 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000729 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000730 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000731 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000732
733 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000734 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000735 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000736
Abramo Bagnara6150c882010-05-11 21:36:43 +0000737 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
738 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000739
740 // There is no such thing as an unnamed class template.
741 if (!Name) {
742 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000743 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000744 }
745
746 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000747 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000748 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000749 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000750 if (SS.isNotEmpty() && !SS.isInvalid()) {
751 SemanticContext = computeDeclContext(SS, true);
752 if (!SemanticContext) {
753 // FIXME: Produce a reasonable diagnostic here
754 return true;
755 }
Mike Stump11289f42009-09-09 15:08:12 +0000756
John McCall0b66eb32010-05-01 00:40:08 +0000757 if (RequireCompleteDeclContext(SS, SemanticContext))
758 return true;
759
John McCall27b18f82009-11-17 02:14:36 +0000760 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000761 } else {
762 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000763 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000764 }
Mike Stump11289f42009-09-09 15:08:12 +0000765
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000766 if (Previous.isAmbiguous())
767 return true;
768
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000769 NamedDecl *PrevDecl = 0;
770 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000771 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000772
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000773 // If there is a previous declaration with the same name, check
774 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000775 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000776 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000777
778 // We may have found the injected-class-name of a class template,
779 // class template partial specialization, or class template specialization.
780 // In these cases, grab the template that is being defined or specialized.
781 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
782 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
783 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
784 PrevClassTemplate
785 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
786 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
787 PrevClassTemplate
788 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
789 ->getSpecializedTemplate();
790 }
791 }
792
John McCalld43784f2009-12-18 11:25:59 +0000793 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000794 // C++ [namespace.memdef]p3:
795 // [...] When looking for a prior declaration of a class or a function
796 // declared as a friend, and when the name of the friend class or
797 // function is neither a qualified name nor a template-id, scopes outside
798 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000799 if (!SS.isSet()) {
800 DeclContext *OutermostContext = CurContext;
801 while (!OutermostContext->isFileContext())
802 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000803
Douglas Gregorb74b1032010-04-18 17:37:40 +0000804 if (PrevDecl &&
805 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
806 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
807 SemanticContext = PrevDecl->getDeclContext();
808 } else {
809 // Declarations in outer scopes don't matter. However, the outermost
810 // context we computed is the semantic context for our new
811 // declaration.
812 PrevDecl = PrevClassTemplate = 0;
813 SemanticContext = OutermostContext;
814 }
John McCall90d3bb92009-12-17 23:21:11 +0000815 }
Douglas Gregorb74b1032010-04-18 17:37:40 +0000816
John McCall90d3bb92009-12-17 23:21:11 +0000817 if (CurContext->isDependentContext()) {
818 // If this is a dependent context, we don't want to link the friend
819 // class template to the template in scope, because that would perform
820 // checking of the template parameter lists that can't be performed
821 // until the outer context is instantiated.
822 PrevDecl = PrevClassTemplate = 0;
823 }
824 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
825 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000826
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000827 if (PrevClassTemplate) {
828 // Ensure that the template parameter lists are compatible.
829 if (!TemplateParameterListsAreEqual(TemplateParams,
830 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000831 /*Complain=*/true,
832 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000833 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000834
835 // C++ [temp.class]p4:
836 // In a redeclaration, partial specialization, explicit
837 // specialization or explicit instantiation of a class template,
838 // the class-key shall agree in kind with the original class
839 // template declaration (7.1.5.3).
840 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000841 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000842 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000843 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000844 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000845 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000846 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000847 }
848
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000849 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000850 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000851 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000852 Diag(NameLoc, diag::err_redefinition) << Name;
853 Diag(Def->getLocation(), diag::note_previous_definition);
854 // FIXME: Would it make sense to try to "forget" the previous
855 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000856 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000857 }
858 }
859 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
860 // Maybe we will complain about the shadowed template parameter.
861 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
862 // Just pretend that we didn't see the previous declaration.
863 PrevDecl = 0;
864 } else if (PrevDecl) {
865 // C++ [temp]p5:
866 // A class template shall not have the same name as any other
867 // template, class, function, object, enumeration, enumerator,
868 // namespace, or type in the same scope (3.3), except as specified
869 // in (14.5.4).
870 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
871 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000872 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000873 }
874
Douglas Gregordba32632009-02-10 19:49:53 +0000875 // Check the template parameter list of this declaration, possibly
876 // merging in the template parameter list from the previous class
877 // template declaration.
878 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000879 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
880 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000881 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000882
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000883 if (SS.isSet()) {
884 // If the name of the template was qualified, we must be defining the
885 // template out-of-line.
886 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
887 !(TUK == TUK_Friend && CurContext->isDependentContext()))
888 Diag(NameLoc, diag::err_member_def_does_not_match)
889 << Name << SemanticContext << SS.getRange();
890 }
891
Mike Stump11289f42009-09-09 15:08:12 +0000892 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000893 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000894 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000895 PrevClassTemplate->getTemplatedDecl() : 0,
896 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000897 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000898
899 ClassTemplateDecl *NewTemplate
900 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
901 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000902 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000903 NewClass->setDescribedClassTemplate(NewTemplate);
904
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000905 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000906 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +0000907 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000908 assert(T->isDependentType() && "Class template type is not dependent?");
909 (void)T;
910
Douglas Gregorcf915552009-10-13 16:30:37 +0000911 // If we are providing an explicit specialization of a member that is a
912 // class template, make a note of that.
913 if (PrevClassTemplate &&
914 PrevClassTemplate->getInstantiatedFromMemberTemplate())
915 PrevClassTemplate->setMemberSpecialization();
916
Anders Carlsson137108d2009-03-26 01:24:28 +0000917 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000918 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000919 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000920
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000921 // Set the lexical context of these templates
922 NewClass->setLexicalDeclContext(CurContext);
923 NewTemplate->setLexicalDeclContext(CurContext);
924
John McCall9bb74a52009-07-31 02:45:11 +0000925 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000926 NewClass->startDefinition();
927
928 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000929 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000930
John McCall27b5c252009-09-14 21:59:20 +0000931 if (TUK != TUK_Friend)
932 PushOnScopeChains(NewTemplate, S);
933 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000934 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000935 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000936 NewClass->setAccess(PrevClassTemplate->getAccess());
937 }
John McCall27b5c252009-09-14 21:59:20 +0000938
Douglas Gregor3dad8422009-09-26 06:47:28 +0000939 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
940 PrevClassTemplate != NULL);
941
John McCall27b5c252009-09-14 21:59:20 +0000942 // Friend templates are visible in fairly strange ways.
943 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000944 DeclContext *DC = SemanticContext->getRedeclContext();
John McCall27b5c252009-09-14 21:59:20 +0000945 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
946 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
947 PushOnScopeChains(NewTemplate, EnclosingScope,
948 /* AddToContext = */ false);
949 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000950
951 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
952 NewClass->getLocation(),
953 NewTemplate,
954 /*FIXME:*/NewClass->getLocation());
955 Friend->setAccess(AS_public);
956 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000957 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000958
Douglas Gregordba32632009-02-10 19:49:53 +0000959 if (Invalid) {
960 NewTemplate->setInvalidDecl();
961 NewClass->setInvalidDecl();
962 }
John McCall48871652010-08-21 09:40:31 +0000963 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000964}
965
Douglas Gregored5731f2009-11-25 17:50:39 +0000966/// \brief Diagnose the presence of a default template argument on a
967/// template parameter, which is ill-formed in certain contexts.
968///
969/// \returns true if the default template argument should be dropped.
970static bool DiagnoseDefaultTemplateArgument(Sema &S,
971 Sema::TemplateParamListContext TPC,
972 SourceLocation ParamLoc,
973 SourceRange DefArgRange) {
974 switch (TPC) {
975 case Sema::TPC_ClassTemplate:
976 return false;
977
978 case Sema::TPC_FunctionTemplate:
979 // C++ [temp.param]p9:
980 // A default template-argument shall not be specified in a
981 // function template declaration or a function template
982 // definition [...]
983 // (This sentence is not in C++0x, per DR226).
984 if (!S.getLangOptions().CPlusPlus0x)
985 S.Diag(ParamLoc,
986 diag::err_template_parameter_default_in_function_template)
987 << DefArgRange;
988 return false;
989
990 case Sema::TPC_ClassTemplateMember:
991 // C++0x [temp.param]p9:
992 // A default template-argument shall not be specified in the
993 // template-parameter-lists of the definition of a member of a
994 // class template that appears outside of the member's class.
995 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
996 << DefArgRange;
997 return true;
998
999 case Sema::TPC_FriendFunctionTemplate:
1000 // C++ [temp.param]p9:
1001 // A default template-argument shall not be specified in a
1002 // friend template declaration.
1003 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1004 << DefArgRange;
1005 return true;
1006
1007 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1008 // for friend function templates if there is only a single
1009 // declaration (and it is a definition). Strange!
1010 }
1011
1012 return false;
1013}
1014
Douglas Gregordba32632009-02-10 19:49:53 +00001015/// \brief Checks the validity of a template parameter list, possibly
1016/// considering the template parameter list from a previous
1017/// declaration.
1018///
1019/// If an "old" template parameter list is provided, it must be
1020/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1021/// template parameter list.
1022///
1023/// \param NewParams Template parameter list for a new template
1024/// declaration. This template parameter list will be updated with any
1025/// default arguments that are carried through from the previous
1026/// template parameter list.
1027///
1028/// \param OldParams If provided, template parameter list from a
1029/// previous declaration of the same template. Default template
1030/// arguments will be merged from the old template parameter list to
1031/// the new template parameter list.
1032///
Douglas Gregored5731f2009-11-25 17:50:39 +00001033/// \param TPC Describes the context in which we are checking the given
1034/// template parameter list.
1035///
Douglas Gregordba32632009-02-10 19:49:53 +00001036/// \returns true if an error occurred, false otherwise.
1037bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001038 TemplateParameterList *OldParams,
1039 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001040 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001041
Douglas Gregordba32632009-02-10 19:49:53 +00001042 // C++ [temp.param]p10:
1043 // The set of default template-arguments available for use with a
1044 // template declaration or definition is obtained by merging the
1045 // default arguments from the definition (if in scope) and all
1046 // declarations in scope in the same way default function
1047 // arguments are (8.3.6).
1048 bool SawDefaultArgument = false;
1049 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001050
Anders Carlsson327865d2009-06-12 23:20:15 +00001051 bool SawParameterPack = false;
1052 SourceLocation ParameterPackLoc;
1053
Mike Stumpc89c8e32009-02-11 23:03:27 +00001054 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001055 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001056 if (OldParams)
1057 OldParam = OldParams->begin();
1058
1059 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1060 NewParamEnd = NewParams->end();
1061 NewParam != NewParamEnd; ++NewParam) {
1062 // Variables used to diagnose redundant default arguments
1063 bool RedundantDefaultArg = false;
1064 SourceLocation OldDefaultLoc;
1065 SourceLocation NewDefaultLoc;
1066
1067 // Variables used to diagnose missing default arguments
1068 bool MissingDefaultArg = false;
1069
Anders Carlsson327865d2009-06-12 23:20:15 +00001070 // C++0x [temp.param]p11:
1071 // If a template parameter of a class template is a template parameter pack,
1072 // it must be the last template parameter.
1073 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001074 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001075 diag::err_template_param_pack_must_be_last_template_parameter);
1076 Invalid = true;
1077 }
1078
Douglas Gregordba32632009-02-10 19:49:53 +00001079 if (TemplateTypeParmDecl *NewTypeParm
1080 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001081 // Check the presence of a default argument here.
1082 if (NewTypeParm->hasDefaultArgument() &&
1083 DiagnoseDefaultTemplateArgument(*this, TPC,
1084 NewTypeParm->getLocation(),
1085 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001086 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001087 NewTypeParm->removeDefaultArgument();
1088
1089 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001090 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001091 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001092
Anders Carlsson327865d2009-06-12 23:20:15 +00001093 if (NewTypeParm->isParameterPack()) {
1094 assert(!NewTypeParm->hasDefaultArgument() &&
1095 "Parameter packs can't have a default argument!");
1096 SawParameterPack = true;
1097 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001098 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001099 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001100 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1101 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1102 SawDefaultArgument = true;
1103 RedundantDefaultArg = true;
1104 PreviousDefaultArgLoc = NewDefaultLoc;
1105 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1106 // Merge the default argument from the old declaration to the
1107 // new declaration.
1108 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001109 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001110 true);
1111 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1112 } else if (NewTypeParm->hasDefaultArgument()) {
1113 SawDefaultArgument = true;
1114 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1115 } else if (SawDefaultArgument)
1116 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001117 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001118 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001119 // Check the presence of a default argument here.
1120 if (NewNonTypeParm->hasDefaultArgument() &&
1121 DiagnoseDefaultTemplateArgument(*this, TPC,
1122 NewNonTypeParm->getLocation(),
1123 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001124 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001125 }
1126
Mike Stump12b8ce12009-08-04 21:02:39 +00001127 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001128 NonTypeTemplateParmDecl *OldNonTypeParm
1129 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001130 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001131 NewNonTypeParm->hasDefaultArgument()) {
1132 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1133 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1134 SawDefaultArgument = true;
1135 RedundantDefaultArg = true;
1136 PreviousDefaultArgLoc = NewDefaultLoc;
1137 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1138 // Merge the default argument from the old declaration to the
1139 // new declaration.
1140 SawDefaultArgument = true;
1141 // FIXME: We need to create a new kind of "default argument"
1142 // expression that points to a previous template template
1143 // parameter.
1144 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001145 OldNonTypeParm->getDefaultArgument(),
1146 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001147 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1148 } else if (NewNonTypeParm->hasDefaultArgument()) {
1149 SawDefaultArgument = true;
1150 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1151 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001152 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001153 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001154 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001155 TemplateTemplateParmDecl *NewTemplateParm
1156 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001157 if (NewTemplateParm->hasDefaultArgument() &&
1158 DiagnoseDefaultTemplateArgument(*this, TPC,
1159 NewTemplateParm->getLocation(),
1160 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001161 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001162
1163 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001164 TemplateTemplateParmDecl *OldTemplateParm
1165 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001166 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001167 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001168 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1169 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001170 SawDefaultArgument = true;
1171 RedundantDefaultArg = true;
1172 PreviousDefaultArgLoc = NewDefaultLoc;
1173 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1174 // Merge the default argument from the old declaration to the
1175 // new declaration.
1176 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001177 // FIXME: We need to create a new kind of "default argument" expression
1178 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001179 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001180 OldTemplateParm->getDefaultArgument(),
1181 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001182 PreviousDefaultArgLoc
1183 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001184 } else if (NewTemplateParm->hasDefaultArgument()) {
1185 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001186 PreviousDefaultArgLoc
1187 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001188 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001189 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001190 }
1191
1192 if (RedundantDefaultArg) {
1193 // C++ [temp.param]p12:
1194 // A template-parameter shall not be given default arguments
1195 // by two different declarations in the same scope.
1196 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1197 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1198 Invalid = true;
1199 } else if (MissingDefaultArg) {
1200 // C++ [temp.param]p11:
1201 // If a template-parameter has a default template-argument,
1202 // all subsequent template-parameters shall have a default
1203 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001204 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001205 diag::err_template_param_default_arg_missing);
1206 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1207 Invalid = true;
1208 }
1209
1210 // If we have an old template parameter list that we're merging
1211 // in, move on to the next parameter.
1212 if (OldParams)
1213 ++OldParam;
1214 }
1215
1216 return Invalid;
1217}
Douglas Gregord32e0282009-02-09 23:23:08 +00001218
Mike Stump11289f42009-09-09 15:08:12 +00001219/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001220/// specifier, returning the template parameter list that applies to the
1221/// name.
1222///
1223/// \param DeclStartLoc the start of the declaration that has a scope
1224/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001225///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001226/// \param SS the scope specifier that will be matched to the given template
1227/// parameter lists. This scope specifier precedes a qualified name that is
1228/// being declared.
1229///
1230/// \param ParamLists the template parameter lists, from the outermost to the
1231/// innermost template parameter lists.
1232///
1233/// \param NumParamLists the number of template parameter lists in ParamLists.
1234///
John McCalle820e5e2010-04-13 20:37:33 +00001235/// \param IsFriend Whether to apply the slightly different rules for
1236/// matching template parameters to scope specifiers in friend
1237/// declarations.
1238///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001239/// \param IsExplicitSpecialization will be set true if the entity being
1240/// declared is an explicit specialization, false otherwise.
1241///
Mike Stump11289f42009-09-09 15:08:12 +00001242/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001243/// name that is preceded by the scope specifier @p SS. This template
1244/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001245/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001246/// template specialization), or may be NULL (if we were's declaring isn't
1247/// itself a template).
1248TemplateParameterList *
1249Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1250 const CXXScopeSpec &SS,
1251 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001252 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001253 bool IsFriend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001254 bool &IsExplicitSpecialization,
1255 bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001256 IsExplicitSpecialization = false;
1257
Douglas Gregord8d297c2009-07-21 23:53:31 +00001258 // Find the template-ids that occur within the nested-name-specifier. These
1259 // template-ids will match up with the template parameter lists.
1260 llvm::SmallVector<const TemplateSpecializationType *, 4>
1261 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001262 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1263 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001264 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1265 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001266 const Type *T = NNS->getAsType();
1267 if (!T) break;
1268
1269 // C++0x [temp.expl.spec]p17:
1270 // A member or a member template may be nested within many
1271 // enclosing class templates. In an explicit specialization for
1272 // such a member, the member declaration shall be preceded by a
1273 // template<> for each enclosing class template that is
1274 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001275 //
1276 // Following the existing practice of GNU and EDG, we allow a typedef of a
1277 // template specialization type.
1278 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1279 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001280
Mike Stump11289f42009-09-09 15:08:12 +00001281 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001282 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001283 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1284 if (!Template)
1285 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001286
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001287 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001288 ClassTemplateSpecializationDecl *SpecDecl
1289 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1290 // If the nested name specifier refers to an explicit specialization,
1291 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001292 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1293 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001294 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001295 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001296 }
Mike Stump11289f42009-09-09 15:08:12 +00001297
Douglas Gregord8d297c2009-07-21 23:53:31 +00001298 TemplateIdsInSpecifier.push_back(SpecType);
1299 }
1300 }
Mike Stump11289f42009-09-09 15:08:12 +00001301
Douglas Gregord8d297c2009-07-21 23:53:31 +00001302 // Reverse the list of template-ids in the scope specifier, so that we can
1303 // more easily match up the template-ids and the template parameter lists.
1304 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001305
Douglas Gregord8d297c2009-07-21 23:53:31 +00001306 SourceLocation FirstTemplateLoc = DeclStartLoc;
1307 if (NumParamLists)
1308 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001309
Douglas Gregord8d297c2009-07-21 23:53:31 +00001310 // Match the template-ids found in the specifier to the template parameter
1311 // lists.
1312 unsigned Idx = 0;
1313 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1314 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001315 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1316 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001317 if (Idx >= NumParamLists) {
1318 // We have a template-id without a corresponding template parameter
1319 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001320
1321 // ...which is fine if this is a friend declaration.
1322 if (IsFriend) {
1323 IsExplicitSpecialization = true;
1324 break;
1325 }
1326
Douglas Gregord8d297c2009-07-21 23:53:31 +00001327 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001328 // FIXME: the location information here isn't great.
1329 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001330 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001331 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001332 << SS.getRange();
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001333 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001334 } else {
1335 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1336 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001337 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001338 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001339 }
1340 return 0;
1341 }
Mike Stump11289f42009-09-09 15:08:12 +00001342
Douglas Gregord8d297c2009-07-21 23:53:31 +00001343 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001344 if (DependentTemplateId) {
John McCall2408e322010-04-27 00:57:59 +00001345 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00001346
John McCall2408e322010-04-27 00:57:59 +00001347 // Are there cases in (e.g.) friends where this won't match?
1348 if (const InjectedClassNameType *Injected
1349 = TemplateId->getAs<InjectedClassNameType>()) {
1350 CXXRecordDecl *Record = Injected->getDecl();
1351 if (ClassTemplatePartialSpecializationDecl *Partial =
1352 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1353 ExpectedTemplateParams = Partial->getTemplateParameters();
1354 else
1355 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1356 ->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001357 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001358
John McCall2408e322010-04-27 00:57:59 +00001359 if (ExpectedTemplateParams)
1360 TemplateParameterListsAreEqual(ParamLists[Idx],
1361 ExpectedTemplateParams,
1362 true, TPL_TemplateMatch);
1363
Douglas Gregored5731f2009-11-25 17:50:39 +00001364 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001365 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001366 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001367 diag::err_template_param_list_matches_nontemplate)
1368 << TemplateId
1369 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001370 else
1371 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001372 }
Mike Stump11289f42009-09-09 15:08:12 +00001373
Douglas Gregord8d297c2009-07-21 23:53:31 +00001374 // If there were at least as many template-ids as there were template
1375 // parameter lists, then there are no template parameter lists remaining for
1376 // the declaration itself.
Douglas Gregor5be1eb82010-08-20 03:26:10 +00001377 if (Idx >= NumParamLists)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001378 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001379
Douglas Gregord8d297c2009-07-21 23:53:31 +00001380 // If there were too many template parameter lists, complain about that now.
1381 if (Idx != NumParamLists - 1) {
1382 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001383 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001384 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001385 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1386 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001387 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1388 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001389
1390 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1391 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1392 diag::note_explicit_template_spec_does_not_need_header)
1393 << ExplicitSpecializationsInSpecifier.back();
1394 ExplicitSpecializationsInSpecifier.pop_back();
1395 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001396
1397 // We have a template parameter list with no corresponding scope, which
1398 // means that the resulting template declaration can't be instantiated
1399 // properly (we'll end up with dependent nodes when we shouldn't).
1400 if (!isExplicitSpecHeader)
1401 Invalid = true;
1402
Douglas Gregord8d297c2009-07-21 23:53:31 +00001403 ++Idx;
1404 }
1405 }
Mike Stump11289f42009-09-09 15:08:12 +00001406
Douglas Gregord8d297c2009-07-21 23:53:31 +00001407 // Return the last template parameter list, which corresponds to the
1408 // entity being declared.
1409 return ParamLists[NumParamLists - 1];
1410}
1411
Douglas Gregordc572a32009-03-30 22:58:21 +00001412QualType Sema::CheckTemplateIdType(TemplateName Name,
1413 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001414 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001415 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001416 if (!Template) {
1417 // The template name does not resolve to a template, so we just
1418 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001419 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001420 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001421
Douglas Gregorc40290e2009-03-09 23:48:35 +00001422 // Check that the template argument list is well-formed for this
1423 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001424 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001425 TemplateArgs.size());
1426 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001427 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001428 return QualType();
1429
Mike Stump11289f42009-09-09 15:08:12 +00001430 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001431 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001432 "Converted template argument list is too short!");
1433
1434 QualType CanonType;
1435
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001436 if (Name.isDependent() ||
1437 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001438 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001439 // This class template specialization is a dependent
1440 // type. Therefore, its canonical type is another class template
1441 // specialization type that contains all of the converted
1442 // arguments in canonical form. This ensures that, e.g., A<T> and
1443 // A<T, T> have identical types when A is declared as:
1444 //
1445 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001446 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001447 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001448 Converted.getFlatArguments(),
1449 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001450
Douglas Gregora8e02e72009-07-28 23:00:59 +00001451 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001452 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001453 // In the future, we need to teach getTemplateSpecializationType to only
1454 // build the canonical type and return that to us.
1455 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001456
1457 // This might work out to be a current instantiation, in which
1458 // case the canonical type needs to be the InjectedClassNameType.
1459 //
1460 // TODO: in theory this could be a simple hashtable lookup; most
1461 // changes to CurContext don't change the set of current
1462 // instantiations.
1463 if (isa<ClassTemplateDecl>(Template)) {
1464 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1465 // If we get out to a namespace, we're done.
1466 if (Ctx->isFileContext()) break;
1467
1468 // If this isn't a record, keep looking.
1469 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1470 if (!Record) continue;
1471
1472 // Look for one of the two cases with InjectedClassNameTypes
1473 // and check whether it's the same template.
1474 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1475 !Record->getDescribedClassTemplate())
1476 continue;
1477
1478 // Fetch the injected class name type and check whether its
1479 // injected type is equal to the type we just built.
1480 QualType ICNT = Context.getTypeDeclType(Record);
1481 QualType Injected = cast<InjectedClassNameType>(ICNT)
1482 ->getInjectedSpecializationType();
1483
1484 if (CanonType != Injected->getCanonicalTypeInternal())
1485 continue;
1486
1487 // If so, the canonical type of this TST is the injected
1488 // class name type of the record we just found.
1489 assert(ICNT.isCanonical());
1490 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00001491 break;
1492 }
1493 }
Mike Stump11289f42009-09-09 15:08:12 +00001494 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001495 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001496 // Find the class template specialization declaration that
1497 // corresponds to these arguments.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001498 void *InsertPos = 0;
1499 ClassTemplateSpecializationDecl *Decl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001500 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
1501 Converted.flatSize(), InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001502 if (!Decl) {
1503 // This is the first time we have referenced this class template
1504 // specialization. Create the canonical declaration and add it to
1505 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001506 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001507 ClassTemplate->getTemplatedDecl()->getTagKind(),
1508 ClassTemplate->getDeclContext(),
1509 ClassTemplate->getLocation(),
1510 ClassTemplate,
1511 Converted, 0);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001512 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001513 Decl->setLexicalDeclContext(CurContext);
1514 }
1515
1516 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001517 assert(isa<RecordType>(CanonType) &&
1518 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001519 }
Mike Stump11289f42009-09-09 15:08:12 +00001520
Douglas Gregorc40290e2009-03-09 23:48:35 +00001521 // Build the fully-sugared type for this class template
1522 // specialization, which refers back to the class template
1523 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00001524 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001525}
1526
John McCallfaf5fb42010-08-26 23:41:50 +00001527TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001528Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001529 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001530 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001531 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001532 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001533
Douglas Gregorc40290e2009-03-09 23:48:35 +00001534 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001535 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001536 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001537
John McCall6b51f282009-11-23 01:53:49 +00001538 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001539 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001540
1541 if (Result.isNull())
1542 return true;
1543
John McCallbcd03502009-12-07 02:54:59 +00001544 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001545 TemplateSpecializationTypeLoc TL
1546 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1547 TL.setTemplateNameLoc(TemplateLoc);
1548 TL.setLAngleLoc(LAngleLoc);
1549 TL.setRAngleLoc(RAngleLoc);
1550 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1551 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1552
John McCallba7bf592010-08-24 05:47:05 +00001553 return CreateParsedType(Result, DI);
John McCalld8fe9af2009-09-08 17:47:29 +00001554}
John McCall06f6fe8d2009-09-04 01:14:41 +00001555
John McCallfaf5fb42010-08-26 23:41:50 +00001556TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1557 TagUseKind TUK,
1558 TypeSpecifierType TagSpec,
1559 SourceLocation TagLoc) {
John McCalld8fe9af2009-09-08 17:47:29 +00001560 if (TypeResult.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00001561 return ::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001562
John McCall0ad16662009-10-29 08:12:44 +00001563 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001564 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001565 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001566
John McCalld8fe9af2009-09-08 17:47:29 +00001567 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001568 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001569
John McCalld8fe9af2009-09-08 17:47:29 +00001570 if (const RecordType *RT = Type->getAs<RecordType>()) {
1571 RecordDecl *D = RT->getDecl();
1572
1573 IdentifierInfo *Id = D->getIdentifier();
1574 assert(Id && "templated class must have an identifier");
1575
1576 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1577 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001578 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001579 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001580 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001581 }
1582 }
1583
Abramo Bagnara6150c882010-05-11 21:36:43 +00001584 ElaboratedTypeKeyword Keyword
1585 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1586 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001587
John McCallba7bf592010-08-24 05:47:05 +00001588 return ParsedType::make(ElabType);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001589}
1590
John McCalldadc5752010-08-24 06:29:42 +00001591ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001592 LookupResult &R,
1593 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001594 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001595 // FIXME: Can we do any checking at this point? I guess we could check the
1596 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001597 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001598 // though.
John McCalle66edc12009-11-24 19:00:30 +00001599
1600 // These should be filtered out by our callers.
1601 assert(!R.empty() && "empty lookup results when building templateid");
1602 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1603
1604 NestedNameSpecifier *Qualifier = 0;
1605 SourceRange QualifierRange;
1606 if (SS.isSet()) {
1607 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1608 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001609 }
John McCall58cc69d2010-01-27 01:50:18 +00001610
1611 // We don't want lookup warnings at this point.
1612 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001613
John McCalle66edc12009-11-24 19:00:30 +00001614 bool Dependent
1615 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1616 &TemplateArgs);
1617 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001618 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001619 Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001620 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001621 RequiresADL, TemplateArgs,
1622 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001623
1624 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001625}
1626
John McCalle66edc12009-11-24 19:00:30 +00001627// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00001628ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001629Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001630 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +00001631 const TemplateArgumentListInfo &TemplateArgs) {
1632 DeclContext *DC;
1633 if (!(DC = computeDeclContext(SS, false)) ||
1634 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001635 RequireCompleteDeclContext(SS, DC))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001636 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001637
Douglas Gregor786123d2010-05-21 23:18:07 +00001638 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001639 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00001640 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1641 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00001642
John McCalle66edc12009-11-24 19:00:30 +00001643 if (R.isAmbiguous())
1644 return ExprError();
1645
1646 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001647 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1648 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001649 return ExprError();
1650 }
1651
1652 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001653 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1654 << (NestedNameSpecifier*) SS.getScopeRep()
1655 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001656 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1657 return ExprError();
1658 }
1659
1660 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001661}
1662
Douglas Gregorb67535d2009-03-31 00:43:58 +00001663/// \brief Form a dependent template name.
1664///
1665/// This action forms a dependent template name given the template
1666/// name and its (presumably dependent) scope specifier. For
1667/// example, given "MetaFun::template apply", the scope specifier \p
1668/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1669/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregorbb119652010-06-16 23:00:59 +00001670TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1671 SourceLocation TemplateKWLoc,
1672 CXXScopeSpec &SS,
1673 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00001674 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00001675 bool EnteringContext,
1676 TemplateTy &Result) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00001677 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1678 !getLangOptions().CPlusPlus0x)
1679 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1680 << FixItHint::CreateRemoval(TemplateKWLoc);
1681
Douglas Gregor9abe2372010-01-19 16:01:07 +00001682 DeclContext *LookupCtx = 0;
1683 if (SS.isSet())
1684 LookupCtx = computeDeclContext(SS, EnteringContext);
1685 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00001686 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00001687 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001688 // C++0x [temp.names]p5:
1689 // If a name prefixed by the keyword template is not the name of
1690 // a template, the program is ill-formed. [Note: the keyword
1691 // template may not be applied to non-template members of class
1692 // templates. -end note ] [ Note: as is the case with the
1693 // typename prefix, the template prefix is allowed in cases
1694 // where it is not strictly necessary; i.e., when the
1695 // nested-name-specifier or the expression on the left of the ->
1696 // or . is not dependent on a template-parameter, or the use
1697 // does not appear in the scope of a template. -end note]
1698 //
1699 // Note: C++03 was more strict here, because it banned the use of
1700 // the "template" keyword prior to a template-name that was not a
1701 // dependent name. C++ DR468 relaxed this requirement (the
1702 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00001703 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00001704 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001705 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1706 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00001707 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001708 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1709 isa<CXXRecordDecl>(LookupCtx) &&
1710 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregorbb119652010-06-16 23:00:59 +00001711 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00001712 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001713 Diag(Name.getSourceRange().getBegin(),
1714 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001715 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001716 << Name.getSourceRange()
1717 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001718 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00001719 } else {
1720 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00001721 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001722 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001723 }
1724
Mike Stump11289f42009-09-09 15:08:12 +00001725 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001726 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001727
1728 switch (Name.getKind()) {
1729 case UnqualifiedId::IK_Identifier:
Douglas Gregorbb119652010-06-16 23:00:59 +00001730 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1731 Name.Identifier));
1732 return TNK_Dependent_template_name;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001733
Douglas Gregor71395fa2009-11-04 00:56:37 +00001734 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00001735 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00001736 Name.OperatorFunctionId.Operator));
Douglas Gregorbb119652010-06-16 23:00:59 +00001737 return TNK_Dependent_template_name;
Alexis Hunted0530f2009-11-28 08:58:14 +00001738
1739 case UnqualifiedId::IK_LiteralOperatorId:
1740 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1741
Douglas Gregor3cf81312009-11-03 23:16:33 +00001742 default:
1743 break;
1744 }
1745
1746 Diag(Name.getSourceRange().getBegin(),
1747 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001748 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001749 << Name.getSourceRange()
1750 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001751 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001752}
1753
Mike Stump11289f42009-09-09 15:08:12 +00001754bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001755 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001756 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001757 const TemplateArgument &Arg = AL.getArgument();
1758
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001759 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001760 switch(Arg.getKind()) {
1761 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001762 // C++ [temp.arg.type]p1:
1763 // A template-argument for a template-parameter which is a
1764 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001765 break;
1766 case TemplateArgument::Template: {
1767 // We have a template type parameter but the template argument
1768 // is a template without any arguments.
1769 SourceRange SR = AL.getSourceRange();
1770 TemplateName Name = Arg.getAsTemplate();
1771 Diag(SR.getBegin(), diag::err_template_missing_args)
1772 << Name << SR;
1773 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1774 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001775
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001776 return true;
1777 }
1778 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001779 // We have a template type parameter but the template argument
1780 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001781 SourceRange SR = AL.getSourceRange();
1782 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001783 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001784
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001785 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001786 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001787 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001788
John McCallbcd03502009-12-07 02:54:59 +00001789 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001790 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001791
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001792 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001793 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001794 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001795 return false;
1796}
1797
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001798/// \brief Substitute template arguments into the default template argument for
1799/// the given template type parameter.
1800///
1801/// \param SemaRef the semantic analysis object for which we are performing
1802/// the substitution.
1803///
1804/// \param Template the template that we are synthesizing template arguments
1805/// for.
1806///
1807/// \param TemplateLoc the location of the template name that started the
1808/// template-id we are checking.
1809///
1810/// \param RAngleLoc the location of the right angle bracket ('>') that
1811/// terminates the template-id.
1812///
1813/// \param Param the template template parameter whose default we are
1814/// substituting into.
1815///
1816/// \param Converted the list of template arguments provided for template
1817/// parameters that precede \p Param in the template parameter list.
1818///
1819/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001820static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001821SubstDefaultTemplateArgument(Sema &SemaRef,
1822 TemplateDecl *Template,
1823 SourceLocation TemplateLoc,
1824 SourceLocation RAngleLoc,
1825 TemplateTypeParmDecl *Param,
1826 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001827 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001828
1829 // If the argument type is dependent, instantiate it now based
1830 // on the previously-computed template arguments.
1831 if (ArgType->getType()->isDependentType()) {
1832 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1833 /*TakeArgs=*/false);
1834
1835 MultiLevelTemplateArgumentList AllTemplateArgs
1836 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1837
1838 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1839 Template, Converted.getFlatArguments(),
1840 Converted.flatSize(),
1841 SourceRange(TemplateLoc, RAngleLoc));
1842
1843 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1844 Param->getDefaultArgumentLoc(),
1845 Param->getDeclName());
1846 }
1847
1848 return ArgType;
1849}
1850
1851/// \brief Substitute template arguments into the default template argument for
1852/// the given non-type template parameter.
1853///
1854/// \param SemaRef the semantic analysis object for which we are performing
1855/// the substitution.
1856///
1857/// \param Template the template that we are synthesizing template arguments
1858/// for.
1859///
1860/// \param TemplateLoc the location of the template name that started the
1861/// template-id we are checking.
1862///
1863/// \param RAngleLoc the location of the right angle bracket ('>') that
1864/// terminates the template-id.
1865///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001866/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001867/// substituting into.
1868///
1869/// \param Converted the list of template arguments provided for template
1870/// parameters that precede \p Param in the template parameter list.
1871///
1872/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00001873static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001874SubstDefaultTemplateArgument(Sema &SemaRef,
1875 TemplateDecl *Template,
1876 SourceLocation TemplateLoc,
1877 SourceLocation RAngleLoc,
1878 NonTypeTemplateParmDecl *Param,
1879 TemplateArgumentListBuilder &Converted) {
1880 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1881 /*TakeArgs=*/false);
1882
1883 MultiLevelTemplateArgumentList AllTemplateArgs
1884 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1885
1886 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1887 Template, Converted.getFlatArguments(),
1888 Converted.flatSize(),
1889 SourceRange(TemplateLoc, RAngleLoc));
1890
1891 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1892}
1893
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001894/// \brief Substitute template arguments into the default template argument for
1895/// the given template template parameter.
1896///
1897/// \param SemaRef the semantic analysis object for which we are performing
1898/// the substitution.
1899///
1900/// \param Template the template that we are synthesizing template arguments
1901/// for.
1902///
1903/// \param TemplateLoc the location of the template name that started the
1904/// template-id we are checking.
1905///
1906/// \param RAngleLoc the location of the right angle bracket ('>') that
1907/// terminates the template-id.
1908///
1909/// \param Param the template template parameter whose default we are
1910/// substituting into.
1911///
1912/// \param Converted the list of template arguments provided for template
1913/// parameters that precede \p Param in the template parameter list.
1914///
1915/// \returns the substituted template argument, or NULL if an error occurred.
1916static TemplateName
1917SubstDefaultTemplateArgument(Sema &SemaRef,
1918 TemplateDecl *Template,
1919 SourceLocation TemplateLoc,
1920 SourceLocation RAngleLoc,
1921 TemplateTemplateParmDecl *Param,
1922 TemplateArgumentListBuilder &Converted) {
1923 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1924 /*TakeArgs=*/false);
1925
1926 MultiLevelTemplateArgumentList AllTemplateArgs
1927 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1928
1929 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1930 Template, Converted.getFlatArguments(),
1931 Converted.flatSize(),
1932 SourceRange(TemplateLoc, RAngleLoc));
1933
1934 return SemaRef.SubstTemplateName(
1935 Param->getDefaultArgument().getArgument().getAsTemplate(),
1936 Param->getDefaultArgument().getTemplateNameLoc(),
1937 AllTemplateArgs);
1938}
1939
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001940/// \brief If the given template parameter has a default template
1941/// argument, substitute into that default template argument and
1942/// return the corresponding template argument.
1943TemplateArgumentLoc
1944Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1945 SourceLocation TemplateLoc,
1946 SourceLocation RAngleLoc,
1947 Decl *Param,
1948 TemplateArgumentListBuilder &Converted) {
1949 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1950 if (!TypeParm->hasDefaultArgument())
1951 return TemplateArgumentLoc();
1952
John McCallbcd03502009-12-07 02:54:59 +00001953 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001954 TemplateLoc,
1955 RAngleLoc,
1956 TypeParm,
1957 Converted);
1958 if (DI)
1959 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1960
1961 return TemplateArgumentLoc();
1962 }
1963
1964 if (NonTypeTemplateParmDecl *NonTypeParm
1965 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1966 if (!NonTypeParm->hasDefaultArgument())
1967 return TemplateArgumentLoc();
1968
John McCalldadc5752010-08-24 06:29:42 +00001969 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001970 TemplateLoc,
1971 RAngleLoc,
1972 NonTypeParm,
1973 Converted);
1974 if (Arg.isInvalid())
1975 return TemplateArgumentLoc();
1976
1977 Expr *ArgE = Arg.takeAs<Expr>();
1978 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1979 }
1980
1981 TemplateTemplateParmDecl *TempTempParm
1982 = cast<TemplateTemplateParmDecl>(Param);
1983 if (!TempTempParm->hasDefaultArgument())
1984 return TemplateArgumentLoc();
1985
1986 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1987 TemplateLoc,
1988 RAngleLoc,
1989 TempTempParm,
1990 Converted);
1991 if (TName.isNull())
1992 return TemplateArgumentLoc();
1993
1994 return TemplateArgumentLoc(TemplateArgument(TName),
1995 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1996 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1997}
1998
Douglas Gregorda0fb532009-11-11 19:31:23 +00001999/// \brief Check that the given template argument corresponds to the given
2000/// template parameter.
2001bool Sema::CheckTemplateArgument(NamedDecl *Param,
2002 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002003 TemplateDecl *Template,
2004 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002005 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002006 TemplateArgumentListBuilder &Converted,
2007 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00002008 // Check template type parameters.
2009 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002010 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002011
Douglas Gregoreebed722009-11-11 19:41:09 +00002012 // Check non-type template parameters.
2013 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00002014 // Do substitution on the type of the non-type template parameter
2015 // with the template arguments we've seen thus far.
2016 QualType NTTPType = NTTP->getType();
2017 if (NTTPType->isDependentType()) {
2018 // Do substitution on the type of the non-type template parameter.
2019 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2020 NTTP, Converted.getFlatArguments(),
2021 Converted.flatSize(),
2022 SourceRange(TemplateLoc, RAngleLoc));
2023
2024 TemplateArgumentList TemplateArgs(Context, Converted,
2025 /*TakeArgs=*/false);
2026 NTTPType = SubstType(NTTPType,
2027 MultiLevelTemplateArgumentList(TemplateArgs),
2028 NTTP->getLocation(),
2029 NTTP->getDeclName());
2030 // If that worked, check the non-type template parameter type
2031 // for validity.
2032 if (!NTTPType.isNull())
2033 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2034 NTTP->getLocation());
2035 if (NTTPType.isNull())
2036 return true;
2037 }
2038
2039 switch (Arg.getArgument().getKind()) {
2040 case TemplateArgument::Null:
2041 assert(false && "Should never see a NULL template argument here");
2042 return true;
2043
2044 case TemplateArgument::Expression: {
2045 Expr *E = Arg.getArgument().getAsExpr();
2046 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002047 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002048 return true;
2049
2050 Converted.Append(Result);
2051 break;
2052 }
2053
2054 case TemplateArgument::Declaration:
2055 case TemplateArgument::Integral:
2056 // We've already checked this template argument, so just copy
2057 // it to the list of converted arguments.
2058 Converted.Append(Arg.getArgument());
2059 break;
2060
2061 case TemplateArgument::Template:
2062 // We were given a template template argument. It may not be ill-formed;
2063 // see below.
2064 if (DependentTemplateName *DTN
2065 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2066 // We have a template argument such as \c T::template X, which we
2067 // parsed as a template template argument. However, since we now
2068 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002069 // template name into an expression.
2070
2071 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2072 Arg.getTemplateNameLoc());
2073
John McCalle66edc12009-11-24 19:00:30 +00002074 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2075 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002076 Arg.getTemplateQualifierRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002077 NameInfo);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002078
2079 TemplateArgument Result;
2080 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2081 return true;
2082
2083 Converted.Append(Result);
2084 break;
2085 }
2086
2087 // We have a template argument that actually does refer to a class
2088 // template, template alias, or template template parameter, and
2089 // therefore cannot be a non-type template argument.
2090 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2091 << Arg.getSourceRange();
2092
2093 Diag(Param->getLocation(), diag::note_template_param_here);
2094 return true;
2095
2096 case TemplateArgument::Type: {
2097 // We have a non-type template parameter but the template
2098 // argument is a type.
2099
2100 // C++ [temp.arg]p2:
2101 // In a template-argument, an ambiguity between a type-id and
2102 // an expression is resolved to a type-id, regardless of the
2103 // form of the corresponding template-parameter.
2104 //
2105 // We warn specifically about this case, since it can be rather
2106 // confusing for users.
2107 QualType T = Arg.getArgument().getAsType();
2108 SourceRange SR = Arg.getSourceRange();
2109 if (T->isFunctionType())
2110 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2111 else
2112 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2113 Diag(Param->getLocation(), diag::note_template_param_here);
2114 return true;
2115 }
2116
2117 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002118 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002119 break;
2120 }
2121
2122 return false;
2123 }
2124
2125
2126 // Check template template parameters.
2127 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2128
2129 // Substitute into the template parameter list of the template
2130 // template parameter, since previously-supplied template arguments
2131 // may appear within the template template parameter.
2132 {
2133 // Set up a template instantiation context.
2134 LocalInstantiationScope Scope(*this);
2135 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2136 TempParm, Converted.getFlatArguments(),
2137 Converted.flatSize(),
2138 SourceRange(TemplateLoc, RAngleLoc));
2139
2140 TemplateArgumentList TemplateArgs(Context, Converted,
2141 /*TakeArgs=*/false);
2142 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2143 SubstDecl(TempParm, CurContext,
2144 MultiLevelTemplateArgumentList(TemplateArgs)));
2145 if (!TempParm)
2146 return true;
2147
2148 // FIXME: TempParam is leaked.
2149 }
2150
2151 switch (Arg.getArgument().getKind()) {
2152 case TemplateArgument::Null:
2153 assert(false && "Should never see a NULL template argument here");
2154 return true;
2155
2156 case TemplateArgument::Template:
2157 if (CheckTemplateArgument(TempParm, Arg))
2158 return true;
2159
2160 Converted.Append(Arg.getArgument());
2161 break;
2162
2163 case TemplateArgument::Expression:
2164 case TemplateArgument::Type:
2165 // We have a template template parameter but the template
2166 // argument does not refer to a template.
2167 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2168 return true;
2169
2170 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002171 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002172 "Declaration argument with template template parameter");
2173 break;
2174 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002175 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002176 "Integral argument with template template parameter");
2177 break;
2178
2179 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002180 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002181 break;
2182 }
2183
2184 return false;
2185}
2186
Douglas Gregord32e0282009-02-09 23:23:08 +00002187/// \brief Check that the given template argument list is well-formed
2188/// for specializing the given template.
2189bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2190 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002191 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002192 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002193 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002194 TemplateParameterList *Params = Template->getTemplateParameters();
2195 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002196 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002197 bool Invalid = false;
2198
John McCall6b51f282009-11-23 01:53:49 +00002199 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2200
Mike Stump11289f42009-09-09 15:08:12 +00002201 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002202 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002203
Anders Carlsson15201f12009-06-13 02:08:00 +00002204 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002205 (NumArgs < Params->getMinRequiredArguments() &&
2206 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002207 // FIXME: point at either the first arg beyond what we can handle,
2208 // or the '>', depending on whether we have too many or too few
2209 // arguments.
2210 SourceRange Range;
2211 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002212 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002213 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2214 << (NumArgs > NumParams)
2215 << (isa<ClassTemplateDecl>(Template)? 0 :
2216 isa<FunctionTemplateDecl>(Template)? 1 :
2217 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2218 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002219 Diag(Template->getLocation(), diag::note_template_decl_here)
2220 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002221 Invalid = true;
2222 }
Mike Stump11289f42009-09-09 15:08:12 +00002223
2224 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002225 // [...] The type and form of each template-argument specified in
2226 // a template-id shall match the type and form specified for the
2227 // corresponding parameter declared by the template in its
2228 // template-parameter-list.
2229 unsigned ArgIdx = 0;
2230 for (TemplateParameterList::iterator Param = Params->begin(),
2231 ParamEnd = Params->end();
2232 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002233 if (ArgIdx > NumArgs && PartialTemplateArgs)
2234 break;
Mike Stump11289f42009-09-09 15:08:12 +00002235
Douglas Gregoreebed722009-11-11 19:41:09 +00002236 // If we have a template parameter pack, check every remaining template
2237 // argument against that template parameter pack.
2238 if ((*Param)->isTemplateParameterPack()) {
2239 Converted.BeginPack();
2240 for (; ArgIdx < NumArgs; ++ArgIdx) {
2241 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2242 TemplateLoc, RAngleLoc, Converted)) {
2243 Invalid = true;
2244 break;
2245 }
2246 }
2247 Converted.EndPack();
2248 continue;
2249 }
2250
Douglas Gregor84d49a22009-11-11 21:54:23 +00002251 if (ArgIdx < NumArgs) {
2252 // Check the template argument we were given.
2253 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2254 TemplateLoc, RAngleLoc, Converted))
2255 return true;
2256
2257 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002258 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002259
Douglas Gregor84d49a22009-11-11 21:54:23 +00002260 // We have a default template argument that we will use.
2261 TemplateArgumentLoc Arg;
2262
2263 // Retrieve the default template argument from the template
2264 // parameter. For each kind of template parameter, we substitute the
2265 // template arguments provided thus far and any "outer" template arguments
2266 // (when the template parameter was part of a nested template) into
2267 // the default argument.
2268 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2269 if (!TTP->hasDefaultArgument()) {
2270 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2271 break;
2272 }
2273
John McCallbcd03502009-12-07 02:54:59 +00002274 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002275 Template,
2276 TemplateLoc,
2277 RAngleLoc,
2278 TTP,
2279 Converted);
2280 if (!ArgType)
2281 return true;
2282
2283 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2284 ArgType);
2285 } else if (NonTypeTemplateParmDecl *NTTP
2286 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2287 if (!NTTP->hasDefaultArgument()) {
2288 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2289 break;
2290 }
2291
John McCalldadc5752010-08-24 06:29:42 +00002292 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002293 TemplateLoc,
2294 RAngleLoc,
2295 NTTP,
2296 Converted);
2297 if (E.isInvalid())
2298 return true;
2299
2300 Expr *Ex = E.takeAs<Expr>();
2301 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2302 } else {
2303 TemplateTemplateParmDecl *TempParm
2304 = cast<TemplateTemplateParmDecl>(*Param);
2305
2306 if (!TempParm->hasDefaultArgument()) {
2307 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2308 break;
2309 }
2310
2311 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2312 TemplateLoc,
2313 RAngleLoc,
2314 TempParm,
2315 Converted);
2316 if (Name.isNull())
2317 return true;
2318
2319 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2320 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2321 TempParm->getDefaultArgument().getTemplateNameLoc());
2322 }
2323
2324 // Introduce an instantiation record that describes where we are using
2325 // the default template argument.
2326 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2327 Converted.getFlatArguments(),
2328 Converted.flatSize(),
2329 SourceRange(TemplateLoc, RAngleLoc));
2330
2331 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002332 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002333 RAngleLoc, Converted))
2334 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002335 }
2336
2337 return Invalid;
2338}
2339
2340/// \brief Check a template argument against its corresponding
2341/// template type parameter.
2342///
2343/// This routine implements the semantics of C++ [temp.arg.type]. It
2344/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002345bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002346 TypeSourceInfo *ArgInfo) {
2347 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002348 QualType Arg = ArgInfo->getType();
2349
Douglas Gregord32e0282009-02-09 23:23:08 +00002350 // C++ [temp.arg.type]p2:
2351 // A local type, a type with no linkage, an unnamed type or a type
2352 // compounded from any of these types shall not be used as a
2353 // template-argument for a template type-parameter.
2354 //
Douglas Gregor959d5a02010-05-22 16:17:30 +00002355 // FIXME: Perform the unnamed type check.
2356 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002357 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002358 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002359 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002360 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002361 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002362 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002363 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall0ad16662009-10-29 08:12:44 +00002364 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2365 << QualType(Tag, 0) << SR;
2366 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002367 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002368 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002369 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2370 return true;
Douglas Gregor959d5a02010-05-22 16:17:30 +00002371 } else if (Arg->isVariablyModifiedType()) {
2372 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2373 << Arg;
2374 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002375 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002376 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002377 }
2378
2379 return false;
2380}
2381
Douglas Gregorccb07762009-02-11 19:52:55 +00002382/// \brief Checks whether the given template argument is the address
2383/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002384static bool
2385CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2386 NonTypeTemplateParmDecl *Param,
2387 QualType ParamType,
2388 Expr *ArgIn,
2389 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002390 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002391 Expr *Arg = ArgIn;
2392 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002393
2394 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002395 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002396 Arg = Cast->getSubExpr();
2397
2398 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002399 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002400 // A template-argument for a non-type, non-template
2401 // template-parameter shall be one of: [...]
2402 //
2403 // -- the address of an object or function with external
2404 // linkage, including function templates and function
2405 // template-ids but excluding non-static class members,
2406 // expressed as & id-expression where the & is optional if
2407 // the name refers to a function or array, or if the
2408 // corresponding template-parameter is a reference; or
2409 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002410
Douglas Gregorccb07762009-02-11 19:52:55 +00002411 // Ignore (and complain about) any excess parentheses.
2412 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2413 if (!Invalid) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002414 S.Diag(Arg->getSourceRange().getBegin(),
2415 diag::err_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002416 << Arg->getSourceRange();
2417 Invalid = true;
2418 }
2419
2420 Arg = Parens->getSubExpr();
2421 }
2422
Douglas Gregorb242683d2010-04-01 18:32:35 +00002423 bool AddressTaken = false;
2424 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002425 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00002426 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002427 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002428 AddressTaken = true;
2429 AddrOpLoc = UnOp->getOperatorLoc();
2430 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002431 } else
2432 DRE = dyn_cast<DeclRefExpr>(Arg);
2433
Douglas Gregorb242683d2010-04-01 18:32:35 +00002434 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002435 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2436 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002437 S.Diag(Param->getLocation(), diag::note_template_param_here);
2438 return true;
2439 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002440
2441 // Stop checking the precise nature of the argument if it is value dependent,
2442 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002443 if (Arg->isValueDependent()) {
2444 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002445 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002446 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002447
Douglas Gregorb242683d2010-04-01 18:32:35 +00002448 if (!isa<ValueDecl>(DRE->getDecl())) {
2449 S.Diag(Arg->getSourceRange().getBegin(),
2450 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002451 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002452 S.Diag(Param->getLocation(), diag::note_template_param_here);
2453 return true;
2454 }
2455
2456 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002457
2458 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002459 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2460 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002461 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002462 S.Diag(Param->getLocation(), diag::note_template_param_here);
2463 return true;
2464 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002465
2466 // Cannot refer to non-static member functions
2467 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002468 if (!Method->isStatic()) {
2469 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002470 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002471 S.Diag(Param->getLocation(), diag::note_template_param_here);
2472 return true;
2473 }
Mike Stump11289f42009-09-09 15:08:12 +00002474
Douglas Gregorccb07762009-02-11 19:52:55 +00002475 // Functions must have external linkage.
2476 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002477 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002478 S.Diag(Arg->getSourceRange().getBegin(),
2479 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002480 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002481 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002482 << true;
2483 return true;
2484 }
2485
2486 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002487 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002488
Douglas Gregorb242683d2010-04-01 18:32:35 +00002489 // If the template parameter has pointer type, the function decays.
2490 if (ParamType->isPointerType() && !AddressTaken)
2491 ArgType = S.Context.getPointerType(Func->getType());
2492 else if (AddressTaken && ParamType->isReferenceType()) {
2493 // If we originally had an address-of operator, but the
2494 // parameter has reference type, complain and (if things look
2495 // like they will work) drop the address-of operator.
2496 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2497 ParamType.getNonReferenceType())) {
2498 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2499 << ParamType;
2500 S.Diag(Param->getLocation(), diag::note_template_param_here);
2501 return true;
2502 }
2503
2504 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2505 << ParamType
2506 << FixItHint::CreateRemoval(AddrOpLoc);
2507 S.Diag(Param->getLocation(), diag::note_template_param_here);
2508
2509 ArgType = Func->getType();
2510 }
2511 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002512 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002513 S.Diag(Arg->getSourceRange().getBegin(),
2514 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002515 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002516 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002517 << true;
2518 return true;
2519 }
2520
Douglas Gregorb242683d2010-04-01 18:32:35 +00002521 // A value of reference type is not an object.
2522 if (Var->getType()->isReferenceType()) {
2523 S.Diag(Arg->getSourceRange().getBegin(),
2524 diag::err_template_arg_reference_var)
2525 << Var->getType() << Arg->getSourceRange();
2526 S.Diag(Param->getLocation(), diag::note_template_param_here);
2527 return true;
2528 }
2529
Douglas Gregorccb07762009-02-11 19:52:55 +00002530 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002531 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002532
2533 // If the template parameter has pointer type, we must have taken
2534 // the address of this object.
2535 if (ParamType->isReferenceType()) {
2536 if (AddressTaken) {
2537 // If we originally had an address-of operator, but the
2538 // parameter has reference type, complain and (if things look
2539 // like they will work) drop the address-of operator.
2540 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2541 ParamType.getNonReferenceType())) {
2542 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2543 << ParamType;
2544 S.Diag(Param->getLocation(), diag::note_template_param_here);
2545 return true;
2546 }
2547
2548 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2549 << ParamType
2550 << FixItHint::CreateRemoval(AddrOpLoc);
2551 S.Diag(Param->getLocation(), diag::note_template_param_here);
2552
2553 ArgType = Var->getType();
2554 }
2555 } else if (!AddressTaken && ParamType->isPointerType()) {
2556 if (Var->getType()->isArrayType()) {
2557 // Array-to-pointer decay.
2558 ArgType = S.Context.getArrayDecayedType(Var->getType());
2559 } else {
2560 // If the template parameter has pointer type but the address of
2561 // this object was not taken, complain and (possibly) recover by
2562 // taking the address of the entity.
2563 ArgType = S.Context.getPointerType(Var->getType());
2564 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2565 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2566 << ParamType;
2567 S.Diag(Param->getLocation(), diag::note_template_param_here);
2568 return true;
2569 }
2570
2571 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2572 << ParamType
2573 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2574
2575 S.Diag(Param->getLocation(), diag::note_template_param_here);
2576 }
2577 }
2578 } else {
2579 // We found something else, but we don't know specifically what it is.
2580 S.Diag(Arg->getSourceRange().getBegin(),
2581 diag::err_template_arg_not_object_or_func)
2582 << Arg->getSourceRange();
2583 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2584 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002585 }
Mike Stump11289f42009-09-09 15:08:12 +00002586
Douglas Gregorb242683d2010-04-01 18:32:35 +00002587 if (ParamType->isPointerType() &&
2588 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2589 S.IsQualificationConversion(ArgType, ParamType)) {
2590 // For pointer-to-object types, qualification conversions are
2591 // permitted.
2592 } else {
2593 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2594 if (!ParamRef->getPointeeType()->isFunctionType()) {
2595 // C++ [temp.arg.nontype]p5b3:
2596 // For a non-type template-parameter of type reference to
2597 // object, no conversions apply. The type referred to by the
2598 // reference may be more cv-qualified than the (otherwise
2599 // identical) type of the template- argument. The
2600 // template-parameter is bound directly to the
2601 // template-argument, which shall be an lvalue.
2602
2603 // FIXME: Other qualifiers?
2604 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2605 unsigned ArgQuals = ArgType.getCVRQualifiers();
2606
2607 if ((ParamQuals | ArgQuals) != ParamQuals) {
2608 S.Diag(Arg->getSourceRange().getBegin(),
2609 diag::err_template_arg_ref_bind_ignores_quals)
2610 << ParamType << Arg->getType()
2611 << Arg->getSourceRange();
2612 S.Diag(Param->getLocation(), diag::note_template_param_here);
2613 return true;
2614 }
2615 }
2616 }
2617
2618 // At this point, the template argument refers to an object or
2619 // function with external linkage. We now need to check whether the
2620 // argument and parameter types are compatible.
2621 if (!S.Context.hasSameUnqualifiedType(ArgType,
2622 ParamType.getNonReferenceType())) {
2623 // We can't perform this conversion or binding.
2624 if (ParamType->isReferenceType())
2625 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2626 << ParamType << Arg->getType() << Arg->getSourceRange();
2627 else
2628 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2629 << Arg->getType() << ParamType << Arg->getSourceRange();
2630 S.Diag(Param->getLocation(), diag::note_template_param_here);
2631 return true;
2632 }
2633 }
2634
2635 // Create the template argument.
2636 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002637 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002638 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002639}
2640
2641/// \brief Checks whether the given template argument is a pointer to
2642/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002643bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2644 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002645 bool Invalid = false;
2646
2647 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002648 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002649 Arg = Cast->getSubExpr();
2650
2651 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002652 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002653 // A template-argument for a non-type, non-template
2654 // template-parameter shall be one of: [...]
2655 //
2656 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002657 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002658
2659 // Ignore (and complain about) any excess parentheses.
2660 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2661 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002662 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002663 diag::err_template_arg_extra_parens)
2664 << Arg->getSourceRange();
2665 Invalid = true;
2666 }
2667
2668 Arg = Parens->getSubExpr();
2669 }
2670
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002671 // A pointer-to-member constant written &Class::member.
2672 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00002673 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002674 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2675 if (DRE && !DRE->getQualifier())
2676 DRE = 0;
2677 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002678 }
2679 // A constant of pointer-to-member type.
2680 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2681 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2682 if (VD->getType()->isMemberPointerType()) {
2683 if (isa<NonTypeTemplateParmDecl>(VD) ||
2684 (isa<VarDecl>(VD) &&
2685 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2686 if (Arg->isTypeDependent() || Arg->isValueDependent())
2687 Converted = TemplateArgument(Arg->Retain());
2688 else
2689 Converted = TemplateArgument(VD->getCanonicalDecl());
2690 return Invalid;
2691 }
2692 }
2693 }
2694
2695 DRE = 0;
2696 }
2697
Douglas Gregorccb07762009-02-11 19:52:55 +00002698 if (!DRE)
2699 return Diag(Arg->getSourceRange().getBegin(),
2700 diag::err_template_arg_not_pointer_to_member_form)
2701 << Arg->getSourceRange();
2702
2703 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2704 assert((isa<FieldDecl>(DRE->getDecl()) ||
2705 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2706 "Only non-static member pointers can make it here");
2707
2708 // Okay: this is the address of a non-static member, and therefore
2709 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002710 if (Arg->isTypeDependent() || Arg->isValueDependent())
2711 Converted = TemplateArgument(Arg->Retain());
2712 else
2713 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002714 return Invalid;
2715 }
2716
2717 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002718 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002719 diag::err_template_arg_not_pointer_to_member_form)
2720 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002721 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002722 diag::note_template_arg_refers_here);
2723 return true;
2724}
2725
Douglas Gregord32e0282009-02-09 23:23:08 +00002726/// \brief Check a template argument against its corresponding
2727/// non-type template parameter.
2728///
Douglas Gregor463421d2009-03-03 04:44:36 +00002729/// This routine implements the semantics of C++ [temp.arg.nontype].
2730/// It returns true if an error occurred, and false otherwise. \p
2731/// InstantiatedParamType is the type of the non-type template
2732/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002733///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002734/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002735bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002736 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002737 TemplateArgument &Converted,
2738 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002739 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2740
Douglas Gregor86560402009-02-10 23:36:10 +00002741 // If either the parameter has a dependent type or the argument is
2742 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002743 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2744 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002745 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002746 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002747 }
Douglas Gregor86560402009-02-10 23:36:10 +00002748
2749 // C++ [temp.arg.nontype]p5:
2750 // The following conversions are performed on each expression used
2751 // as a non-type template-argument. If a non-type
2752 // template-argument cannot be converted to the type of the
2753 // corresponding template-parameter then the program is
2754 // ill-formed.
2755 //
2756 // -- for a non-type template-parameter of integral or
2757 // enumeration type, integral promotions (4.5) and integral
2758 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002759 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002760 QualType ArgType = Arg->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +00002761 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002762 // C++ [temp.arg.nontype]p1:
2763 // A template-argument for a non-type, non-template
2764 // template-parameter shall be one of:
2765 //
2766 // -- an integral constant-expression of integral or enumeration
2767 // type; or
2768 // -- the name of a non-type template-parameter; or
2769 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002770 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00002771 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002772 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002773 diag::err_template_arg_not_integral_or_enumeral)
2774 << ArgType << Arg->getSourceRange();
2775 Diag(Param->getLocation(), diag::note_template_param_here);
2776 return true;
2777 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002778 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002779 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2780 << ArgType << Arg->getSourceRange();
2781 return true;
2782 }
2783
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002784 // From here on out, all we care about are the unqualified forms
2785 // of the parameter and argument types.
2786 ParamType = ParamType.getUnqualifiedType();
2787 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00002788
2789 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002790 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002791 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002792 } else if (CTAK == CTAK_Deduced) {
2793 // C++ [temp.deduct.type]p17:
2794 // If, in the declaration of a function template with a non-type
2795 // template-parameter, the non-type template- parameter is used
2796 // in an expression in the function parameter-list and, if the
2797 // corresponding template-argument is deduced, the
2798 // template-argument type shall match the type of the
2799 // template-parameter exactly, except that a template-argument
2800 // deduced from an array bound may be of any integral type.
2801 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2802 << ArgType << ParamType;
2803 Diag(Param->getLocation(), diag::note_template_param_here);
2804 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00002805 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2806 !ParamType->isEnumeralType()) {
2807 // This is an integral promotion or conversion.
John McCalle3027922010-08-25 11:45:40 +00002808 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002809 } else {
2810 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002811 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002812 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002813 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002814 Diag(Param->getLocation(), diag::note_template_param_here);
2815 return true;
2816 }
2817
Douglas Gregor52aba872009-03-14 00:20:21 +00002818 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002819 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002820 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002821
2822 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002823 llvm::APSInt OldValue = Value;
2824
2825 // Coerce the template argument's value to the value it will have
2826 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002827 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002828 if (Value.getBitWidth() != AllowedBits)
2829 Value.extOrTrunc(AllowedBits);
2830 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002831
2832 // Complain if an unsigned parameter received a negative value.
2833 if (IntegerType->isUnsignedIntegerType()
2834 && (OldValue.isSigned() && OldValue.isNegative())) {
2835 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2836 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2837 << Arg->getSourceRange();
2838 Diag(Param->getLocation(), diag::note_template_param_here);
2839 }
2840
2841 // Complain if we overflowed the template parameter's type.
2842 unsigned RequiredBits;
2843 if (IntegerType->isUnsignedIntegerType())
2844 RequiredBits = OldValue.getActiveBits();
2845 else if (OldValue.isUnsigned())
2846 RequiredBits = OldValue.getActiveBits() + 1;
2847 else
2848 RequiredBits = OldValue.getMinSignedBits();
2849 if (RequiredBits > AllowedBits) {
2850 Diag(Arg->getSourceRange().getBegin(),
2851 diag::warn_template_arg_too_large)
2852 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2853 << Arg->getSourceRange();
2854 Diag(Param->getLocation(), diag::note_template_param_here);
2855 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002856 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002857
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002858 // Add the value of this argument to the list of converted
2859 // arguments. We use the bitwidth and signedness of the template
2860 // parameter.
2861 if (Arg->isValueDependent()) {
2862 // The argument is value-dependent. Create a new
2863 // TemplateArgument with the converted expression.
2864 Converted = TemplateArgument(Arg);
2865 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002866 }
2867
John McCall0ad16662009-10-29 08:12:44 +00002868 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002869 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002870 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002871 return false;
2872 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002873
John McCall16df1e52010-03-30 21:47:33 +00002874 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2875
Douglas Gregorb242683d2010-04-01 18:32:35 +00002876 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2877 // from a template argument of type std::nullptr_t to a non-type
2878 // template parameter of type pointer to object, pointer to
2879 // function, or pointer-to-member, respectively.
2880 if (ArgType->isNullPtrType() &&
2881 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2882 Converted = TemplateArgument((NamedDecl *)0);
2883 return false;
2884 }
2885
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002886 // Handle pointer-to-function, reference-to-function, and
2887 // pointer-to-member-function all in (roughly) the same way.
2888 if (// -- For a non-type template-parameter of type pointer to
2889 // function, only the function-to-pointer conversion (4.3) is
2890 // applied. If the template-argument represents a set of
2891 // overloaded functions (or a pointer to such), the matching
2892 // function is selected from the set (13.4).
2893 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002894 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002895 // -- For a non-type template-parameter of type reference to
2896 // function, no conversions apply. If the template-argument
2897 // represents a set of overloaded functions, the matching
2898 // function is selected from the set (13.4).
2899 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002900 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002901 // -- For a non-type template-parameter of type pointer to
2902 // member function, no conversions apply. If the
2903 // template-argument represents a set of overloaded member
2904 // functions, the matching member function is selected from
2905 // the set (13.4).
2906 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002907 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002908 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002909
Douglas Gregor064fdb22010-04-14 23:11:21 +00002910 if (Arg->getType() == Context.OverloadTy) {
2911 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2912 true,
2913 FoundResult)) {
2914 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2915 return true;
2916
2917 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2918 ArgType = Arg->getType();
2919 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00002920 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002921 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002922
Douglas Gregorb242683d2010-04-01 18:32:35 +00002923 if (!ParamType->isMemberPointerType())
2924 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2925 ParamType,
2926 Arg, Converted);
2927
2928 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCalle3027922010-08-25 11:45:40 +00002929 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb242683d2010-04-01 18:32:35 +00002930 } else if (!Context.hasSameUnqualifiedType(ArgType,
2931 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002932 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002933 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002934 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002935 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002936 Diag(Param->getLocation(), diag::note_template_param_here);
2937 return true;
2938 }
Mike Stump11289f42009-09-09 15:08:12 +00002939
Douglas Gregorb242683d2010-04-01 18:32:35 +00002940 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002941 }
2942
Chris Lattner696197c2009-02-20 21:37:53 +00002943 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002944 // -- for a non-type template-parameter of type pointer to
2945 // object, qualification conversions (4.4) and the
2946 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002947 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00002948 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002949 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002950
Douglas Gregorb242683d2010-04-01 18:32:35 +00002951 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2952 ParamType,
2953 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00002954 }
Mike Stump11289f42009-09-09 15:08:12 +00002955
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002956 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002957 // -- For a non-type template-parameter of type reference to
2958 // object, no conversions apply. The type referred to by the
2959 // reference may be more cv-qualified than the (otherwise
2960 // identical) type of the template-argument. The
2961 // template-parameter is bound directly to the
2962 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00002963 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002964 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002965
Douglas Gregor064fdb22010-04-14 23:11:21 +00002966 if (Arg->getType() == Context.OverloadTy) {
2967 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2968 ParamRefType->getPointeeType(),
2969 true,
2970 FoundResult)) {
2971 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2972 return true;
2973
2974 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2975 ArgType = Arg->getType();
2976 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00002977 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002978 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002979
Douglas Gregorb242683d2010-04-01 18:32:35 +00002980 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2981 ParamType,
2982 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002983 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002984
2985 // -- For a non-type template-parameter of type pointer to data
2986 // member, qualification conversions (4.4) are applied.
2987 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2988
Douglas Gregor1515f762009-02-11 18:22:40 +00002989 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002990 // Types match exactly: nothing more to do here.
2991 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCalle3027922010-08-25 11:45:40 +00002992 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor0e558532009-02-11 16:16:59 +00002993 } else {
2994 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002995 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002996 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002997 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002998 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002999 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00003000 }
3001
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00003002 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00003003}
3004
3005/// \brief Check a template argument against its corresponding
3006/// template template parameter.
3007///
3008/// This routine implements the semantics of C++ [temp.arg.template].
3009/// It returns true if an error occurred, and false otherwise.
3010bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003011 const TemplateArgumentLoc &Arg) {
3012 TemplateName Name = Arg.getArgument().getAsTemplate();
3013 TemplateDecl *Template = Name.getAsTemplateDecl();
3014 if (!Template) {
3015 // Any dependent template name is fine.
3016 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3017 return false;
3018 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003019
3020 // C++ [temp.arg.template]p1:
3021 // A template-argument for a template template-parameter shall be
3022 // the name of a class template, expressed as id-expression. Only
3023 // primary class templates are considered when matching the
3024 // template template argument with the corresponding parameter;
3025 // partial specializations are not considered even if their
3026 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003027 //
3028 // Note that we also allow template template parameters here, which
3029 // will happen when we are dealing with, e.g., class template
3030 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003031 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003032 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003033 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003034 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003035 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003036 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003037 << Template;
3038 }
3039
3040 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3041 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003042 true,
3043 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003044 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003045}
3046
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003047/// \brief Given a non-type template argument that refers to a
3048/// declaration and the type of its corresponding non-type template
3049/// parameter, produce an expression that properly refers to that
3050/// declaration.
John McCalldadc5752010-08-24 06:29:42 +00003051ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003052Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3053 QualType ParamType,
3054 SourceLocation Loc) {
3055 assert(Arg.getKind() == TemplateArgument::Declaration &&
3056 "Only declaration template arguments permitted here");
3057 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3058
3059 if (VD->getDeclContext()->isRecord() &&
3060 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3061 // If the value is a class member, we might have a pointer-to-member.
3062 // Determine whether the non-type template template parameter is of
3063 // pointer-to-member type. If so, we need to build an appropriate
3064 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3065 // would refer to the member itself.
3066 if (ParamType->isMemberPointerType()) {
3067 QualType ClassType
3068 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3069 NestedNameSpecifier *Qualifier
John McCallb268a282010-08-23 23:25:46 +00003070 = NestedNameSpecifier::Create(Context, 0, false,
3071 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003072 CXXScopeSpec SS;
3073 SS.setScopeRep(Qualifier);
John McCalldadc5752010-08-24 06:29:42 +00003074 ExprResult RefExpr = BuildDeclRefExpr(VD,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003075 VD->getType().getNonReferenceType(),
3076 Loc,
3077 &SS);
3078 if (RefExpr.isInvalid())
3079 return ExprError();
3080
John McCalle3027922010-08-25 11:45:40 +00003081 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003082
3083 // We might need to perform a trailing qualification conversion, since
3084 // the element type on the parameter could be more qualified than the
3085 // element type in the expression we constructed.
3086 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3087 ParamType.getUnqualifiedType())) {
3088 Expr *RefE = RefExpr.takeAs<Expr>();
John McCalle3027922010-08-25 11:45:40 +00003089 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003090 RefExpr = Owned(RefE);
3091 }
3092
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003093 assert(!RefExpr.isInvalid() &&
3094 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003095 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003096 return move(RefExpr);
3097 }
3098 }
3099
3100 QualType T = VD->getType().getNonReferenceType();
3101 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003102 // When the non-type template parameter is a pointer, take the
3103 // address of the declaration.
John McCalldadc5752010-08-24 06:29:42 +00003104 ExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003105 if (RefExpr.isInvalid())
3106 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003107
3108 if (T->isFunctionType() || T->isArrayType()) {
3109 // Decay functions and arrays.
3110 Expr *RefE = (Expr *)RefExpr.get();
3111 DefaultFunctionArrayConversion(RefE);
3112 if (RefE != RefExpr.get()) {
3113 RefExpr.release();
3114 RefExpr = Owned(RefE);
3115 }
3116
3117 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003118 }
3119
Douglas Gregorb242683d2010-04-01 18:32:35 +00003120 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00003121 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003122 }
3123
3124 // If the non-type template parameter has reference type, qualify the
3125 // resulting declaration reference with the extra qualifiers on the
3126 // type that the reference refers to.
3127 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3128 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3129
3130 return BuildDeclRefExpr(VD, T, Loc);
3131}
3132
3133/// \brief Construct a new expression that refers to the given
3134/// integral template argument with the given source-location
3135/// information.
3136///
3137/// This routine takes care of the mapping from an integral template
3138/// argument (which may have any integral type) to the appropriate
3139/// literal value.
John McCalldadc5752010-08-24 06:29:42 +00003140ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003141Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3142 SourceLocation Loc) {
3143 assert(Arg.getKind() == TemplateArgument::Integral &&
3144 "Operation is only value for integral template arguments");
3145 QualType T = Arg.getIntegralType();
3146 if (T->isCharType() || T->isWideCharType())
3147 return Owned(new (Context) CharacterLiteral(
3148 Arg.getAsIntegral()->getZExtValue(),
3149 T->isWideCharType(),
3150 T,
3151 Loc));
3152 if (T->isBooleanType())
3153 return Owned(new (Context) CXXBoolLiteralExpr(
3154 Arg.getAsIntegral()->getBoolValue(),
3155 T,
3156 Loc));
3157
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003158 return Owned(IntegerLiteral::Create(Context, *Arg.getAsIntegral(), T, Loc));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003159}
3160
3161
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003162/// \brief Determine whether the given template parameter lists are
3163/// equivalent.
3164///
Mike Stump11289f42009-09-09 15:08:12 +00003165/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003166/// source code as part of a new template declaration.
3167///
3168/// \param Old The old template parameter list, typically found via
3169/// name lookup of the template declared with this template parameter
3170/// list.
3171///
3172/// \param Complain If true, this routine will produce a diagnostic if
3173/// the template parameter lists are not equivalent.
3174///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003175/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003176///
3177/// \param TemplateArgLoc If this source location is valid, then we
3178/// are actually checking the template parameter list of a template
3179/// argument (New) against the template parameter list of its
3180/// corresponding template template parameter (Old). We produce
3181/// slightly different diagnostics in this scenario.
3182///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003183/// \returns True if the template parameter lists are equal, false
3184/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003185bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003186Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3187 TemplateParameterList *Old,
3188 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003189 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003190 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003191 if (Old->size() != New->size()) {
3192 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003193 unsigned NextDiag = diag::err_template_param_list_different_arity;
3194 if (TemplateArgLoc.isValid()) {
3195 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3196 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003197 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003198 Diag(New->getTemplateLoc(), NextDiag)
3199 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003200 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003201 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003202 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003203 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003204 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3205 }
3206
3207 return false;
3208 }
3209
3210 for (TemplateParameterList::iterator OldParm = Old->begin(),
3211 OldParmEnd = Old->end(), NewParm = New->begin();
3212 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3213 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003214 if (Complain) {
3215 unsigned NextDiag = diag::err_template_param_different_kind;
3216 if (TemplateArgLoc.isValid()) {
3217 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3218 NextDiag = diag::note_template_param_different_kind;
3219 }
3220 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003221 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003222 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003223 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003224 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003225 return false;
3226 }
3227
Douglas Gregor2e87ca22010-06-04 08:34:32 +00003228 if (TemplateTypeParmDecl *OldTTP
3229 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3230 // Template type parameters are equivalent if either both are template
3231 // type parameter packs or neither are (since we know we're at the same
3232 // index).
3233 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3234 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3235 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3236 // allow one to match a template parameter pack in the template
3237 // parameter list of a template template parameter to one or more
3238 // template parameters in the template parameter list of the
3239 // corresponding template template argument.
3240 if (Complain) {
3241 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3242 if (TemplateArgLoc.isValid()) {
3243 Diag(TemplateArgLoc,
3244 diag::err_template_arg_template_params_mismatch);
3245 NextDiag = diag::note_template_parameter_pack_non_pack;
3246 }
3247 Diag(NewTTP->getLocation(), NextDiag)
3248 << 0 << NewTTP->isParameterPack();
3249 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3250 << 0 << OldTTP->isParameterPack();
3251 }
3252 return false;
3253 }
Mike Stump11289f42009-09-09 15:08:12 +00003254 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003255 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3256 // The types of non-type template parameters must agree.
3257 NonTypeTemplateParmDecl *NewNTTP
3258 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003259
3260 // If we are matching a template template argument to a template
3261 // template parameter and one of the non-type template parameter types
3262 // is dependent, then we must wait until template instantiation time
3263 // to actually compare the arguments.
3264 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3265 (OldNTTP->getType()->isDependentType() ||
3266 NewNTTP->getType()->isDependentType()))
3267 continue;
3268
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003269 if (Context.getCanonicalType(OldNTTP->getType()) !=
3270 Context.getCanonicalType(NewNTTP->getType())) {
3271 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003272 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3273 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003274 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003275 diag::err_template_arg_template_params_mismatch);
3276 NextDiag = diag::note_template_nontype_parm_different_type;
3277 }
3278 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003279 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003280 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003281 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003282 diag::note_template_nontype_parm_prev_declaration)
3283 << OldNTTP->getType();
3284 }
3285 return false;
3286 }
3287 } else {
3288 // The template parameter lists of template template
3289 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003290 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003291 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003292 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003293 = cast<TemplateTemplateParmDecl>(*OldParm);
3294 TemplateTemplateParmDecl *NewTTP
3295 = cast<TemplateTemplateParmDecl>(*NewParm);
3296 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3297 OldTTP->getTemplateParameters(),
3298 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003299 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003300 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003301 return false;
3302 }
3303 }
3304
3305 return true;
3306}
3307
3308/// \brief Check whether a template can be declared within this scope.
3309///
3310/// If the template declaration is valid in this scope, returns
3311/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003312bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003313Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003314 // Find the nearest enclosing declaration scope.
3315 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3316 (S->getFlags() & Scope::TemplateParamScope) != 0)
3317 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003318
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003319 // C++ [temp]p2:
3320 // A template-declaration can appear only as a namespace scope or
3321 // class scope declaration.
3322 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003323 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3324 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003325 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003326 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003327
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003328 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003329 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003330
3331 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3332 return false;
3333
Mike Stump11289f42009-09-09 15:08:12 +00003334 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003335 diag::err_template_outside_namespace_or_class_scope)
3336 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003337}
Douglas Gregor67a65642009-02-17 23:15:12 +00003338
Douglas Gregor54888652009-10-07 00:13:32 +00003339/// \brief Determine what kind of template specialization the given declaration
3340/// is.
3341static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3342 if (!D)
3343 return TSK_Undeclared;
3344
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003345 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3346 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003347 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3348 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003349 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3350 return Var->getTemplateSpecializationKind();
3351
Douglas Gregor54888652009-10-07 00:13:32 +00003352 return TSK_Undeclared;
3353}
3354
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003355/// \brief Check whether a specialization is well-formed in the current
3356/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003357///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003358/// This routine determines whether a template specialization can be declared
3359/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003360///
3361/// \param S the semantic analysis object for which this check is being
3362/// performed.
3363///
3364/// \param Specialized the entity being specialized or instantiated, which
3365/// may be a kind of template (class template, function template, etc.) or
3366/// a member of a class template (member function, static data member,
3367/// member class).
3368///
3369/// \param PrevDecl the previous declaration of this entity, if any.
3370///
3371/// \param Loc the location of the explicit specialization or instantiation of
3372/// this entity.
3373///
3374/// \param IsPartialSpecialization whether this is a partial specialization of
3375/// a class template.
3376///
Douglas Gregor54888652009-10-07 00:13:32 +00003377/// \returns true if there was an error that we cannot recover from, false
3378/// otherwise.
3379static bool CheckTemplateSpecializationScope(Sema &S,
3380 NamedDecl *Specialized,
3381 NamedDecl *PrevDecl,
3382 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003383 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003384 // Keep these "kind" numbers in sync with the %select statements in the
3385 // various diagnostics emitted by this routine.
3386 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003387 bool isTemplateSpecialization = false;
3388 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003389 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003390 isTemplateSpecialization = true;
3391 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003392 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003393 isTemplateSpecialization = true;
3394 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003395 EntityKind = 3;
3396 else if (isa<VarDecl>(Specialized))
3397 EntityKind = 4;
3398 else if (isa<RecordDecl>(Specialized))
3399 EntityKind = 5;
3400 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003401 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3402 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003403 return true;
3404 }
3405
Douglas Gregorf47b9112009-02-25 22:02:03 +00003406 // C++ [temp.expl.spec]p2:
3407 // An explicit specialization shall be declared in the namespace
3408 // of which the template is a member, or, for member templates, in
3409 // the namespace of which the enclosing class or enclosing class
3410 // template is a member. An explicit specialization of a member
3411 // function, member class or static data member of a class
3412 // template shall be declared in the namespace of which the class
3413 // template is a member. Such a declaration may also be a
3414 // definition. If the declaration is not a definition, the
3415 // specialization may be defined later in the name- space in which
3416 // the explicit specialization was declared, or in a namespace
3417 // that encloses the one in which the explicit specialization was
3418 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00003419 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00003420 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003421 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003422 return true;
3423 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003424
Douglas Gregor40fb7442009-10-07 17:30:37 +00003425 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3426 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003427 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003428 return true;
3429 }
3430
Douglas Gregore4b05162009-10-07 17:21:34 +00003431 // C++ [temp.class.spec]p6:
3432 // A class template partial specialization may be declared or redeclared
3433 // in any namespace scope in which its definition may be defined (14.5.1
3434 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003435 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003436 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003437 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003438 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003439 if ((!PrevDecl ||
3440 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3441 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3442 // There is no prior declaration of this entity, so this
3443 // specialization must be in the same context as the template
Sebastian Redl35034562010-08-31 00:36:40 +00003444 // itself, or in the enclosing namespace set.
3445 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003446 if (isa<TranslationUnitDecl>(SpecializedContext))
3447 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3448 << EntityKind << Specialized;
3449 else if (isa<NamespaceDecl>(SpecializedContext))
3450 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3451 << EntityKind << Specialized
3452 << cast<NamedDecl>(SpecializedContext);
3453
3454 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3455 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003456 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003457 }
Douglas Gregor54888652009-10-07 00:13:32 +00003458
3459 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003460 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003461 // Note that HandleDeclarator() performs this check for explicit
3462 // specializations of function templates, static data members, and member
3463 // functions, so we skip the check here for those kinds of entities.
3464 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003465 // Should we refactor that check, so that it occurs later?
3466 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003467 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3468 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003469 if (isa<TranslationUnitDecl>(SpecializedContext))
3470 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3471 << EntityKind << Specialized;
3472 else if (isa<NamespaceDecl>(SpecializedContext))
3473 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3474 << EntityKind << Specialized
3475 << cast<NamedDecl>(SpecializedContext);
3476
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003477 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003478 }
Douglas Gregor54888652009-10-07 00:13:32 +00003479
3480 // FIXME: check for specialization-after-instantiation errors and such.
3481
Douglas Gregorf47b9112009-02-25 22:02:03 +00003482 return false;
3483}
Douglas Gregor54888652009-10-07 00:13:32 +00003484
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003485/// \brief Check the non-type template arguments of a class template
3486/// partial specialization according to C++ [temp.class.spec]p9.
3487///
Douglas Gregor09a30232009-06-12 22:08:06 +00003488/// \param TemplateParams the template parameters of the primary class
3489/// template.
3490///
3491/// \param TemplateArg the template arguments of the class template
3492/// partial specialization.
3493///
3494/// \param MirrorsPrimaryTemplate will be set true if the class
3495/// template partial specialization arguments are identical to the
3496/// implicit template arguments of the primary template. This is not
3497/// necessarily an error (C++0x), and it is left to the caller to diagnose
3498/// this condition when it is an error.
3499///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003500/// \returns true if there was an error, false otherwise.
3501bool Sema::CheckClassTemplatePartialSpecializationArgs(
3502 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003503 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003504 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003505 // FIXME: the interface to this function will have to change to
3506 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003507 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003508
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003509 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003510
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003511 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003512 // Determine whether the template argument list of the partial
3513 // specialization is identical to the implicit argument list of
3514 // the primary template. The caller may need to diagnostic this as
3515 // an error per C++ [temp.class.spec]p9b3.
3516 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003517 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003518 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3519 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003520 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003521 MirrorsPrimaryTemplate = false;
3522 } else if (TemplateTemplateParmDecl *TTP
3523 = dyn_cast<TemplateTemplateParmDecl>(
3524 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003525 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003526 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003527 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003528 if (!ArgDecl ||
3529 ArgDecl->getIndex() != TTP->getIndex() ||
3530 ArgDecl->getDepth() != TTP->getDepth())
3531 MirrorsPrimaryTemplate = false;
3532 }
3533 }
3534
Mike Stump11289f42009-09-09 15:08:12 +00003535 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003536 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003537 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003538 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003539 }
3540
Anders Carlsson40c1d492009-06-13 18:20:51 +00003541 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003542 if (!ArgExpr) {
3543 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003544 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003545 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003546
3547 // C++ [temp.class.spec]p8:
3548 // A non-type argument is non-specialized if it is the name of a
3549 // non-type parameter. All other non-type arguments are
3550 // specialized.
3551 //
3552 // Below, we check the two conditions that only apply to
3553 // specialized non-type arguments, so skip any non-specialized
3554 // arguments.
3555 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003556 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003557 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003558 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003559 (Param->getIndex() != NTTP->getIndex() ||
3560 Param->getDepth() != NTTP->getDepth()))
3561 MirrorsPrimaryTemplate = false;
3562
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003563 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003564 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003565
3566 // C++ [temp.class.spec]p9:
3567 // Within the argument list of a class template partial
3568 // specialization, the following restrictions apply:
3569 // -- A partially specialized non-type argument expression
3570 // shall not involve a template parameter of the partial
3571 // specialization except when the argument expression is a
3572 // simple identifier.
3573 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003574 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003575 diag::err_dependent_non_type_arg_in_partial_spec)
3576 << ArgExpr->getSourceRange();
3577 return true;
3578 }
3579
3580 // -- The type of a template parameter corresponding to a
3581 // specialized non-type argument shall not be dependent on a
3582 // parameter of the specialization.
3583 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003584 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003585 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3586 << Param->getType()
3587 << ArgExpr->getSourceRange();
3588 Diag(Param->getLocation(), diag::note_template_param_here);
3589 return true;
3590 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003591
3592 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003593 }
3594
3595 return false;
3596}
3597
Douglas Gregorc854c662010-02-26 06:03:23 +00003598/// \brief Retrieve the previous declaration of the given declaration.
3599static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3600 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3601 return VD->getPreviousDeclaration();
3602 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3603 return FD->getPreviousDeclaration();
3604 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3605 return TD->getPreviousDeclaration();
3606 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3607 return TD->getPreviousDeclaration();
3608 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3609 return FTD->getPreviousDeclaration();
3610 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3611 return CTD->getPreviousDeclaration();
3612 return 0;
3613}
3614
John McCall48871652010-08-21 09:40:31 +00003615DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003616Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3617 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003618 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003619 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003620 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003621 SourceLocation TemplateNameLoc,
3622 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003623 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003624 SourceLocation RAngleLoc,
3625 AttributeList *Attr,
3626 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003627 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003628
Douglas Gregor67a65642009-02-17 23:15:12 +00003629 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003630 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003631 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003632 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3633
3634 if (!ClassTemplate) {
3635 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3636 << (Name.getAsTemplateDecl() &&
3637 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3638 return true;
3639 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003640
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003641 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003642 bool isPartialSpecialization = false;
3643
Douglas Gregorf47b9112009-02-25 22:02:03 +00003644 // Check the validity of the template headers that introduce this
3645 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003646 // FIXME: We probably shouldn't complain about these headers for
3647 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003648 bool Invalid = false;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003649 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003650 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3651 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003652 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003653 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003654 isExplicitSpecialization,
3655 Invalid);
3656 if (Invalid)
3657 return true;
3658
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003659 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3660 if (TemplateParams)
3661 --NumMatchedTemplateParamLists;
3662
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003663 if (TemplateParams && TemplateParams->size() > 0) {
3664 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003665
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003666 // C++ [temp.class.spec]p10:
3667 // The template parameter list of a specialization shall not
3668 // contain default template argument values.
3669 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3670 Decl *Param = TemplateParams->getParam(I);
3671 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3672 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003673 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003674 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003675 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003676 }
3677 } else if (NonTypeTemplateParmDecl *NTTP
3678 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3679 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003680 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003681 diag::err_default_arg_in_partial_spec)
3682 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003683 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003684 }
3685 } else {
3686 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003687 if (TTP->hasDefaultArgument()) {
3688 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003689 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003690 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003691 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00003692 }
3693 }
3694 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003695 } else if (TemplateParams) {
3696 if (TUK == TUK_Friend)
3697 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003698 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003699 SourceRange(TemplateParams->getTemplateLoc(),
3700 TemplateParams->getRAngleLoc()))
3701 << SourceRange(LAngleLoc, RAngleLoc);
3702 else
3703 isExplicitSpecialization = true;
3704 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003705 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003706 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003707 isExplicitSpecialization = true;
3708 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003709
Douglas Gregor67a65642009-02-17 23:15:12 +00003710 // Check that the specialization uses the same tag kind as the
3711 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003712 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3713 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00003714 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003715 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003716 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003717 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003718 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003719 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003720 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003721 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003722 diag::note_previous_use);
3723 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3724 }
3725
Douglas Gregorc40290e2009-03-09 23:48:35 +00003726 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003727 TemplateArgumentListInfo TemplateArgs;
3728 TemplateArgs.setLAngleLoc(LAngleLoc);
3729 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003730 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003731
Douglas Gregor67a65642009-02-17 23:15:12 +00003732 // Check that the template argument list is well-formed for this
3733 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003734 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3735 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003736 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3737 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003738 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003739
Mike Stump11289f42009-09-09 15:08:12 +00003740 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003741 ClassTemplate->getTemplateParameters()->size()) &&
3742 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003743
Douglas Gregor2373c592009-05-31 09:31:02 +00003744 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003745 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00003746 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003747 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003748 if (CheckClassTemplatePartialSpecializationArgs(
3749 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003750 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003751 return true;
3752
Douglas Gregor09a30232009-06-12 22:08:06 +00003753 if (MirrorsPrimaryTemplate) {
3754 // C++ [temp.class.spec]p9b3:
3755 //
Mike Stump11289f42009-09-09 15:08:12 +00003756 // -- The argument list of the specialization shall not be identical
3757 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003758 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003759 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003760 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003761 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003762 ClassTemplate->getIdentifier(),
3763 TemplateNameLoc,
3764 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003765 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003766 AS_none);
3767 }
3768
Douglas Gregor2208a292009-09-26 20:57:03 +00003769 // FIXME: Diagnose friend partial specializations
3770
Douglas Gregor92354b62010-02-09 00:37:32 +00003771 if (!Name.isDependent() &&
3772 !TemplateSpecializationType::anyDependentTemplateArguments(
3773 TemplateArgs.getArgumentArray(),
3774 TemplateArgs.size())) {
3775 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3776 << ClassTemplate->getDeclName();
3777 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00003778 }
3779 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003780
Douglas Gregor67a65642009-02-17 23:15:12 +00003781 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003782 ClassTemplateSpecializationDecl *PrevDecl = 0;
3783
3784 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003785 // FIXME: Template parameter list matters, too
Douglas Gregor2373c592009-05-31 09:31:02 +00003786 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003787 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
3788 Converted.flatSize(),
3789 InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00003790 else
3791 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003792 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
3793 Converted.flatSize(), InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003794
3795 ClassTemplateSpecializationDecl *Specialization = 0;
3796
Douglas Gregorf47b9112009-02-25 22:02:03 +00003797 // Check whether we can declare a class template specialization in
3798 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003799 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003800 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003801 TemplateNameLoc,
3802 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003803 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003804
Douglas Gregor15301382009-07-30 17:40:51 +00003805 // The canonical type
3806 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003807 if (PrevDecl &&
3808 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003809 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003810 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003811 // arguments was referenced but not declared, or we're only
3812 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003813 // declaration node as our own, updating its source location to
3814 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003815 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003816 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003817 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003818 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003819 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003820 // Build the canonical type that describes the converted template
3821 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003822 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3823 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003824 Converted.getFlatArguments(),
3825 Converted.flatSize());
3826
Douglas Gregor2373c592009-05-31 09:31:02 +00003827 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003828 ClassTemplatePartialSpecializationDecl *PrevPartial
3829 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00003830 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003831 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump11289f42009-09-09 15:08:12 +00003832 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00003833 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00003834 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003835 TemplateNameLoc,
3836 TemplateParams,
3837 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003838 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003839 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003840 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00003841 PrevPartial,
3842 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00003843 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00003844 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003845 Partial->setTemplateParameterListsInfo(Context,
3846 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003847 (TemplateParameterList**) TemplateParameterLists.release());
3848 }
Douglas Gregor2373c592009-05-31 09:31:02 +00003849
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003850 if (!PrevPartial)
3851 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00003852 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003853
Douglas Gregor21610382009-10-29 00:04:11 +00003854 // If we are providing an explicit specialization of a member class
3855 // template specialization, make a note of that.
3856 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3857 PrevPartial->setMemberSpecialization();
3858
Douglas Gregor91772d12009-06-13 00:26:55 +00003859 // Check that all of the template parameters of the class template
3860 // partial specialization are deducible from the template
3861 // arguments. If not, this class template partial specialization
3862 // will never be used.
3863 llvm::SmallVector<bool, 8> DeducibleParams;
3864 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003865 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003866 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003867 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003868 unsigned NumNonDeducible = 0;
3869 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3870 if (!DeducibleParams[I])
3871 ++NumNonDeducible;
3872
3873 if (NumNonDeducible) {
3874 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3875 << (NumNonDeducible > 1)
3876 << SourceRange(TemplateNameLoc, RAngleLoc);
3877 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3878 if (!DeducibleParams[I]) {
3879 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3880 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003881 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003882 diag::note_partial_spec_unused_parameter)
3883 << Param->getDeclName();
3884 else
Mike Stump11289f42009-09-09 15:08:12 +00003885 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003886 diag::note_partial_spec_unused_parameter)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003887 << "<anonymous>";
Douglas Gregor91772d12009-06-13 00:26:55 +00003888 }
3889 }
3890 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003891 } else {
3892 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003893 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003894 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00003895 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00003896 ClassTemplate->getDeclContext(),
3897 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003898 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003899 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003900 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00003901 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00003902 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003903 Specialization->setTemplateParameterListsInfo(Context,
3904 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003905 (TemplateParameterList**) TemplateParameterLists.release());
3906 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003907
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003908 if (!PrevDecl)
3909 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00003910
3911 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003912 }
3913
Douglas Gregor06db9f52009-10-12 20:18:28 +00003914 // C++ [temp.expl.spec]p6:
3915 // If a template, a member template or the member of a class template is
3916 // explicitly specialized then that specialization shall be declared
3917 // before the first use of that specialization that would cause an implicit
3918 // instantiation to take place, in every translation unit in which such a
3919 // use occurs; no diagnostic is required.
3920 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003921 bool Okay = false;
3922 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3923 // Is there any previous explicit specialization declaration?
3924 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3925 Okay = true;
3926 break;
3927 }
3928 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003929
Douglas Gregorc854c662010-02-26 06:03:23 +00003930 if (!Okay) {
3931 SourceRange Range(TemplateNameLoc, RAngleLoc);
3932 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3933 << Context.getTypeDeclType(Specialization) << Range;
3934
3935 Diag(PrevDecl->getPointOfInstantiation(),
3936 diag::note_instantiation_required_here)
3937 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003938 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003939 return true;
3940 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003941 }
3942
Douglas Gregor2208a292009-09-26 20:57:03 +00003943 // If this is not a friend, note that this is an explicit specialization.
3944 if (TUK != TUK_Friend)
3945 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003946
3947 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003948 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003949 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003950 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003951 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003952 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003953 Diag(Def->getLocation(), diag::note_previous_definition);
3954 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003955 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003956 }
3957 }
3958
Douglas Gregord56a91e2009-02-26 22:19:44 +00003959 // Build the fully-sugared type for this class template
3960 // specialization as the user wrote in the specialization
3961 // itself. This means that we'll pretty-print the type retrieved
3962 // from the specialization's declaration the way that the user
3963 // actually wrote the specialization, rather than formatting the
3964 // name based on the "canonical" representation used to store the
3965 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003966 TypeSourceInfo *WrittenTy
3967 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3968 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00003969 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003970 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregord890b732010-07-06 18:33:12 +00003971 if (TemplateParams)
3972 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnara8075c852010-06-12 07:44:57 +00003973 }
Douglas Gregorc40290e2009-03-09 23:48:35 +00003974 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003975
Douglas Gregor1e249f82009-02-25 22:18:32 +00003976 // C++ [temp.expl.spec]p9:
3977 // A template explicit specialization is in the scope of the
3978 // namespace in which the template was defined.
3979 //
3980 // We actually implement this paragraph where we set the semantic
3981 // context (in the creation of the ClassTemplateSpecializationDecl),
3982 // but we also maintain the lexical context where the actual
3983 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003984 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003985
Douglas Gregor67a65642009-02-17 23:15:12 +00003986 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003987 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003988 Specialization->startDefinition();
3989
Douglas Gregor2208a292009-09-26 20:57:03 +00003990 if (TUK == TUK_Friend) {
3991 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3992 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00003993 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00003994 /*FIXME:*/KWLoc);
3995 Friend->setAccess(AS_public);
3996 CurContext->addDecl(Friend);
3997 } else {
3998 // Add the specialization into its lexical context, so that it can
3999 // be seen when iterating through the list of declarations in that
4000 // context. However, specializations are not found by name lookup.
4001 CurContext->addDecl(Specialization);
4002 }
John McCall48871652010-08-21 09:40:31 +00004003 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00004004}
Douglas Gregor333489b2009-03-27 23:10:48 +00004005
John McCall48871652010-08-21 09:40:31 +00004006Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004007 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004008 Declarator &D) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004009 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4010}
4011
John McCall48871652010-08-21 09:40:31 +00004012Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004013 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004014 Declarator &D) {
Douglas Gregor17a7c122009-06-24 00:54:41 +00004015 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4016 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4017 "Not a function declarator!");
4018 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00004019
Douglas Gregor17a7c122009-06-24 00:54:41 +00004020 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004021 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004022 }
Mike Stump11289f42009-09-09 15:08:12 +00004023
Douglas Gregor17a7c122009-06-24 00:54:41 +00004024 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004025
John McCall48871652010-08-21 09:40:31 +00004026 Decl *DP = HandleDeclarator(ParentScope, D,
4027 move(TemplateParameterLists),
4028 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004029 if (FunctionTemplateDecl *FunctionTemplate
John McCall48871652010-08-21 09:40:31 +00004030 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump11289f42009-09-09 15:08:12 +00004031 return ActOnStartOfFunctionDef(FnBodyScope,
John McCall48871652010-08-21 09:40:31 +00004032 FunctionTemplate->getTemplatedDecl());
4033 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4034 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4035 return 0;
Douglas Gregor17a7c122009-06-24 00:54:41 +00004036}
4037
John McCall4f7ced62010-02-11 01:33:53 +00004038/// \brief Strips various properties off an implicit instantiation
4039/// that has just been explicitly specialized.
4040static void StripImplicitInstantiation(NamedDecl *D) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004041 D->dropAttrs();
John McCall4f7ced62010-02-11 01:33:53 +00004042
4043 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4044 FD->setInlineSpecified(false);
4045 }
4046}
4047
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004048/// \brief Diagnose cases where we have an explicit template specialization
4049/// before/after an explicit template instantiation, producing diagnostics
4050/// for those cases where they are required and determining whether the
4051/// new specialization/instantiation will have any effect.
4052///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004053/// \param NewLoc the location of the new explicit specialization or
4054/// instantiation.
4055///
4056/// \param NewTSK the kind of the new explicit specialization or instantiation.
4057///
4058/// \param PrevDecl the previous declaration of the entity.
4059///
4060/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4061///
4062/// \param PrevPointOfInstantiation if valid, indicates where the previus
4063/// declaration was instantiated (either implicitly or explicitly).
4064///
Abramo Bagnara8075c852010-06-12 07:44:57 +00004065/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004066/// specialization or instantiation has no effect and should be ignored.
4067///
4068/// \returns true if there was an error that should prevent the introduction of
4069/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004070bool
4071Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4072 TemplateSpecializationKind NewTSK,
4073 NamedDecl *PrevDecl,
4074 TemplateSpecializationKind PrevTSK,
4075 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004076 bool &HasNoEffect) {
4077 HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004078
4079 switch (NewTSK) {
4080 case TSK_Undeclared:
4081 case TSK_ImplicitInstantiation:
4082 assert(false && "Don't check implicit instantiations here");
4083 return false;
4084
4085 case TSK_ExplicitSpecialization:
4086 switch (PrevTSK) {
4087 case TSK_Undeclared:
4088 case TSK_ExplicitSpecialization:
4089 // Okay, we're just specializing something that is either already
4090 // explicitly specialized or has merely been mentioned without any
4091 // instantiation.
4092 return false;
4093
4094 case TSK_ImplicitInstantiation:
4095 if (PrevPointOfInstantiation.isInvalid()) {
4096 // The declaration itself has not actually been instantiated, so it is
4097 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004098 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004099 return false;
4100 }
4101 // Fall through
4102
4103 case TSK_ExplicitInstantiationDeclaration:
4104 case TSK_ExplicitInstantiationDefinition:
4105 assert((PrevTSK == TSK_ImplicitInstantiation ||
4106 PrevPointOfInstantiation.isValid()) &&
4107 "Explicit instantiation without point of instantiation?");
4108
4109 // C++ [temp.expl.spec]p6:
4110 // If a template, a member template or the member of a class template
4111 // is explicitly specialized then that specialization shall be declared
4112 // before the first use of that specialization that would cause an
4113 // implicit instantiation to take place, in every translation unit in
4114 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004115 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4116 // Is there any previous explicit specialization declaration?
4117 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4118 return false;
4119 }
4120
Douglas Gregor1d957a32009-10-27 18:42:08 +00004121 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004122 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004123 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004124 << (PrevTSK != TSK_ImplicitInstantiation);
4125
4126 return true;
4127 }
4128 break;
4129
4130 case TSK_ExplicitInstantiationDeclaration:
4131 switch (PrevTSK) {
4132 case TSK_ExplicitInstantiationDeclaration:
4133 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00004134 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004135 return false;
4136
4137 case TSK_Undeclared:
4138 case TSK_ImplicitInstantiation:
4139 // We're explicitly instantiating something that may have already been
4140 // implicitly instantiated; that's fine.
4141 return false;
4142
4143 case TSK_ExplicitSpecialization:
4144 // C++0x [temp.explicit]p4:
4145 // For a given set of template parameters, if an explicit instantiation
4146 // of a template appears after a declaration of an explicit
4147 // specialization for that template, the explicit instantiation has no
4148 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00004149 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004150 return false;
4151
4152 case TSK_ExplicitInstantiationDefinition:
4153 // C++0x [temp.explicit]p10:
4154 // If an entity is the subject of both an explicit instantiation
4155 // declaration and an explicit instantiation definition in the same
4156 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004157 Diag(NewLoc,
4158 diag::err_explicit_instantiation_declaration_after_definition);
4159 Diag(PrevPointOfInstantiation,
4160 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004161 assert(PrevPointOfInstantiation.isValid() &&
4162 "Explicit instantiation without point of instantiation?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00004163 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004164 return false;
4165 }
4166 break;
4167
4168 case TSK_ExplicitInstantiationDefinition:
4169 switch (PrevTSK) {
4170 case TSK_Undeclared:
4171 case TSK_ImplicitInstantiation:
4172 // We're explicitly instantiating something that may have already been
4173 // implicitly instantiated; that's fine.
4174 return false;
4175
4176 case TSK_ExplicitSpecialization:
4177 // C++ DR 259, C++0x [temp.explicit]p4:
4178 // For a given set of template parameters, if an explicit
4179 // instantiation of a template appears after a declaration of
4180 // an explicit specialization for that template, the explicit
4181 // instantiation has no effect.
4182 //
4183 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004184 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004185 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004186 if (!getLangOptions().CPlusPlus0x) {
4187 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004188 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004189 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004190 diag::note_previous_template_specialization);
4191 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004192 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004193 return false;
4194
4195 case TSK_ExplicitInstantiationDeclaration:
4196 // We're explicity instantiating a definition for something for which we
4197 // were previously asked to suppress instantiations. That's fine.
4198 return false;
4199
4200 case TSK_ExplicitInstantiationDefinition:
4201 // C++0x [temp.spec]p5:
4202 // For a given template and a given set of template-arguments,
4203 // - an explicit instantiation definition shall appear at most once
4204 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004205 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004206 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004207 Diag(PrevPointOfInstantiation,
4208 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004209 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004210 return false;
4211 }
4212 break;
4213 }
4214
4215 assert(false && "Missing specialization/instantiation case?");
4216
4217 return false;
4218}
4219
John McCallb9c78482010-04-08 09:05:18 +00004220/// \brief Perform semantic analysis for the given dependent function
4221/// template specialization. The only possible way to get a dependent
4222/// function template specialization is with a friend declaration,
4223/// like so:
4224///
4225/// template <class T> void foo(T);
4226/// template <class T> class A {
4227/// friend void foo<>(T);
4228/// };
4229///
4230/// There really isn't any useful analysis we can do here, so we
4231/// just store the information.
4232bool
4233Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4234 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4235 LookupResult &Previous) {
4236 // Remove anything from Previous that isn't a function template in
4237 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00004238 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00004239 LookupResult::Filter F = Previous.makeFilter();
4240 while (F.hasNext()) {
4241 NamedDecl *D = F.next()->getUnderlyingDecl();
4242 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00004243 !FDLookupContext->InEnclosingNamespaceSetOf(
4244 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00004245 F.erase();
4246 }
4247 F.done();
4248
4249 // Should this be diagnosed here?
4250 if (Previous.empty()) return true;
4251
4252 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4253 ExplicitTemplateArgs);
4254 return false;
4255}
4256
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004257/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004258/// specialization.
4259///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004260/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004261/// explicit function template specialization. On successful completion,
4262/// the function declaration \p FD will become a function template
4263/// specialization.
4264///
4265/// \param FD the function declaration, which will be updated to become a
4266/// function template specialization.
4267///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004268/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4269/// if any. Note that this may be valid info even when 0 arguments are
4270/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4271/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004272///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004273/// \param PrevDecl the set of declarations that may be specialized by
4274/// this function specialization.
4275bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004276Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004277 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004278 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004279 // The set of function template specializations that could match this
4280 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004281 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004282
Sebastian Redl50c68252010-08-31 00:36:30 +00004283 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00004284 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4285 I != E; ++I) {
4286 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4287 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004288 // Only consider templates found within the same semantic lookup scope as
4289 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00004290 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4291 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004292 continue;
4293
4294 // C++ [temp.expl.spec]p11:
4295 // A trailing template-argument can be left unspecified in the
4296 // template-id naming an explicit function template specialization
4297 // provided it can be deduced from the function argument type.
4298 // Perform template argument deduction to determine whether we may be
4299 // specializing this template.
4300 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004301 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004302 FunctionDecl *Specialization = 0;
4303 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004304 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004305 FD->getType(),
4306 Specialization,
4307 Info)) {
4308 // FIXME: Template argument deduction failed; record why it failed, so
4309 // that we can provide nifty diagnostics.
4310 (void)TDK;
4311 continue;
4312 }
4313
4314 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004315 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004316 }
4317 }
4318
Douglas Gregor5de279c2009-09-26 03:41:46 +00004319 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004320 UnresolvedSetIterator Result
4321 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4322 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004323 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004324 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004325 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004326 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004327 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004328 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004329 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004330
4331 // Ignore access information; it doesn't figure into redeclaration checking.
4332 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004333 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004334
4335 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004336 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004337
4338 // If this is a friend declaration, then we're not really declaring
4339 // an explicit specialization.
4340 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004341
Douglas Gregor54888652009-10-07 00:13:32 +00004342 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004343 if (!isFriend &&
4344 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004345 Specialization->getPrimaryTemplate(),
4346 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004347 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004348 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004349
4350 // C++ [temp.expl.spec]p6:
4351 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004352 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004353 // before the first use of that specialization that would cause an implicit
4354 // instantiation to take place, in every translation unit in which such a
4355 // use occurs; no diagnostic is required.
4356 FunctionTemplateSpecializationInfo *SpecInfo
4357 = Specialization->getTemplateSpecializationInfo();
4358 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004359
Abramo Bagnara8075c852010-06-12 07:44:57 +00004360 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00004361 if (!isFriend &&
4362 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004363 TSK_ExplicitSpecialization,
4364 Specialization,
4365 SpecInfo->getTemplateSpecializationKind(),
4366 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004367 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004368 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004369
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004370 // Mark the prior declaration as an explicit specialization, so that later
4371 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004372 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00004373 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004374 MarkUnusedFileScopedDecl(Specialization);
4375 }
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004376
4377 // Turn the given function declaration into a function template
4378 // specialization, with the template arguments from the previous
4379 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004380 // Take copies of (semantic and syntactic) template argument lists.
4381 const TemplateArgumentList* TemplArgs = new (Context)
4382 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4383 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4384 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004385 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004386 TemplArgs, /*InsertPos=*/0,
4387 SpecInfo->getTemplateSpecializationKind(),
4388 TemplArgsAsWritten);
4389
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004390 // The "previous declaration" for this function template specialization is
4391 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004392 Previous.clear();
4393 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004394 return false;
4395}
4396
Douglas Gregor86d142a2009-10-08 07:24:58 +00004397/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004398/// specialization.
4399///
4400/// This routine performs all of the semantic analysis required for an
4401/// explicit member function specialization. On successful completion,
4402/// the function declaration \p FD will become a member function
4403/// specialization.
4404///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004405/// \param Member the member declaration, which will be updated to become a
4406/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004407///
John McCall1f82f242009-11-18 22:49:29 +00004408/// \param Previous the set of declarations, one of which may be specialized
4409/// by this function specialization; the set will be modified to contain the
4410/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004411bool
John McCall1f82f242009-11-18 22:49:29 +00004412Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004413 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004414
Douglas Gregor86d142a2009-10-08 07:24:58 +00004415 // Try to find the member we are instantiating.
4416 NamedDecl *Instantiation = 0;
4417 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004418 MemberSpecializationInfo *MSInfo = 0;
4419
John McCall1f82f242009-11-18 22:49:29 +00004420 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004421 // Nowhere to look anyway.
4422 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004423 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4424 I != E; ++I) {
4425 NamedDecl *D = (*I)->getUnderlyingDecl();
4426 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004427 if (Context.hasSameType(Function->getType(), Method->getType())) {
4428 Instantiation = Method;
4429 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004430 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004431 break;
4432 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004433 }
4434 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004435 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004436 VarDecl *PrevVar;
4437 if (Previous.isSingleResult() &&
4438 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004439 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004440 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004441 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004442 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004443 }
4444 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004445 CXXRecordDecl *PrevRecord;
4446 if (Previous.isSingleResult() &&
4447 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4448 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004449 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004450 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004451 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004452 }
4453
4454 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004455 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004456 // specializations are always out-of-line, the caller will complain about
4457 // this mismatch later.
4458 return false;
4459 }
John McCalle820e5e2010-04-13 20:37:33 +00004460
4461 // If this is a friend, just bail out here before we start turning
4462 // things into explicit specializations.
4463 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4464 // Preserve instantiation information.
4465 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4466 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4467 cast<CXXMethodDecl>(InstantiatedFrom),
4468 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4469 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4470 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4471 cast<CXXRecordDecl>(InstantiatedFrom),
4472 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4473 }
4474
4475 Previous.clear();
4476 Previous.addDecl(Instantiation);
4477 return false;
4478 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004479
Douglas Gregor86d142a2009-10-08 07:24:58 +00004480 // Make sure that this is a specialization of a member.
4481 if (!InstantiatedFrom) {
4482 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4483 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004484 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4485 return true;
4486 }
4487
Douglas Gregor06db9f52009-10-12 20:18:28 +00004488 // C++ [temp.expl.spec]p6:
4489 // If a template, a member template or the member of a class template is
4490 // explicitly specialized then that spe- cialization shall be declared
4491 // before the first use of that specialization that would cause an implicit
4492 // instantiation to take place, in every translation unit in which such a
4493 // use occurs; no diagnostic is required.
4494 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004495
Abramo Bagnara8075c852010-06-12 07:44:57 +00004496 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00004497 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4498 TSK_ExplicitSpecialization,
4499 Instantiation,
4500 MSInfo->getTemplateSpecializationKind(),
4501 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004502 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004503 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004504
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004505 // Check the scope of this explicit specialization.
4506 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004507 InstantiatedFrom,
4508 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004509 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004510 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004511
Douglas Gregor86d142a2009-10-08 07:24:58 +00004512 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004513 // the original declaration to note that it is an explicit specialization
4514 // (if it was previously an implicit instantiation). This latter step
4515 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004516 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004517 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4518 if (InstantiationFunction->getTemplateSpecializationKind() ==
4519 TSK_ImplicitInstantiation) {
4520 InstantiationFunction->setTemplateSpecializationKind(
4521 TSK_ExplicitSpecialization);
4522 InstantiationFunction->setLocation(Member->getLocation());
4523 }
4524
Douglas Gregor86d142a2009-10-08 07:24:58 +00004525 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4526 cast<CXXMethodDecl>(InstantiatedFrom),
4527 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004528 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004529 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004530 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4531 if (InstantiationVar->getTemplateSpecializationKind() ==
4532 TSK_ImplicitInstantiation) {
4533 InstantiationVar->setTemplateSpecializationKind(
4534 TSK_ExplicitSpecialization);
4535 InstantiationVar->setLocation(Member->getLocation());
4536 }
4537
Douglas Gregor86d142a2009-10-08 07:24:58 +00004538 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4539 cast<VarDecl>(InstantiatedFrom),
4540 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004541 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004542 } else {
4543 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004544 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4545 if (InstantiationClass->getTemplateSpecializationKind() ==
4546 TSK_ImplicitInstantiation) {
4547 InstantiationClass->setTemplateSpecializationKind(
4548 TSK_ExplicitSpecialization);
4549 InstantiationClass->setLocation(Member->getLocation());
4550 }
4551
Douglas Gregor86d142a2009-10-08 07:24:58 +00004552 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004553 cast<CXXRecordDecl>(InstantiatedFrom),
4554 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004555 }
4556
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004557 // Save the caller the trouble of having to figure out which declaration
4558 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004559 Previous.clear();
4560 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004561 return false;
4562}
4563
Douglas Gregore47f5a72009-10-14 23:41:34 +00004564/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004565///
4566/// \returns true if a serious error occurs, false otherwise.
4567static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00004568 SourceLocation InstLoc,
4569 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00004570 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
4571 DeclContext *CurContext = S.CurContext->getRedeclContext();
Douglas Gregore47f5a72009-10-14 23:41:34 +00004572
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004573 if (CurContext->isRecord()) {
4574 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4575 << D;
4576 return true;
4577 }
4578
Douglas Gregore47f5a72009-10-14 23:41:34 +00004579 // C++0x [temp.explicit]p2:
4580 // An explicit instantiation shall appear in an enclosing namespace of its
4581 // template.
4582 //
4583 // This is DR275, which we do not retroactively apply to C++98/03.
4584 if (S.getLangOptions().CPlusPlus0x &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004585 !CurContext->Encloses(OrigContext)) {
4586 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004587 S.Diag(InstLoc,
4588 S.getLangOptions().CPlusPlus0x?
4589 diag::err_explicit_instantiation_out_of_scope
4590 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004591 << D << NS;
4592 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004593 S.Diag(InstLoc,
4594 S.getLangOptions().CPlusPlus0x?
4595 diag::err_explicit_instantiation_must_be_global
4596 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004597 << D;
4598 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004599 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004600 }
Sebastian Redl50c68252010-08-31 00:36:30 +00004601
Douglas Gregore47f5a72009-10-14 23:41:34 +00004602 // C++0x [temp.explicit]p2:
4603 // If the name declared in the explicit instantiation is an unqualified
4604 // name, the explicit instantiation shall appear in the namespace where
4605 // its template is declared or, if that namespace is inline (7.3.1), any
4606 // namespace from its enclosing namespace set.
4607 if (WasQualifiedName)
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004608 return false;
Sebastian Redl50c68252010-08-31 00:36:30 +00004609
4610 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004611 return false;
Sebastian Redl50c68252010-08-31 00:36:30 +00004612
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004613 S.Diag(InstLoc,
4614 S.getLangOptions().CPlusPlus0x?
4615 diag::err_explicit_instantiation_unqualified_wrong_namespace
4616 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Sebastian Redl50c68252010-08-31 00:36:30 +00004617 << D << OrigContext;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004618 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004619 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004620}
4621
4622/// \brief Determine whether the given scope specifier has a template-id in it.
4623static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4624 if (!SS.isSet())
4625 return false;
4626
4627 // C++0x [temp.explicit]p2:
4628 // If the explicit instantiation is for a member function, a member class
4629 // or a static data member of a class template specialization, the name of
4630 // the class template specialization in the qualified-id for the member
4631 // name shall be a simple-template-id.
4632 //
4633 // C++98 has the same restriction, just worded differently.
4634 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4635 NNS; NNS = NNS->getPrefix())
4636 if (Type *T = NNS->getAsType())
4637 if (isa<TemplateSpecializationType>(T))
4638 return true;
4639
4640 return false;
4641}
4642
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004643// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00004644DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004645Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004646 SourceLocation ExternLoc,
4647 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004648 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004649 SourceLocation KWLoc,
4650 const CXXScopeSpec &SS,
4651 TemplateTy TemplateD,
4652 SourceLocation TemplateNameLoc,
4653 SourceLocation LAngleLoc,
4654 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004655 SourceLocation RAngleLoc,
4656 AttributeList *Attr) {
4657 // Find the class template we're specializing
4658 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004659 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004660 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4661
4662 // Check that the specialization uses the same tag kind as the
4663 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004664 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4665 assert(Kind != TTK_Enum &&
4666 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004667 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004668 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004669 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004670 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004671 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004672 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004673 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004674 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004675 diag::note_previous_use);
4676 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4677 }
4678
Douglas Gregore47f5a72009-10-14 23:41:34 +00004679 // C++0x [temp.explicit]p2:
4680 // There are two forms of explicit instantiation: an explicit instantiation
4681 // definition and an explicit instantiation declaration. An explicit
4682 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004683 TemplateSpecializationKind TSK
4684 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4685 : TSK_ExplicitInstantiationDeclaration;
4686
Douglas Gregora1f49972009-05-13 00:25:59 +00004687 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004688 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004689 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004690
4691 // Check that the template argument list is well-formed for this
4692 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004693 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4694 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004695 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4696 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004697 return true;
4698
Mike Stump11289f42009-09-09 15:08:12 +00004699 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004700 ClassTemplate->getTemplateParameters()->size()) &&
4701 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004702
Douglas Gregora1f49972009-05-13 00:25:59 +00004703 // Find the class template specialization declaration that
4704 // corresponds to these arguments.
Douglas Gregora1f49972009-05-13 00:25:59 +00004705 void *InsertPos = 0;
4706 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004707 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4708 Converted.flatSize(), InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004709
Abramo Bagnara8075c852010-06-12 07:44:57 +00004710 TemplateSpecializationKind PrevDecl_TSK
4711 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4712
Douglas Gregor54888652009-10-07 00:13:32 +00004713 // C++0x [temp.explicit]p2:
4714 // [...] An explicit instantiation shall appear in an enclosing
4715 // namespace of its template. [...]
4716 //
4717 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004718 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4719 SS.isSet()))
4720 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004721
Douglas Gregora1f49972009-05-13 00:25:59 +00004722 ClassTemplateSpecializationDecl *Specialization = 0;
4723
Douglas Gregor0681a352009-11-25 06:01:46 +00004724 bool ReusedDecl = false;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004725 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004726 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00004727 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004728 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004729 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004730 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00004731 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00004732
Abramo Bagnara8075c852010-06-12 07:44:57 +00004733 // Even though HasNoEffect == true means that this explicit instantiation
4734 // has no effect on semantics, we go on to put its syntax in the AST.
4735
4736 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4737 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004738 // Since the only prior class template specialization with these
4739 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00004740 // declaration node as our own, updating the source location
4741 // for the template name to reflect our new declaration.
4742 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004743 Specialization = PrevDecl;
4744 Specialization->setLocation(TemplateNameLoc);
4745 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004746 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004747 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004748 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004749
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004750 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004751 // Create a new class template specialization declaration node for
4752 // this explicit specialization.
4753 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004754 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00004755 ClassTemplate->getDeclContext(),
4756 TemplateNameLoc,
4757 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004758 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004759 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004760
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004761 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00004762 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004763 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004764 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004765 }
4766
4767 // Build the fully-sugared type for this explicit instantiation as
4768 // the user wrote in the explicit instantiation itself. This means
4769 // that we'll pretty-print the type retrieved from the
4770 // specialization's declaration the way that the user actually wrote
4771 // the explicit instantiation, rather than formatting the name based
4772 // on the "canonical" representation used to store the template
4773 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004774 TypeSourceInfo *WrittenTy
4775 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4776 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004777 Context.getTypeDeclType(Specialization));
4778 Specialization->setTypeAsWritten(WrittenTy);
4779 TemplateArgsIn.release();
4780
Abramo Bagnara8075c852010-06-12 07:44:57 +00004781 // Set source locations for keywords.
4782 Specialization->setExternLoc(ExternLoc);
4783 Specialization->setTemplateKeywordLoc(TemplateLoc);
4784
4785 // Add the explicit instantiation into its lexical context. However,
4786 // since explicit instantiations are never found by name lookup, we
4787 // just put it into the declaration context directly.
4788 Specialization->setLexicalDeclContext(CurContext);
4789 CurContext->addDecl(Specialization);
4790
4791 // Syntax is now OK, so return if it has no other effect on semantics.
4792 if (HasNoEffect) {
4793 // Set the template specialization kind.
4794 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00004795 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00004796 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004797
4798 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004799 // A definition of a class template or class member template
4800 // shall be in scope at the point of the explicit instantiation of
4801 // the class template or class member template.
4802 //
4803 // This check comes when we actually try to perform the
4804 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004805 ClassTemplateSpecializationDecl *Def
4806 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004807 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004808 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004809 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004810 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00004811 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004812 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
4813 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004814
Douglas Gregor1d957a32009-10-27 18:42:08 +00004815 // Instantiate the members of this class template specialization.
4816 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004817 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004818 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004819 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4820
4821 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4822 // TSK_ExplicitInstantiationDefinition
4823 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4824 TSK == TSK_ExplicitInstantiationDefinition)
4825 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004826
Douglas Gregor12e49d32009-10-15 22:53:21 +00004827 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004828 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004829
Abramo Bagnara8075c852010-06-12 07:44:57 +00004830 // Set the template specialization kind.
4831 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00004832 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00004833}
4834
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004835// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00004836DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004837Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004838 SourceLocation ExternLoc,
4839 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004840 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004841 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004842 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004843 IdentifierInfo *Name,
4844 SourceLocation NameLoc,
4845 AttributeList *Attr) {
4846
Douglas Gregord6ab8742009-05-28 23:31:59 +00004847 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004848 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00004849 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00004850 KWLoc, SS, Name, NameLoc, Attr, AS_none,
4851 MultiTemplateParamsArg(*this, 0, 0),
4852 Owned, IsDependent);
John McCall7f41d982009-09-11 04:59:25 +00004853 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4854
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004855 if (!TagD)
4856 return true;
4857
John McCall48871652010-08-21 09:40:31 +00004858 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004859 if (Tag->isEnum()) {
4860 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4861 << Context.getTypeDeclType(Tag);
4862 return true;
4863 }
4864
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004865 if (Tag->isInvalidDecl())
4866 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004867
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004868 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4869 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4870 if (!Pattern) {
4871 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4872 << Context.getTypeDeclType(Record);
4873 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4874 return true;
4875 }
4876
Douglas Gregore47f5a72009-10-14 23:41:34 +00004877 // C++0x [temp.explicit]p2:
4878 // If the explicit instantiation is for a class or member class, the
4879 // elaborated-type-specifier in the declaration shall include a
4880 // simple-template-id.
4881 //
4882 // C++98 has the same restriction, just worded differently.
4883 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00004884 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004885 << Record << SS.getRange();
4886
4887 // C++0x [temp.explicit]p2:
4888 // There are two forms of explicit instantiation: an explicit instantiation
4889 // definition and an explicit instantiation declaration. An explicit
4890 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004891 TemplateSpecializationKind TSK
4892 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4893 : TSK_ExplicitInstantiationDeclaration;
4894
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004895 // C++0x [temp.explicit]p2:
4896 // [...] An explicit instantiation shall appear in an enclosing
4897 // namespace of its template. [...]
4898 //
4899 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004900 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004901
4902 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004903 CXXRecordDecl *PrevDecl
4904 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004905 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004906 PrevDecl = Record;
4907 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004908 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00004909 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004910 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004911 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004912 PrevDecl,
4913 MSInfo->getTemplateSpecializationKind(),
4914 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004915 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004916 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004917 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004918 return TagD;
4919 }
4920
Douglas Gregor12e49d32009-10-15 22:53:21 +00004921 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004922 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004923 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004924 // C++ [temp.explicit]p3:
4925 // A definition of a member class of a class template shall be in scope
4926 // at the point of an explicit instantiation of the member class.
4927 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004928 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004929 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004930 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4931 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004932 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4933 << Pattern;
4934 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004935 } else {
4936 if (InstantiateClass(NameLoc, Record, Def,
4937 getTemplateInstantiationArgs(Record),
4938 TSK))
4939 return true;
4940
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004941 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004942 if (!RecordDef)
4943 return true;
4944 }
4945 }
4946
4947 // Instantiate all of the members of the class.
4948 InstantiateClassMembers(NameLoc, RecordDef,
4949 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004950
Douglas Gregor88d292c2010-05-13 16:44:06 +00004951 if (TSK == TSK_ExplicitInstantiationDefinition)
4952 MarkVTableUsed(NameLoc, RecordDef, true);
4953
Mike Stump87c57ac2009-05-16 07:39:55 +00004954 // FIXME: We don't have any representation for explicit instantiations of
4955 // member classes. Such a representation is not needed for compilation, but it
4956 // should be available for clients that want to see all of the declarations in
4957 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004958 return TagD;
4959}
4960
John McCallfaf5fb42010-08-26 23:41:50 +00004961DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4962 SourceLocation ExternLoc,
4963 SourceLocation TemplateLoc,
4964 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004965 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004966 // TODO: check if/when DNInfo should replace Name.
4967 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4968 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00004969 if (!Name) {
4970 if (!D.isInvalidType())
4971 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4972 diag::err_explicit_instantiation_requires_name)
4973 << D.getDeclSpec().getSourceRange()
4974 << D.getSourceRange();
4975
4976 return true;
4977 }
4978
4979 // The scope passed in may not be a decl scope. Zip up the scope tree until
4980 // we find one that is.
4981 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4982 (S->getFlags() & Scope::TemplateParamScope) != 0)
4983 S = S->getParent();
4984
4985 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00004986 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
4987 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00004988 if (R.isNull())
4989 return true;
4990
4991 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4992 // Cannot explicitly instantiate a typedef.
4993 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4994 << Name;
4995 return true;
4996 }
4997
Douglas Gregor3c74d412009-10-14 20:14:33 +00004998 // C++0x [temp.explicit]p1:
4999 // [...] An explicit instantiation of a function template shall not use the
5000 // inline or constexpr specifiers.
5001 // Presumably, this also applies to member functions of class templates as
5002 // well.
5003 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5004 Diag(D.getDeclSpec().getInlineSpecLoc(),
5005 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00005006 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00005007
5008 // FIXME: check for constexpr specifier.
5009
Douglas Gregore47f5a72009-10-14 23:41:34 +00005010 // C++0x [temp.explicit]p2:
5011 // There are two forms of explicit instantiation: an explicit instantiation
5012 // definition and an explicit instantiation declaration. An explicit
5013 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00005014 TemplateSpecializationKind TSK
5015 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5016 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005017
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005018 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005019 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00005020
5021 if (!R->isFunctionType()) {
5022 // C++ [temp.explicit]p1:
5023 // A [...] static data member of a class template can be explicitly
5024 // instantiated from the member definition associated with its class
5025 // template.
John McCall27b18f82009-11-17 02:14:36 +00005026 if (Previous.isAmbiguous())
5027 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00005028
John McCall67c00872009-12-02 08:25:40 +00005029 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005030 if (!Prev || !Prev->isStaticDataMember()) {
5031 // We expect to see a data data member here.
5032 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5033 << Name;
5034 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5035 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005036 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005037 return true;
5038 }
5039
5040 if (!Prev->getInstantiatedFromStaticDataMember()) {
5041 // FIXME: Check for explicit specialization?
5042 Diag(D.getIdentifierLoc(),
5043 diag::err_explicit_instantiation_data_member_not_instantiated)
5044 << Prev;
5045 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5046 // FIXME: Can we provide a note showing where this was declared?
5047 return true;
5048 }
5049
Douglas Gregore47f5a72009-10-14 23:41:34 +00005050 // C++0x [temp.explicit]p2:
5051 // If the explicit instantiation is for a member function, a member class
5052 // or a static data member of a class template specialization, the name of
5053 // the class template specialization in the qualified-id for the member
5054 // name shall be a simple-template-id.
5055 //
5056 // C++98 has the same restriction, just worded differently.
5057 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5058 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005059 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005060 << Prev << D.getCXXScopeSpec().getRange();
5061
5062 // Check the scope of this explicit instantiation.
5063 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5064
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005065 // Verify that it is okay to explicitly instantiate here.
5066 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5067 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00005068 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005069 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005070 MSInfo->getTemplateSpecializationKind(),
5071 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005072 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005073 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005074 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005075 return (Decl*) 0;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005076
Douglas Gregor450f00842009-09-25 18:43:00 +00005077 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005078 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005079 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005080 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregor450f00842009-09-25 18:43:00 +00005081
5082 // FIXME: Create an ExplicitInstantiation node?
John McCall48871652010-08-21 09:40:31 +00005083 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005084 }
5085
Douglas Gregor0e876e02009-09-25 23:53:26 +00005086 // If the declarator is a template-id, translate the parser's template
5087 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005088 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005089 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005090 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5091 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005092 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5093 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005094 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5095 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005096 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005097 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005098 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005099 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005100 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005101
Douglas Gregor450f00842009-09-25 18:43:00 +00005102 // C++ [temp.explicit]p1:
5103 // A [...] function [...] can be explicitly instantiated from its template.
5104 // A member function [...] of a class template can be explicitly
5105 // instantiated from the member definition associated with its class
5106 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005107 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005108 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5109 P != PEnd; ++P) {
5110 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005111 if (!HasExplicitTemplateArgs) {
5112 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5113 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5114 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005115
John McCall58cc69d2010-01-27 01:50:18 +00005116 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005117 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5118 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005119 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005120 }
5121 }
5122
5123 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5124 if (!FunTmpl)
5125 continue;
5126
John McCallbc077cf2010-02-08 23:07:23 +00005127 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005128 FunctionDecl *Specialization = 0;
5129 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005130 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005131 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005132 R, Specialization, Info)) {
5133 // FIXME: Keep track of almost-matches?
5134 (void)TDK;
5135 continue;
5136 }
5137
John McCall58cc69d2010-01-27 01:50:18 +00005138 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005139 }
5140
5141 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005142 UnresolvedSetIterator Result
5143 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005144 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005145 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5146 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5147 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005148
John McCall58cc69d2010-01-27 01:50:18 +00005149 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005150 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005151
5152 // Ignore access control bits, we don't need them for redeclaration checking.
5153 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005154
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005155 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005156 Diag(D.getIdentifierLoc(),
5157 diag::err_explicit_instantiation_member_function_not_instantiated)
5158 << Specialization
5159 << (Specialization->getTemplateSpecializationKind() ==
5160 TSK_ExplicitSpecialization);
5161 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5162 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005163 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005164
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005165 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005166 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5167 PrevDecl = Specialization;
5168
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005169 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005170 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005171 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005172 PrevDecl,
5173 PrevDecl->getTemplateSpecializationKind(),
5174 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005175 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005176 return true;
5177
5178 // FIXME: We may still want to build some representation of this
5179 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00005180 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005181 return (Decl*) 0;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005182 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005183
5184 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005185
5186 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005187 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005188
Douglas Gregore47f5a72009-10-14 23:41:34 +00005189 // C++0x [temp.explicit]p2:
5190 // If the explicit instantiation is for a member function, a member class
5191 // or a static data member of a class template specialization, the name of
5192 // the class template specialization in the qualified-id for the member
5193 // name shall be a simple-template-id.
5194 //
5195 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005196 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005197 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005198 D.getCXXScopeSpec().isSet() &&
5199 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5200 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005201 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005202 << Specialization << D.getCXXScopeSpec().getRange();
5203
5204 CheckExplicitInstantiationScope(*this,
5205 FunTmpl? (NamedDecl *)FunTmpl
5206 : Specialization->getInstantiatedFromMemberFunction(),
5207 D.getIdentifierLoc(),
5208 D.getCXXScopeSpec().isSet());
5209
Douglas Gregor450f00842009-09-25 18:43:00 +00005210 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCall48871652010-08-21 09:40:31 +00005211 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005212}
5213
John McCallfaf5fb42010-08-26 23:41:50 +00005214TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005215Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5216 const CXXScopeSpec &SS, IdentifierInfo *Name,
5217 SourceLocation TagLoc, SourceLocation NameLoc) {
5218 // This has to hold, because SS is expected to be defined.
5219 assert(Name && "Expected a name in a dependent tag");
5220
5221 NestedNameSpecifier *NNS
5222 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5223 if (!NNS)
5224 return true;
5225
Abramo Bagnara6150c882010-05-11 21:36:43 +00005226 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005227
Douglas Gregorba41d012010-04-24 16:38:41 +00005228 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5229 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005230 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005231 return true;
5232 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005233
5234 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallba7bf592010-08-24 05:47:05 +00005235 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCall7f41d982009-09-11 04:59:25 +00005236}
5237
John McCallfaf5fb42010-08-26 23:41:50 +00005238TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005239Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5240 const CXXScopeSpec &SS, const IdentifierInfo &II,
5241 SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005242 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005243 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5244 if (!NNS)
5245 return true;
5246
Douglas Gregorf7d77712010-06-16 22:31:08 +00005247 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5248 !getLangOptions().CPlusPlus0x)
5249 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5250 << FixItHint::CreateRemoval(TypenameLoc);
5251
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005252 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005253 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005254 if (T.isNull())
5255 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005256
5257 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5258 if (isa<DependentNameType>(T)) {
5259 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005260 TL.setKeywordLoc(TypenameLoc);
5261 TL.setQualifierRange(SS.getRange());
5262 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005263 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005264 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005265 TL.setKeywordLoc(TypenameLoc);
5266 TL.setQualifierRange(SS.getRange());
5267 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005268 }
5269
John McCallba7bf592010-08-24 05:47:05 +00005270 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00005271}
5272
John McCallfaf5fb42010-08-26 23:41:50 +00005273TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005274Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5275 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallba7bf592010-08-24 05:47:05 +00005276 ParsedType Ty) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00005277 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5278 !getLangOptions().CPlusPlus0x)
5279 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5280 << FixItHint::CreateRemoval(TypenameLoc);
5281
John McCallf7bcc812010-05-28 23:32:21 +00005282 TypeSourceInfo *InnerTSI = 0;
5283 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCallf7bcc812010-05-28 23:32:21 +00005284
5285 assert(isa<TemplateSpecializationType>(T) &&
5286 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005287
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005288 if (computeDeclContext(SS, false)) {
5289 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005290 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005291 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005292
5293 // Push the inner type, preserving its source locations if possible.
5294 TypeLocBuilder Builder;
5295 if (InnerTSI)
5296 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5297 else
5298 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5299
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005300 /* Note: NNS already embedded in template specialization type T. */
5301 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCallf7bcc812010-05-28 23:32:21 +00005302 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5303 TL.setKeywordLoc(TypenameLoc);
5304 TL.setQualifierRange(SS.getRange());
5305
5306 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallba7bf592010-08-24 05:47:05 +00005307 return CreateParsedType(T, TSI);
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005308 }
Mike Stump11289f42009-09-09 15:08:12 +00005309
John McCallc392f372010-06-11 00:33:02 +00005310 // TODO: it's really silly that we make a template specialization
5311 // type earlier only to drop it again here.
5312 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5313 DependentTemplateName *DTN =
5314 TST->getTemplateName().getAsDependentTemplateName();
5315 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005316 assert(DTN->getQualifier()
5317 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5318 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5319 DTN->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00005320 DTN->getIdentifier(),
5321 TST->getNumArgs(),
5322 TST->getArgs());
John McCall99b2fe52010-04-29 23:50:39 +00005323 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCallc392f372010-06-11 00:33:02 +00005324 DependentTemplateSpecializationTypeLoc TL =
5325 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5326 if (InnerTSI) {
5327 TemplateSpecializationTypeLoc TSTL =
5328 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5329 TL.setLAngleLoc(TSTL.getLAngleLoc());
5330 TL.setRAngleLoc(TSTL.getRAngleLoc());
5331 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5332 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5333 } else {
5334 TL.initializeLocal(SourceLocation());
5335 }
John McCallf7bcc812010-05-28 23:32:21 +00005336 TL.setKeywordLoc(TypenameLoc);
5337 TL.setQualifierRange(SS.getRange());
John McCallba7bf592010-08-24 05:47:05 +00005338 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00005339}
5340
Douglas Gregor333489b2009-03-27 23:10:48 +00005341/// \brief Build the type that describes a C++ typename specifier,
5342/// e.g., "typename T::type".
5343QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005344Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5345 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005346 SourceLocation KeywordLoc, SourceRange NNSRange,
5347 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005348 CXXScopeSpec SS;
5349 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005350 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005351
John McCall0b66eb32010-05-01 00:40:08 +00005352 DeclContext *Ctx = computeDeclContext(SS);
5353 if (!Ctx) {
5354 // If the nested-name-specifier is dependent and couldn't be
5355 // resolved to a type, build a typename type.
5356 assert(NNS->isDependent());
5357 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005358 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005359
John McCall0b66eb32010-05-01 00:40:08 +00005360 // If the nested-name-specifier refers to the current instantiation,
5361 // the "typename" keyword itself is superfluous. In C++03, the
5362 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5363 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00005364 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005365
John McCall0b66eb32010-05-01 00:40:08 +00005366 if (RequireCompleteDeclContext(SS, Ctx))
5367 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005368
5369 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005370 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005371 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005372 unsigned DiagID = 0;
5373 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005374 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005375 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005376 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005377 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005378
5379 case LookupResult::NotFoundInCurrentInstantiation:
5380 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005381 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005382
5383 case LookupResult::Found:
Douglas Gregorf7d77712010-06-16 22:31:08 +00005384 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005385 // We found a type. Build an ElaboratedType, since the
5386 // typename-specifier was just sugar.
5387 return Context.getElaboratedType(ETK_Typename, NNS,
5388 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005389 }
5390
5391 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005392 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005393 break;
5394
John McCalle61f2ba2009-11-18 02:36:19 +00005395 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005396 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005397 return QualType();
5398
Douglas Gregor333489b2009-03-27 23:10:48 +00005399 case LookupResult::FoundOverloaded:
5400 DiagID = diag::err_typename_nested_not_type;
5401 Referenced = *Result.begin();
5402 break;
5403
John McCall6538c932009-10-10 05:48:19 +00005404 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005405 return QualType();
5406 }
5407
5408 // If we get here, it's because name lookup did not find a
5409 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005410 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5411 IILoc);
5412 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005413 if (Referenced)
5414 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5415 << Name;
5416 return QualType();
5417}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005418
5419namespace {
5420 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005421 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005422 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005423 SourceLocation Loc;
5424 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005425
Douglas Gregor15acfb92009-08-06 16:20:37 +00005426 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005427 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5428
Mike Stump11289f42009-09-09 15:08:12 +00005429 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005430 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005431 DeclarationName Entity)
5432 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005433 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005434
5435 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005436 /// transformed.
5437 ///
5438 /// For the purposes of type reconstruction, a type has already been
5439 /// transformed if it is NULL or if it is not dependent.
5440 bool AlreadyTransformed(QualType T) {
5441 return T.isNull() || !T->isDependentType();
5442 }
Mike Stump11289f42009-09-09 15:08:12 +00005443
5444 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005445 /// rebuilt.
5446 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005447
Douglas Gregor15acfb92009-08-06 16:20:37 +00005448 /// \brief Returns the name of the entity whose type is being rebuilt.
5449 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005450
Douglas Gregoref6ab412009-10-27 06:26:26 +00005451 /// \brief Sets the "base" location and entity when that
5452 /// information is known based on another transformation.
5453 void setBase(SourceLocation Loc, DeclarationName Entity) {
5454 this->Loc = Loc;
5455 this->Entity = Entity;
5456 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00005457 };
5458}
5459
Douglas Gregor15acfb92009-08-06 16:20:37 +00005460/// \brief Rebuilds a type within the context of the current instantiation.
5461///
Mike Stump11289f42009-09-09 15:08:12 +00005462/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005463/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005464/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005465/// partial specialization thereof). This routine will rebuild that type now
5466/// that we have entered the declarator's scope, which may produce different
5467/// canonical types, e.g.,
5468///
5469/// \code
5470/// template<typename T>
5471/// struct X {
5472/// typedef T* pointer;
5473/// pointer data();
5474/// };
5475///
5476/// template<typename T>
5477/// typename X<T>::pointer X<T>::data() { ... }
5478/// \endcode
5479///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005480/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005481/// since we do not know that we can look into X<T> when we parsed the type.
5482/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005483/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005484/// as the canonical type of T*, allowing the return types of the out-of-line
5485/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005486TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5487 SourceLocation Loc,
5488 DeclarationName Name) {
5489 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005490 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005491
Douglas Gregor15acfb92009-08-06 16:20:37 +00005492 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5493 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005494}
Douglas Gregorbe999392009-09-15 16:23:51 +00005495
John McCalldadc5752010-08-24 06:29:42 +00005496ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00005497 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5498 DeclarationName());
5499 return Rebuilder.TransformExpr(E);
5500}
5501
John McCall99b2fe52010-04-29 23:50:39 +00005502bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5503 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005504
5505 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5506 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5507 DeclarationName());
5508 NestedNameSpecifier *Rebuilt =
5509 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005510 if (!Rebuilt) return true;
5511
5512 SS.setScopeRep(Rebuilt);
5513 return false;
John McCall2408e322010-04-27 00:57:59 +00005514}
5515
Douglas Gregorbe999392009-09-15 16:23:51 +00005516/// \brief Produces a formatted string that describes the binding of
5517/// template parameters to template arguments.
5518std::string
5519Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5520 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005521 // FIXME: For variadic templates, we'll need to get the structured list.
5522 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5523 Args.flat_size());
5524}
5525
5526std::string
5527Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5528 const TemplateArgument *Args,
5529 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005530 std::string Result;
5531
Douglas Gregore62e6a02009-11-11 19:13:48 +00005532 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005533 return Result;
5534
5535 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005536 if (I >= NumArgs)
5537 break;
5538
Douglas Gregorbe999392009-09-15 16:23:51 +00005539 if (I == 0)
5540 Result += "[with ";
5541 else
5542 Result += ", ";
5543
5544 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5545 Result += Id->getName();
5546 } else {
5547 Result += '$';
5548 Result += llvm::utostr(I);
5549 }
5550
5551 Result += " = ";
5552
5553 switch (Args[I].getKind()) {
5554 case TemplateArgument::Null:
5555 Result += "<no value>";
5556 break;
5557
5558 case TemplateArgument::Type: {
5559 std::string TypeStr;
5560 Args[I].getAsType().getAsStringInternal(TypeStr,
5561 Context.PrintingPolicy);
5562 Result += TypeStr;
5563 break;
5564 }
5565
5566 case TemplateArgument::Declaration: {
5567 bool Unnamed = true;
5568 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5569 if (ND->getDeclName()) {
5570 Unnamed = false;
5571 Result += ND->getNameAsString();
5572 }
5573 }
5574
5575 if (Unnamed) {
5576 Result += "<anonymous>";
5577 }
5578 break;
5579 }
5580
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005581 case TemplateArgument::Template: {
5582 std::string Str;
5583 llvm::raw_string_ostream OS(Str);
5584 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5585 Result += OS.str();
5586 break;
5587 }
5588
Douglas Gregorbe999392009-09-15 16:23:51 +00005589 case TemplateArgument::Integral: {
5590 Result += Args[I].getAsIntegral()->toString(10);
5591 break;
5592 }
5593
5594 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005595 // FIXME: This is non-optimal, since we're regurgitating the
5596 // expression we were given.
5597 std::string Str;
5598 {
5599 llvm::raw_string_ostream OS(Str);
5600 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5601 Context.PrintingPolicy);
5602 }
5603 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005604 break;
5605 }
5606
5607 case TemplateArgument::Pack:
5608 // FIXME: Format template argument packs
5609 Result += "<template argument pack>";
5610 break;
5611 }
5612 }
5613
5614 Result += ']';
5615 return Result;
5616}