blob: ec928ea4b7bbe1b2559082943a2fd276dd6cdb10 [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.
John McCallde3fd222010-10-12 23:13:28 +00001377 if (Idx >= NumParamLists) {
1378 // Silently drop template member friend declarations.
1379 // TODO: implement these
1380 if (IsFriend && NumParamLists) Invalid = true;
1381
Douglas Gregord8d297c2009-07-21 23:53:31 +00001382 return 0;
John McCallde3fd222010-10-12 23:13:28 +00001383 }
Mike Stump11289f42009-09-09 15:08:12 +00001384
Douglas Gregord8d297c2009-07-21 23:53:31 +00001385 // If there were too many template parameter lists, complain about that now.
1386 if (Idx != NumParamLists - 1) {
1387 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001388 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001389 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001390 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1391 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001392 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1393 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001394
1395 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1396 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1397 diag::note_explicit_template_spec_does_not_need_header)
1398 << ExplicitSpecializationsInSpecifier.back();
1399 ExplicitSpecializationsInSpecifier.pop_back();
1400 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001401
1402 // We have a template parameter list with no corresponding scope, which
1403 // means that the resulting template declaration can't be instantiated
1404 // properly (we'll end up with dependent nodes when we shouldn't).
1405 if (!isExplicitSpecHeader)
1406 Invalid = true;
1407
Douglas Gregord8d297c2009-07-21 23:53:31 +00001408 ++Idx;
1409 }
1410 }
Mike Stump11289f42009-09-09 15:08:12 +00001411
John McCallde3fd222010-10-12 23:13:28 +00001412 // Silently drop template member template friend declarations.
1413 // TODO: implement these
1414 if (IsFriend && NumParamLists > 1)
1415 Invalid = true;
1416
Douglas Gregord8d297c2009-07-21 23:53:31 +00001417 // Return the last template parameter list, which corresponds to the
1418 // entity being declared.
1419 return ParamLists[NumParamLists - 1];
1420}
1421
Douglas Gregordc572a32009-03-30 22:58:21 +00001422QualType Sema::CheckTemplateIdType(TemplateName Name,
1423 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001424 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001425 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001426 if (!Template) {
1427 // The template name does not resolve to a template, so we just
1428 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001429 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001430 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001431
Douglas Gregorc40290e2009-03-09 23:48:35 +00001432 // Check that the template argument list is well-formed for this
1433 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001434 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001435 TemplateArgs.size());
1436 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001437 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001438 return QualType();
1439
Mike Stump11289f42009-09-09 15:08:12 +00001440 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001441 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001442 "Converted template argument list is too short!");
1443
1444 QualType CanonType;
1445
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001446 if (Name.isDependent() ||
1447 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001448 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001449 // This class template specialization is a dependent
1450 // type. Therefore, its canonical type is another class template
1451 // specialization type that contains all of the converted
1452 // arguments in canonical form. This ensures that, e.g., A<T> and
1453 // A<T, T> have identical types when A is declared as:
1454 //
1455 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001456 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001457 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001458 Converted.getFlatArguments(),
1459 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001460
Douglas Gregora8e02e72009-07-28 23:00:59 +00001461 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001462 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001463 // In the future, we need to teach getTemplateSpecializationType to only
1464 // build the canonical type and return that to us.
1465 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001466
1467 // This might work out to be a current instantiation, in which
1468 // case the canonical type needs to be the InjectedClassNameType.
1469 //
1470 // TODO: in theory this could be a simple hashtable lookup; most
1471 // changes to CurContext don't change the set of current
1472 // instantiations.
1473 if (isa<ClassTemplateDecl>(Template)) {
1474 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1475 // If we get out to a namespace, we're done.
1476 if (Ctx->isFileContext()) break;
1477
1478 // If this isn't a record, keep looking.
1479 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1480 if (!Record) continue;
1481
1482 // Look for one of the two cases with InjectedClassNameTypes
1483 // and check whether it's the same template.
1484 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1485 !Record->getDescribedClassTemplate())
1486 continue;
1487
1488 // Fetch the injected class name type and check whether its
1489 // injected type is equal to the type we just built.
1490 QualType ICNT = Context.getTypeDeclType(Record);
1491 QualType Injected = cast<InjectedClassNameType>(ICNT)
1492 ->getInjectedSpecializationType();
1493
1494 if (CanonType != Injected->getCanonicalTypeInternal())
1495 continue;
1496
1497 // If so, the canonical type of this TST is the injected
1498 // class name type of the record we just found.
1499 assert(ICNT.isCanonical());
1500 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00001501 break;
1502 }
1503 }
Mike Stump11289f42009-09-09 15:08:12 +00001504 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001505 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001506 // Find the class template specialization declaration that
1507 // corresponds to these arguments.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001508 void *InsertPos = 0;
1509 ClassTemplateSpecializationDecl *Decl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001510 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
1511 Converted.flatSize(), InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001512 if (!Decl) {
1513 // This is the first time we have referenced this class template
1514 // specialization. Create the canonical declaration and add it to
1515 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001516 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001517 ClassTemplate->getTemplatedDecl()->getTagKind(),
1518 ClassTemplate->getDeclContext(),
1519 ClassTemplate->getLocation(),
1520 ClassTemplate,
1521 Converted, 0);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001522 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001523 Decl->setLexicalDeclContext(CurContext);
1524 }
1525
1526 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001527 assert(isa<RecordType>(CanonType) &&
1528 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001529 }
Mike Stump11289f42009-09-09 15:08:12 +00001530
Douglas Gregorc40290e2009-03-09 23:48:35 +00001531 // Build the fully-sugared type for this class template
1532 // specialization, which refers back to the class template
1533 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00001534 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001535}
1536
John McCallfaf5fb42010-08-26 23:41:50 +00001537TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001538Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001539 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001540 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001541 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001542 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001543
Douglas Gregorc40290e2009-03-09 23:48:35 +00001544 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001545 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001546 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001547
John McCall6b51f282009-11-23 01:53:49 +00001548 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001549 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001550
1551 if (Result.isNull())
1552 return true;
1553
John McCallbcd03502009-12-07 02:54:59 +00001554 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001555 TemplateSpecializationTypeLoc TL
1556 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1557 TL.setTemplateNameLoc(TemplateLoc);
1558 TL.setLAngleLoc(LAngleLoc);
1559 TL.setRAngleLoc(RAngleLoc);
1560 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1561 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1562
John McCallba7bf592010-08-24 05:47:05 +00001563 return CreateParsedType(Result, DI);
John McCalld8fe9af2009-09-08 17:47:29 +00001564}
John McCall06f6fe8d2009-09-04 01:14:41 +00001565
John McCallfaf5fb42010-08-26 23:41:50 +00001566TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1567 TagUseKind TUK,
1568 TypeSpecifierType TagSpec,
1569 SourceLocation TagLoc) {
John McCalld8fe9af2009-09-08 17:47:29 +00001570 if (TypeResult.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00001571 return ::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001572
John McCall0ad16662009-10-29 08:12:44 +00001573 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001574 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001575 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001576
John McCalld8fe9af2009-09-08 17:47:29 +00001577 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001578 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001579
John McCalld8fe9af2009-09-08 17:47:29 +00001580 if (const RecordType *RT = Type->getAs<RecordType>()) {
1581 RecordDecl *D = RT->getDecl();
1582
1583 IdentifierInfo *Id = D->getIdentifier();
1584 assert(Id && "templated class must have an identifier");
1585
1586 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1587 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001588 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001589 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001590 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001591 }
1592 }
1593
Abramo Bagnara6150c882010-05-11 21:36:43 +00001594 ElaboratedTypeKeyword Keyword
1595 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1596 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001597
John McCallba7bf592010-08-24 05:47:05 +00001598 return ParsedType::make(ElabType);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001599}
1600
John McCalldadc5752010-08-24 06:29:42 +00001601ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001602 LookupResult &R,
1603 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001604 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001605 // FIXME: Can we do any checking at this point? I guess we could check the
1606 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001607 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001608 // though.
John McCalle66edc12009-11-24 19:00:30 +00001609
1610 // These should be filtered out by our callers.
1611 assert(!R.empty() && "empty lookup results when building templateid");
1612 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1613
1614 NestedNameSpecifier *Qualifier = 0;
1615 SourceRange QualifierRange;
1616 if (SS.isSet()) {
1617 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1618 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001619 }
John McCall58cc69d2010-01-27 01:50:18 +00001620
1621 // We don't want lookup warnings at this point.
1622 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001623
John McCalle66edc12009-11-24 19:00:30 +00001624 bool Dependent
1625 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1626 &TemplateArgs);
1627 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001628 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001629 Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001630 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001631 RequiresADL, TemplateArgs,
1632 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001633
1634 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001635}
1636
John McCalle66edc12009-11-24 19:00:30 +00001637// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00001638ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001639Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001640 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +00001641 const TemplateArgumentListInfo &TemplateArgs) {
1642 DeclContext *DC;
1643 if (!(DC = computeDeclContext(SS, false)) ||
1644 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001645 RequireCompleteDeclContext(SS, DC))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001646 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001647
Douglas Gregor786123d2010-05-21 23:18:07 +00001648 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001649 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00001650 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1651 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00001652
John McCalle66edc12009-11-24 19:00:30 +00001653 if (R.isAmbiguous())
1654 return ExprError();
1655
1656 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001657 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1658 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001659 return ExprError();
1660 }
1661
1662 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001663 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1664 << (NestedNameSpecifier*) SS.getScopeRep()
1665 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001666 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1667 return ExprError();
1668 }
1669
1670 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001671}
1672
Douglas Gregorb67535d2009-03-31 00:43:58 +00001673/// \brief Form a dependent template name.
1674///
1675/// This action forms a dependent template name given the template
1676/// name and its (presumably dependent) scope specifier. For
1677/// example, given "MetaFun::template apply", the scope specifier \p
1678/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1679/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregorbb119652010-06-16 23:00:59 +00001680TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1681 SourceLocation TemplateKWLoc,
1682 CXXScopeSpec &SS,
1683 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00001684 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00001685 bool EnteringContext,
1686 TemplateTy &Result) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00001687 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1688 !getLangOptions().CPlusPlus0x)
1689 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1690 << FixItHint::CreateRemoval(TemplateKWLoc);
1691
Douglas Gregor9abe2372010-01-19 16:01:07 +00001692 DeclContext *LookupCtx = 0;
1693 if (SS.isSet())
1694 LookupCtx = computeDeclContext(SS, EnteringContext);
1695 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00001696 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00001697 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001698 // C++0x [temp.names]p5:
1699 // If a name prefixed by the keyword template is not the name of
1700 // a template, the program is ill-formed. [Note: the keyword
1701 // template may not be applied to non-template members of class
1702 // templates. -end note ] [ Note: as is the case with the
1703 // typename prefix, the template prefix is allowed in cases
1704 // where it is not strictly necessary; i.e., when the
1705 // nested-name-specifier or the expression on the left of the ->
1706 // or . is not dependent on a template-parameter, or the use
1707 // does not appear in the scope of a template. -end note]
1708 //
1709 // Note: C++03 was more strict here, because it banned the use of
1710 // the "template" keyword prior to a template-name that was not a
1711 // dependent name. C++ DR468 relaxed this requirement (the
1712 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00001713 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00001714 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001715 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1716 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00001717 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001718 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1719 isa<CXXRecordDecl>(LookupCtx) &&
1720 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregorbb119652010-06-16 23:00:59 +00001721 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00001722 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001723 Diag(Name.getSourceRange().getBegin(),
1724 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001725 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001726 << Name.getSourceRange()
1727 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001728 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00001729 } else {
1730 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00001731 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001732 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001733 }
1734
Mike Stump11289f42009-09-09 15:08:12 +00001735 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001736 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001737
1738 switch (Name.getKind()) {
1739 case UnqualifiedId::IK_Identifier:
Douglas Gregorbb119652010-06-16 23:00:59 +00001740 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1741 Name.Identifier));
1742 return TNK_Dependent_template_name;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001743
Douglas Gregor71395fa2009-11-04 00:56:37 +00001744 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00001745 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00001746 Name.OperatorFunctionId.Operator));
Douglas Gregorbb119652010-06-16 23:00:59 +00001747 return TNK_Dependent_template_name;
Alexis Hunted0530f2009-11-28 08:58:14 +00001748
1749 case UnqualifiedId::IK_LiteralOperatorId:
1750 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1751
Douglas Gregor3cf81312009-11-03 23:16:33 +00001752 default:
1753 break;
1754 }
1755
1756 Diag(Name.getSourceRange().getBegin(),
1757 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001758 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001759 << Name.getSourceRange()
1760 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001761 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001762}
1763
Mike Stump11289f42009-09-09 15:08:12 +00001764bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001765 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001766 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001767 const TemplateArgument &Arg = AL.getArgument();
1768
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001769 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001770 switch(Arg.getKind()) {
1771 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001772 // C++ [temp.arg.type]p1:
1773 // A template-argument for a template-parameter which is a
1774 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001775 break;
1776 case TemplateArgument::Template: {
1777 // We have a template type parameter but the template argument
1778 // is a template without any arguments.
1779 SourceRange SR = AL.getSourceRange();
1780 TemplateName Name = Arg.getAsTemplate();
1781 Diag(SR.getBegin(), diag::err_template_missing_args)
1782 << Name << SR;
1783 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1784 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001785
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001786 return true;
1787 }
1788 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001789 // We have a template type parameter but the template argument
1790 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001791 SourceRange SR = AL.getSourceRange();
1792 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001793 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001794
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001795 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001796 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001797 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001798
John McCallbcd03502009-12-07 02:54:59 +00001799 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001800 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001801
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001802 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001803 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001804 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001805 return false;
1806}
1807
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001808/// \brief Substitute template arguments into the default template argument for
1809/// the given template type parameter.
1810///
1811/// \param SemaRef the semantic analysis object for which we are performing
1812/// the substitution.
1813///
1814/// \param Template the template that we are synthesizing template arguments
1815/// for.
1816///
1817/// \param TemplateLoc the location of the template name that started the
1818/// template-id we are checking.
1819///
1820/// \param RAngleLoc the location of the right angle bracket ('>') that
1821/// terminates the template-id.
1822///
1823/// \param Param the template template parameter whose default we are
1824/// substituting into.
1825///
1826/// \param Converted the list of template arguments provided for template
1827/// parameters that precede \p Param in the template parameter list.
1828///
1829/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001830static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001831SubstDefaultTemplateArgument(Sema &SemaRef,
1832 TemplateDecl *Template,
1833 SourceLocation TemplateLoc,
1834 SourceLocation RAngleLoc,
1835 TemplateTypeParmDecl *Param,
1836 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001837 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001838
1839 // If the argument type is dependent, instantiate it now based
1840 // on the previously-computed template arguments.
1841 if (ArgType->getType()->isDependentType()) {
1842 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1843 /*TakeArgs=*/false);
1844
1845 MultiLevelTemplateArgumentList AllTemplateArgs
1846 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1847
1848 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1849 Template, Converted.getFlatArguments(),
1850 Converted.flatSize(),
1851 SourceRange(TemplateLoc, RAngleLoc));
1852
1853 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1854 Param->getDefaultArgumentLoc(),
1855 Param->getDeclName());
1856 }
1857
1858 return ArgType;
1859}
1860
1861/// \brief Substitute template arguments into the default template argument for
1862/// the given non-type template parameter.
1863///
1864/// \param SemaRef the semantic analysis object for which we are performing
1865/// the substitution.
1866///
1867/// \param Template the template that we are synthesizing template arguments
1868/// for.
1869///
1870/// \param TemplateLoc the location of the template name that started the
1871/// template-id we are checking.
1872///
1873/// \param RAngleLoc the location of the right angle bracket ('>') that
1874/// terminates the template-id.
1875///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001876/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001877/// substituting into.
1878///
1879/// \param Converted the list of template arguments provided for template
1880/// parameters that precede \p Param in the template parameter list.
1881///
1882/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00001883static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001884SubstDefaultTemplateArgument(Sema &SemaRef,
1885 TemplateDecl *Template,
1886 SourceLocation TemplateLoc,
1887 SourceLocation RAngleLoc,
1888 NonTypeTemplateParmDecl *Param,
1889 TemplateArgumentListBuilder &Converted) {
1890 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1891 /*TakeArgs=*/false);
1892
1893 MultiLevelTemplateArgumentList AllTemplateArgs
1894 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1895
1896 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1897 Template, Converted.getFlatArguments(),
1898 Converted.flatSize(),
1899 SourceRange(TemplateLoc, RAngleLoc));
1900
1901 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1902}
1903
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001904/// \brief Substitute template arguments into the default template argument for
1905/// the given template template parameter.
1906///
1907/// \param SemaRef the semantic analysis object for which we are performing
1908/// the substitution.
1909///
1910/// \param Template the template that we are synthesizing template arguments
1911/// for.
1912///
1913/// \param TemplateLoc the location of the template name that started the
1914/// template-id we are checking.
1915///
1916/// \param RAngleLoc the location of the right angle bracket ('>') that
1917/// terminates the template-id.
1918///
1919/// \param Param the template template parameter whose default we are
1920/// substituting into.
1921///
1922/// \param Converted the list of template arguments provided for template
1923/// parameters that precede \p Param in the template parameter list.
1924///
1925/// \returns the substituted template argument, or NULL if an error occurred.
1926static TemplateName
1927SubstDefaultTemplateArgument(Sema &SemaRef,
1928 TemplateDecl *Template,
1929 SourceLocation TemplateLoc,
1930 SourceLocation RAngleLoc,
1931 TemplateTemplateParmDecl *Param,
1932 TemplateArgumentListBuilder &Converted) {
1933 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1934 /*TakeArgs=*/false);
1935
1936 MultiLevelTemplateArgumentList AllTemplateArgs
1937 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1938
1939 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1940 Template, Converted.getFlatArguments(),
1941 Converted.flatSize(),
1942 SourceRange(TemplateLoc, RAngleLoc));
1943
1944 return SemaRef.SubstTemplateName(
1945 Param->getDefaultArgument().getArgument().getAsTemplate(),
1946 Param->getDefaultArgument().getTemplateNameLoc(),
1947 AllTemplateArgs);
1948}
1949
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001950/// \brief If the given template parameter has a default template
1951/// argument, substitute into that default template argument and
1952/// return the corresponding template argument.
1953TemplateArgumentLoc
1954Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1955 SourceLocation TemplateLoc,
1956 SourceLocation RAngleLoc,
1957 Decl *Param,
1958 TemplateArgumentListBuilder &Converted) {
1959 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1960 if (!TypeParm->hasDefaultArgument())
1961 return TemplateArgumentLoc();
1962
John McCallbcd03502009-12-07 02:54:59 +00001963 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001964 TemplateLoc,
1965 RAngleLoc,
1966 TypeParm,
1967 Converted);
1968 if (DI)
1969 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1970
1971 return TemplateArgumentLoc();
1972 }
1973
1974 if (NonTypeTemplateParmDecl *NonTypeParm
1975 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1976 if (!NonTypeParm->hasDefaultArgument())
1977 return TemplateArgumentLoc();
1978
John McCalldadc5752010-08-24 06:29:42 +00001979 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001980 TemplateLoc,
1981 RAngleLoc,
1982 NonTypeParm,
1983 Converted);
1984 if (Arg.isInvalid())
1985 return TemplateArgumentLoc();
1986
1987 Expr *ArgE = Arg.takeAs<Expr>();
1988 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1989 }
1990
1991 TemplateTemplateParmDecl *TempTempParm
1992 = cast<TemplateTemplateParmDecl>(Param);
1993 if (!TempTempParm->hasDefaultArgument())
1994 return TemplateArgumentLoc();
1995
1996 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1997 TemplateLoc,
1998 RAngleLoc,
1999 TempTempParm,
2000 Converted);
2001 if (TName.isNull())
2002 return TemplateArgumentLoc();
2003
2004 return TemplateArgumentLoc(TemplateArgument(TName),
2005 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2006 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2007}
2008
Douglas Gregorda0fb532009-11-11 19:31:23 +00002009/// \brief Check that the given template argument corresponds to the given
2010/// template parameter.
2011bool Sema::CheckTemplateArgument(NamedDecl *Param,
2012 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002013 TemplateDecl *Template,
2014 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002015 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002016 TemplateArgumentListBuilder &Converted,
2017 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00002018 // Check template type parameters.
2019 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002020 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002021
Douglas Gregoreebed722009-11-11 19:41:09 +00002022 // Check non-type template parameters.
2023 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00002024 // Do substitution on the type of the non-type template parameter
2025 // with the template arguments we've seen thus far.
2026 QualType NTTPType = NTTP->getType();
2027 if (NTTPType->isDependentType()) {
2028 // Do substitution on the type of the non-type template parameter.
2029 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2030 NTTP, Converted.getFlatArguments(),
2031 Converted.flatSize(),
2032 SourceRange(TemplateLoc, RAngleLoc));
2033
2034 TemplateArgumentList TemplateArgs(Context, Converted,
2035 /*TakeArgs=*/false);
2036 NTTPType = SubstType(NTTPType,
2037 MultiLevelTemplateArgumentList(TemplateArgs),
2038 NTTP->getLocation(),
2039 NTTP->getDeclName());
2040 // If that worked, check the non-type template parameter type
2041 // for validity.
2042 if (!NTTPType.isNull())
2043 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2044 NTTP->getLocation());
2045 if (NTTPType.isNull())
2046 return true;
2047 }
2048
2049 switch (Arg.getArgument().getKind()) {
2050 case TemplateArgument::Null:
2051 assert(false && "Should never see a NULL template argument here");
2052 return true;
2053
2054 case TemplateArgument::Expression: {
2055 Expr *E = Arg.getArgument().getAsExpr();
2056 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002057 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002058 return true;
2059
2060 Converted.Append(Result);
2061 break;
2062 }
2063
2064 case TemplateArgument::Declaration:
2065 case TemplateArgument::Integral:
2066 // We've already checked this template argument, so just copy
2067 // it to the list of converted arguments.
2068 Converted.Append(Arg.getArgument());
2069 break;
2070
2071 case TemplateArgument::Template:
2072 // We were given a template template argument. It may not be ill-formed;
2073 // see below.
2074 if (DependentTemplateName *DTN
2075 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2076 // We have a template argument such as \c T::template X, which we
2077 // parsed as a template template argument. However, since we now
2078 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002079 // template name into an expression.
2080
2081 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2082 Arg.getTemplateNameLoc());
2083
John McCalle66edc12009-11-24 19:00:30 +00002084 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2085 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002086 Arg.getTemplateQualifierRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002087 NameInfo);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002088
2089 TemplateArgument Result;
2090 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2091 return true;
2092
2093 Converted.Append(Result);
2094 break;
2095 }
2096
2097 // We have a template argument that actually does refer to a class
2098 // template, template alias, or template template parameter, and
2099 // therefore cannot be a non-type template argument.
2100 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2101 << Arg.getSourceRange();
2102
2103 Diag(Param->getLocation(), diag::note_template_param_here);
2104 return true;
2105
2106 case TemplateArgument::Type: {
2107 // We have a non-type template parameter but the template
2108 // argument is a type.
2109
2110 // C++ [temp.arg]p2:
2111 // In a template-argument, an ambiguity between a type-id and
2112 // an expression is resolved to a type-id, regardless of the
2113 // form of the corresponding template-parameter.
2114 //
2115 // We warn specifically about this case, since it can be rather
2116 // confusing for users.
2117 QualType T = Arg.getArgument().getAsType();
2118 SourceRange SR = Arg.getSourceRange();
2119 if (T->isFunctionType())
2120 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2121 else
2122 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2123 Diag(Param->getLocation(), diag::note_template_param_here);
2124 return true;
2125 }
2126
2127 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002128 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002129 break;
2130 }
2131
2132 return false;
2133 }
2134
2135
2136 // Check template template parameters.
2137 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2138
2139 // Substitute into the template parameter list of the template
2140 // template parameter, since previously-supplied template arguments
2141 // may appear within the template template parameter.
2142 {
2143 // Set up a template instantiation context.
2144 LocalInstantiationScope Scope(*this);
2145 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2146 TempParm, Converted.getFlatArguments(),
2147 Converted.flatSize(),
2148 SourceRange(TemplateLoc, RAngleLoc));
2149
2150 TemplateArgumentList TemplateArgs(Context, Converted,
2151 /*TakeArgs=*/false);
2152 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2153 SubstDecl(TempParm, CurContext,
2154 MultiLevelTemplateArgumentList(TemplateArgs)));
2155 if (!TempParm)
2156 return true;
2157
2158 // FIXME: TempParam is leaked.
2159 }
2160
2161 switch (Arg.getArgument().getKind()) {
2162 case TemplateArgument::Null:
2163 assert(false && "Should never see a NULL template argument here");
2164 return true;
2165
2166 case TemplateArgument::Template:
2167 if (CheckTemplateArgument(TempParm, Arg))
2168 return true;
2169
2170 Converted.Append(Arg.getArgument());
2171 break;
2172
2173 case TemplateArgument::Expression:
2174 case TemplateArgument::Type:
2175 // We have a template template parameter but the template
2176 // argument does not refer to a template.
2177 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2178 return true;
2179
2180 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002181 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002182 "Declaration argument with template template parameter");
2183 break;
2184 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002185 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002186 "Integral argument with template template parameter");
2187 break;
2188
2189 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002190 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002191 break;
2192 }
2193
2194 return false;
2195}
2196
Douglas Gregord32e0282009-02-09 23:23:08 +00002197/// \brief Check that the given template argument list is well-formed
2198/// for specializing the given template.
2199bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2200 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002201 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002202 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002203 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002204 TemplateParameterList *Params = Template->getTemplateParameters();
2205 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002206 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002207 bool Invalid = false;
2208
John McCall6b51f282009-11-23 01:53:49 +00002209 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2210
Mike Stump11289f42009-09-09 15:08:12 +00002211 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002212 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002213
Anders Carlsson15201f12009-06-13 02:08:00 +00002214 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002215 (NumArgs < Params->getMinRequiredArguments() &&
2216 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002217 // FIXME: point at either the first arg beyond what we can handle,
2218 // or the '>', depending on whether we have too many or too few
2219 // arguments.
2220 SourceRange Range;
2221 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002222 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002223 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2224 << (NumArgs > NumParams)
2225 << (isa<ClassTemplateDecl>(Template)? 0 :
2226 isa<FunctionTemplateDecl>(Template)? 1 :
2227 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2228 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002229 Diag(Template->getLocation(), diag::note_template_decl_here)
2230 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002231 Invalid = true;
2232 }
Mike Stump11289f42009-09-09 15:08:12 +00002233
2234 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002235 // [...] The type and form of each template-argument specified in
2236 // a template-id shall match the type and form specified for the
2237 // corresponding parameter declared by the template in its
2238 // template-parameter-list.
2239 unsigned ArgIdx = 0;
2240 for (TemplateParameterList::iterator Param = Params->begin(),
2241 ParamEnd = Params->end();
2242 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002243 if (ArgIdx > NumArgs && PartialTemplateArgs)
2244 break;
Mike Stump11289f42009-09-09 15:08:12 +00002245
Douglas Gregoreebed722009-11-11 19:41:09 +00002246 // If we have a template parameter pack, check every remaining template
2247 // argument against that template parameter pack.
2248 if ((*Param)->isTemplateParameterPack()) {
2249 Converted.BeginPack();
2250 for (; ArgIdx < NumArgs; ++ArgIdx) {
2251 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2252 TemplateLoc, RAngleLoc, Converted)) {
2253 Invalid = true;
2254 break;
2255 }
2256 }
2257 Converted.EndPack();
2258 continue;
2259 }
2260
Douglas Gregor84d49a22009-11-11 21:54:23 +00002261 if (ArgIdx < NumArgs) {
2262 // Check the template argument we were given.
2263 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2264 TemplateLoc, RAngleLoc, Converted))
2265 return true;
2266
2267 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002268 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002269
Douglas Gregor84d49a22009-11-11 21:54:23 +00002270 // We have a default template argument that we will use.
2271 TemplateArgumentLoc Arg;
2272
2273 // Retrieve the default template argument from the template
2274 // parameter. For each kind of template parameter, we substitute the
2275 // template arguments provided thus far and any "outer" template arguments
2276 // (when the template parameter was part of a nested template) into
2277 // the default argument.
2278 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2279 if (!TTP->hasDefaultArgument()) {
2280 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2281 break;
2282 }
2283
John McCallbcd03502009-12-07 02:54:59 +00002284 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002285 Template,
2286 TemplateLoc,
2287 RAngleLoc,
2288 TTP,
2289 Converted);
2290 if (!ArgType)
2291 return true;
2292
2293 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2294 ArgType);
2295 } else if (NonTypeTemplateParmDecl *NTTP
2296 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2297 if (!NTTP->hasDefaultArgument()) {
2298 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2299 break;
2300 }
2301
John McCalldadc5752010-08-24 06:29:42 +00002302 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002303 TemplateLoc,
2304 RAngleLoc,
2305 NTTP,
2306 Converted);
2307 if (E.isInvalid())
2308 return true;
2309
2310 Expr *Ex = E.takeAs<Expr>();
2311 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2312 } else {
2313 TemplateTemplateParmDecl *TempParm
2314 = cast<TemplateTemplateParmDecl>(*Param);
2315
2316 if (!TempParm->hasDefaultArgument()) {
2317 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2318 break;
2319 }
2320
2321 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2322 TemplateLoc,
2323 RAngleLoc,
2324 TempParm,
2325 Converted);
2326 if (Name.isNull())
2327 return true;
2328
2329 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2330 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2331 TempParm->getDefaultArgument().getTemplateNameLoc());
2332 }
2333
2334 // Introduce an instantiation record that describes where we are using
2335 // the default template argument.
2336 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2337 Converted.getFlatArguments(),
2338 Converted.flatSize(),
2339 SourceRange(TemplateLoc, RAngleLoc));
2340
2341 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002342 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002343 RAngleLoc, Converted))
2344 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002345 }
2346
2347 return Invalid;
2348}
2349
2350/// \brief Check a template argument against its corresponding
2351/// template type parameter.
2352///
2353/// This routine implements the semantics of C++ [temp.arg.type]. It
2354/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002355bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002356 TypeSourceInfo *ArgInfo) {
2357 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002358 QualType Arg = ArgInfo->getType();
2359
Chandler Carruth9bb67f42010-09-03 21:12:34 +00002360 // C++03 [temp.arg.type]p2:
Douglas Gregord32e0282009-02-09 23:23:08 +00002361 // A local type, a type with no linkage, an unnamed type or a type
2362 // compounded from any of these types shall not be used as a
2363 // template-argument for a template type-parameter.
Chandler Carruth9bb67f42010-09-03 21:12:34 +00002364 // C++0x allows these, and even in C++03 we allow them as an extension with
2365 // a warning.
Douglas Gregor959d5a02010-05-22 16:17:30 +00002366 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00002367 if (!LangOpts.CPlusPlus0x) {
2368 const TagType *Tag = 0;
2369 if (const EnumType *EnumT = Arg->getAs<EnumType>())
2370 Tag = EnumT;
2371 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
2372 Tag = RecordT;
2373 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2374 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
2375 Diag(SR.getBegin(), diag::ext_template_arg_local_type)
2376 << QualType(Tag, 0) << SR;
2377 } else if (Tag && !Tag->getDecl()->getDeclName() &&
2378 !Tag->getDecl()->getTypedefForAnonDecl()) {
2379 Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
2380 Diag(Tag->getDecl()->getLocation(),
2381 diag::note_template_unnamed_type_here);
2382 }
2383 }
2384
2385 if (Arg->isVariablyModifiedType()) {
2386 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002387 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002388 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002389 }
2390
2391 return false;
2392}
2393
Douglas Gregorccb07762009-02-11 19:52:55 +00002394/// \brief Checks whether the given template argument is the address
2395/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002396static bool
2397CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2398 NonTypeTemplateParmDecl *Param,
2399 QualType ParamType,
2400 Expr *ArgIn,
2401 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002402 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002403 Expr *Arg = ArgIn;
2404 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002405
2406 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002407 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002408 Arg = Cast->getSubExpr();
2409
2410 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002411 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002412 // A template-argument for a non-type, non-template
2413 // template-parameter shall be one of: [...]
2414 //
2415 // -- the address of an object or function with external
2416 // linkage, including function templates and function
2417 // template-ids but excluding non-static class members,
2418 // expressed as & id-expression where the & is optional if
2419 // the name refers to a function or array, or if the
2420 // corresponding template-parameter is a reference; or
2421 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002422
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002423 // In C++98/03 mode, give an extension warning on any extra parentheses.
2424 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2425 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002426 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002427 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002428 S.Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002429 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002430 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002431 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002432 }
2433
2434 Arg = Parens->getSubExpr();
2435 }
2436
Douglas Gregorb242683d2010-04-01 18:32:35 +00002437 bool AddressTaken = false;
2438 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002439 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00002440 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002441 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002442 AddressTaken = true;
2443 AddrOpLoc = UnOp->getOperatorLoc();
2444 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002445 } else
2446 DRE = dyn_cast<DeclRefExpr>(Arg);
2447
Douglas Gregorb242683d2010-04-01 18:32:35 +00002448 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002449 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2450 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002451 S.Diag(Param->getLocation(), diag::note_template_param_here);
2452 return true;
2453 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002454
2455 // Stop checking the precise nature of the argument if it is value dependent,
2456 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002457 if (Arg->isValueDependent()) {
2458 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002459 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002460 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002461
Douglas Gregorb242683d2010-04-01 18:32:35 +00002462 if (!isa<ValueDecl>(DRE->getDecl())) {
2463 S.Diag(Arg->getSourceRange().getBegin(),
2464 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002465 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002466 S.Diag(Param->getLocation(), diag::note_template_param_here);
2467 return true;
2468 }
2469
2470 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002471
2472 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002473 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2474 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002475 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002476 S.Diag(Param->getLocation(), diag::note_template_param_here);
2477 return true;
2478 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002479
2480 // Cannot refer to non-static member functions
2481 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002482 if (!Method->isStatic()) {
2483 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002484 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002485 S.Diag(Param->getLocation(), diag::note_template_param_here);
2486 return true;
2487 }
Mike Stump11289f42009-09-09 15:08:12 +00002488
Douglas Gregorccb07762009-02-11 19:52:55 +00002489 // Functions must have external linkage.
2490 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002491 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002492 S.Diag(Arg->getSourceRange().getBegin(),
2493 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002494 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002495 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002496 << true;
2497 return true;
2498 }
2499
2500 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002501 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002502
Douglas Gregorb242683d2010-04-01 18:32:35 +00002503 // If the template parameter has pointer type, the function decays.
2504 if (ParamType->isPointerType() && !AddressTaken)
2505 ArgType = S.Context.getPointerType(Func->getType());
2506 else if (AddressTaken && ParamType->isReferenceType()) {
2507 // If we originally had an address-of operator, but the
2508 // parameter has reference type, complain and (if things look
2509 // like they will work) drop the address-of operator.
2510 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2511 ParamType.getNonReferenceType())) {
2512 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2513 << ParamType;
2514 S.Diag(Param->getLocation(), diag::note_template_param_here);
2515 return true;
2516 }
2517
2518 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2519 << ParamType
2520 << FixItHint::CreateRemoval(AddrOpLoc);
2521 S.Diag(Param->getLocation(), diag::note_template_param_here);
2522
2523 ArgType = Func->getType();
2524 }
2525 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002526 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002527 S.Diag(Arg->getSourceRange().getBegin(),
2528 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002529 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002530 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002531 << true;
2532 return true;
2533 }
2534
Douglas Gregorb242683d2010-04-01 18:32:35 +00002535 // A value of reference type is not an object.
2536 if (Var->getType()->isReferenceType()) {
2537 S.Diag(Arg->getSourceRange().getBegin(),
2538 diag::err_template_arg_reference_var)
2539 << Var->getType() << Arg->getSourceRange();
2540 S.Diag(Param->getLocation(), diag::note_template_param_here);
2541 return true;
2542 }
2543
Douglas Gregorccb07762009-02-11 19:52:55 +00002544 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002545 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002546
2547 // If the template parameter has pointer type, we must have taken
2548 // the address of this object.
2549 if (ParamType->isReferenceType()) {
2550 if (AddressTaken) {
2551 // If we originally had an address-of operator, but the
2552 // parameter has reference type, complain and (if things look
2553 // like they will work) drop the address-of operator.
2554 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2555 ParamType.getNonReferenceType())) {
2556 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2557 << ParamType;
2558 S.Diag(Param->getLocation(), diag::note_template_param_here);
2559 return true;
2560 }
2561
2562 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2563 << ParamType
2564 << FixItHint::CreateRemoval(AddrOpLoc);
2565 S.Diag(Param->getLocation(), diag::note_template_param_here);
2566
2567 ArgType = Var->getType();
2568 }
2569 } else if (!AddressTaken && ParamType->isPointerType()) {
2570 if (Var->getType()->isArrayType()) {
2571 // Array-to-pointer decay.
2572 ArgType = S.Context.getArrayDecayedType(Var->getType());
2573 } else {
2574 // If the template parameter has pointer type but the address of
2575 // this object was not taken, complain and (possibly) recover by
2576 // taking the address of the entity.
2577 ArgType = S.Context.getPointerType(Var->getType());
2578 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2579 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2580 << ParamType;
2581 S.Diag(Param->getLocation(), diag::note_template_param_here);
2582 return true;
2583 }
2584
2585 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2586 << ParamType
2587 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2588
2589 S.Diag(Param->getLocation(), diag::note_template_param_here);
2590 }
2591 }
2592 } else {
2593 // We found something else, but we don't know specifically what it is.
2594 S.Diag(Arg->getSourceRange().getBegin(),
2595 diag::err_template_arg_not_object_or_func)
2596 << Arg->getSourceRange();
2597 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2598 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002599 }
Mike Stump11289f42009-09-09 15:08:12 +00002600
Douglas Gregorb242683d2010-04-01 18:32:35 +00002601 if (ParamType->isPointerType() &&
2602 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2603 S.IsQualificationConversion(ArgType, ParamType)) {
2604 // For pointer-to-object types, qualification conversions are
2605 // permitted.
2606 } else {
2607 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2608 if (!ParamRef->getPointeeType()->isFunctionType()) {
2609 // C++ [temp.arg.nontype]p5b3:
2610 // For a non-type template-parameter of type reference to
2611 // object, no conversions apply. The type referred to by the
2612 // reference may be more cv-qualified than the (otherwise
2613 // identical) type of the template- argument. The
2614 // template-parameter is bound directly to the
2615 // template-argument, which shall be an lvalue.
2616
2617 // FIXME: Other qualifiers?
2618 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2619 unsigned ArgQuals = ArgType.getCVRQualifiers();
2620
2621 if ((ParamQuals | ArgQuals) != ParamQuals) {
2622 S.Diag(Arg->getSourceRange().getBegin(),
2623 diag::err_template_arg_ref_bind_ignores_quals)
2624 << ParamType << Arg->getType()
2625 << Arg->getSourceRange();
2626 S.Diag(Param->getLocation(), diag::note_template_param_here);
2627 return true;
2628 }
2629 }
2630 }
2631
2632 // At this point, the template argument refers to an object or
2633 // function with external linkage. We now need to check whether the
2634 // argument and parameter types are compatible.
2635 if (!S.Context.hasSameUnqualifiedType(ArgType,
2636 ParamType.getNonReferenceType())) {
2637 // We can't perform this conversion or binding.
2638 if (ParamType->isReferenceType())
2639 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2640 << ParamType << Arg->getType() << Arg->getSourceRange();
2641 else
2642 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2643 << Arg->getType() << ParamType << Arg->getSourceRange();
2644 S.Diag(Param->getLocation(), diag::note_template_param_here);
2645 return true;
2646 }
2647 }
2648
2649 // Create the template argument.
2650 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002651 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002652 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002653}
2654
2655/// \brief Checks whether the given template argument is a pointer to
2656/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002657bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2658 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002659 bool Invalid = false;
2660
2661 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002662 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002663 Arg = Cast->getSubExpr();
2664
2665 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002666 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002667 // A template-argument for a non-type, non-template
2668 // template-parameter shall be one of: [...]
2669 //
2670 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002671 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002672
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002673 // In C++98/03 mode, give an extension warning on any extra parentheses.
2674 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2675 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002676 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002677 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00002678 Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002679 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002680 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002681 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002682 }
2683
2684 Arg = Parens->getSubExpr();
2685 }
2686
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002687 // A pointer-to-member constant written &Class::member.
2688 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00002689 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002690 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2691 if (DRE && !DRE->getQualifier())
2692 DRE = 0;
2693 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002694 }
2695 // A constant of pointer-to-member type.
2696 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2697 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2698 if (VD->getType()->isMemberPointerType()) {
2699 if (isa<NonTypeTemplateParmDecl>(VD) ||
2700 (isa<VarDecl>(VD) &&
2701 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2702 if (Arg->isTypeDependent() || Arg->isValueDependent())
2703 Converted = TemplateArgument(Arg->Retain());
2704 else
2705 Converted = TemplateArgument(VD->getCanonicalDecl());
2706 return Invalid;
2707 }
2708 }
2709 }
2710
2711 DRE = 0;
2712 }
2713
Douglas Gregorccb07762009-02-11 19:52:55 +00002714 if (!DRE)
2715 return Diag(Arg->getSourceRange().getBegin(),
2716 diag::err_template_arg_not_pointer_to_member_form)
2717 << Arg->getSourceRange();
2718
2719 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2720 assert((isa<FieldDecl>(DRE->getDecl()) ||
2721 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2722 "Only non-static member pointers can make it here");
2723
2724 // Okay: this is the address of a non-static member, and therefore
2725 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002726 if (Arg->isTypeDependent() || Arg->isValueDependent())
2727 Converted = TemplateArgument(Arg->Retain());
2728 else
2729 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002730 return Invalid;
2731 }
2732
2733 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002734 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002735 diag::err_template_arg_not_pointer_to_member_form)
2736 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002737 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002738 diag::note_template_arg_refers_here);
2739 return true;
2740}
2741
Douglas Gregord32e0282009-02-09 23:23:08 +00002742/// \brief Check a template argument against its corresponding
2743/// non-type template parameter.
2744///
Douglas Gregor463421d2009-03-03 04:44:36 +00002745/// This routine implements the semantics of C++ [temp.arg.nontype].
2746/// It returns true if an error occurred, and false otherwise. \p
2747/// InstantiatedParamType is the type of the non-type template
2748/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002749///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002750/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002751bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002752 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002753 TemplateArgument &Converted,
2754 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002755 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2756
Douglas Gregor86560402009-02-10 23:36:10 +00002757 // If either the parameter has a dependent type or the argument is
2758 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002759 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2760 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002761 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002762 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002763 }
Douglas Gregor86560402009-02-10 23:36:10 +00002764
2765 // C++ [temp.arg.nontype]p5:
2766 // The following conversions are performed on each expression used
2767 // as a non-type template-argument. If a non-type
2768 // template-argument cannot be converted to the type of the
2769 // corresponding template-parameter then the program is
2770 // ill-formed.
2771 //
2772 // -- for a non-type template-parameter of integral or
2773 // enumeration type, integral promotions (4.5) and integral
2774 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002775 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002776 QualType ArgType = Arg->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +00002777 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002778 // C++ [temp.arg.nontype]p1:
2779 // A template-argument for a non-type, non-template
2780 // template-parameter shall be one of:
2781 //
2782 // -- an integral constant-expression of integral or enumeration
2783 // type; or
2784 // -- the name of a non-type template-parameter; or
2785 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002786 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00002787 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002788 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002789 diag::err_template_arg_not_integral_or_enumeral)
2790 << ArgType << Arg->getSourceRange();
2791 Diag(Param->getLocation(), diag::note_template_param_here);
2792 return true;
2793 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002794 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002795 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2796 << ArgType << Arg->getSourceRange();
2797 return true;
2798 }
2799
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002800 // From here on out, all we care about are the unqualified forms
2801 // of the parameter and argument types.
2802 ParamType = ParamType.getUnqualifiedType();
2803 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00002804
2805 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002806 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002807 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002808 } else if (CTAK == CTAK_Deduced) {
2809 // C++ [temp.deduct.type]p17:
2810 // If, in the declaration of a function template with a non-type
2811 // template-parameter, the non-type template- parameter is used
2812 // in an expression in the function parameter-list and, if the
2813 // corresponding template-argument is deduced, the
2814 // template-argument type shall match the type of the
2815 // template-parameter exactly, except that a template-argument
2816 // deduced from an array bound may be of any integral type.
2817 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2818 << ArgType << ParamType;
2819 Diag(Param->getLocation(), diag::note_template_param_here);
2820 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00002821 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2822 !ParamType->isEnumeralType()) {
2823 // This is an integral promotion or conversion.
John McCalle3027922010-08-25 11:45:40 +00002824 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002825 } else {
2826 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002827 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002828 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002829 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002830 Diag(Param->getLocation(), diag::note_template_param_here);
2831 return true;
2832 }
2833
Douglas Gregor52aba872009-03-14 00:20:21 +00002834 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002835 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002836 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002837
2838 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002839 llvm::APSInt OldValue = Value;
2840
2841 // Coerce the template argument's value to the value it will have
2842 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002843 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002844 if (Value.getBitWidth() != AllowedBits)
2845 Value.extOrTrunc(AllowedBits);
2846 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002847
2848 // Complain if an unsigned parameter received a negative value.
2849 if (IntegerType->isUnsignedIntegerType()
2850 && (OldValue.isSigned() && OldValue.isNegative())) {
2851 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2852 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2853 << Arg->getSourceRange();
2854 Diag(Param->getLocation(), diag::note_template_param_here);
2855 }
2856
2857 // Complain if we overflowed the template parameter's type.
2858 unsigned RequiredBits;
2859 if (IntegerType->isUnsignedIntegerType())
2860 RequiredBits = OldValue.getActiveBits();
2861 else if (OldValue.isUnsigned())
2862 RequiredBits = OldValue.getActiveBits() + 1;
2863 else
2864 RequiredBits = OldValue.getMinSignedBits();
2865 if (RequiredBits > AllowedBits) {
2866 Diag(Arg->getSourceRange().getBegin(),
2867 diag::warn_template_arg_too_large)
2868 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2869 << Arg->getSourceRange();
2870 Diag(Param->getLocation(), diag::note_template_param_here);
2871 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002872 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002873
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002874 // Add the value of this argument to the list of converted
2875 // arguments. We use the bitwidth and signedness of the template
2876 // parameter.
2877 if (Arg->isValueDependent()) {
2878 // The argument is value-dependent. Create a new
2879 // TemplateArgument with the converted expression.
2880 Converted = TemplateArgument(Arg);
2881 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002882 }
2883
John McCall0ad16662009-10-29 08:12:44 +00002884 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002885 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002886 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002887 return false;
2888 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002889
John McCall16df1e52010-03-30 21:47:33 +00002890 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2891
Douglas Gregorb242683d2010-04-01 18:32:35 +00002892 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2893 // from a template argument of type std::nullptr_t to a non-type
2894 // template parameter of type pointer to object, pointer to
2895 // function, or pointer-to-member, respectively.
2896 if (ArgType->isNullPtrType() &&
2897 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2898 Converted = TemplateArgument((NamedDecl *)0);
2899 return false;
2900 }
2901
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002902 // Handle pointer-to-function, reference-to-function, and
2903 // pointer-to-member-function all in (roughly) the same way.
2904 if (// -- For a non-type template-parameter of type pointer to
2905 // function, only the function-to-pointer conversion (4.3) is
2906 // applied. If the template-argument represents a set of
2907 // overloaded functions (or a pointer to such), the matching
2908 // function is selected from the set (13.4).
2909 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002910 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002911 // -- For a non-type template-parameter of type reference to
2912 // function, no conversions apply. If the template-argument
2913 // represents a set of overloaded functions, the matching
2914 // function is selected from the set (13.4).
2915 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002916 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002917 // -- For a non-type template-parameter of type pointer to
2918 // member function, no conversions apply. If the
2919 // template-argument represents a set of overloaded member
2920 // functions, the matching member function is selected from
2921 // the set (13.4).
2922 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002923 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002924 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002925
Douglas Gregor064fdb22010-04-14 23:11:21 +00002926 if (Arg->getType() == Context.OverloadTy) {
2927 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2928 true,
2929 FoundResult)) {
2930 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2931 return true;
2932
2933 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2934 ArgType = Arg->getType();
2935 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00002936 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002937 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002938
Douglas Gregorb242683d2010-04-01 18:32:35 +00002939 if (!ParamType->isMemberPointerType())
2940 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2941 ParamType,
2942 Arg, Converted);
2943
2944 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCalle3027922010-08-25 11:45:40 +00002945 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb242683d2010-04-01 18:32:35 +00002946 } else if (!Context.hasSameUnqualifiedType(ArgType,
2947 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002948 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002949 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002950 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002951 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002952 Diag(Param->getLocation(), diag::note_template_param_here);
2953 return true;
2954 }
Mike Stump11289f42009-09-09 15:08:12 +00002955
Douglas Gregorb242683d2010-04-01 18:32:35 +00002956 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002957 }
2958
Chris Lattner696197c2009-02-20 21:37:53 +00002959 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002960 // -- for a non-type template-parameter of type pointer to
2961 // object, qualification conversions (4.4) and the
2962 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002963 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00002964 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002965 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002966
Douglas Gregorb242683d2010-04-01 18:32:35 +00002967 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2968 ParamType,
2969 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00002970 }
Mike Stump11289f42009-09-09 15:08:12 +00002971
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002972 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002973 // -- For a non-type template-parameter of type reference to
2974 // object, no conversions apply. The type referred to by the
2975 // reference may be more cv-qualified than the (otherwise
2976 // identical) type of the template-argument. The
2977 // template-parameter is bound directly to the
2978 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00002979 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002980 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002981
Douglas Gregor064fdb22010-04-14 23:11:21 +00002982 if (Arg->getType() == Context.OverloadTy) {
2983 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2984 ParamRefType->getPointeeType(),
2985 true,
2986 FoundResult)) {
2987 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2988 return true;
2989
2990 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2991 ArgType = Arg->getType();
2992 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00002993 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002994 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002995
Douglas Gregorb242683d2010-04-01 18:32:35 +00002996 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2997 ParamType,
2998 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002999 }
Douglas Gregor0e558532009-02-11 16:16:59 +00003000
3001 // -- For a non-type template-parameter of type pointer to data
3002 // member, qualification conversions (4.4) are applied.
3003 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3004
Douglas Gregor1515f762009-02-11 18:22:40 +00003005 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00003006 // Types match exactly: nothing more to do here.
3007 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCalle3027922010-08-25 11:45:40 +00003008 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor0e558532009-02-11 16:16:59 +00003009 } else {
3010 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003011 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00003012 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003013 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00003014 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003015 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00003016 }
3017
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00003018 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00003019}
3020
3021/// \brief Check a template argument against its corresponding
3022/// template template parameter.
3023///
3024/// This routine implements the semantics of C++ [temp.arg.template].
3025/// It returns true if an error occurred, and false otherwise.
3026bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003027 const TemplateArgumentLoc &Arg) {
3028 TemplateName Name = Arg.getArgument().getAsTemplate();
3029 TemplateDecl *Template = Name.getAsTemplateDecl();
3030 if (!Template) {
3031 // Any dependent template name is fine.
3032 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3033 return false;
3034 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003035
3036 // C++ [temp.arg.template]p1:
3037 // A template-argument for a template template-parameter shall be
3038 // the name of a class template, expressed as id-expression. Only
3039 // primary class templates are considered when matching the
3040 // template template argument with the corresponding parameter;
3041 // partial specializations are not considered even if their
3042 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003043 //
3044 // Note that we also allow template template parameters here, which
3045 // will happen when we are dealing with, e.g., class template
3046 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003047 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003048 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003049 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003050 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003051 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003052 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003053 << Template;
3054 }
3055
3056 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3057 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003058 true,
3059 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003060 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003061}
3062
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003063/// \brief Given a non-type template argument that refers to a
3064/// declaration and the type of its corresponding non-type template
3065/// parameter, produce an expression that properly refers to that
3066/// declaration.
John McCalldadc5752010-08-24 06:29:42 +00003067ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003068Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3069 QualType ParamType,
3070 SourceLocation Loc) {
3071 assert(Arg.getKind() == TemplateArgument::Declaration &&
3072 "Only declaration template arguments permitted here");
3073 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3074
3075 if (VD->getDeclContext()->isRecord() &&
3076 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3077 // If the value is a class member, we might have a pointer-to-member.
3078 // Determine whether the non-type template template parameter is of
3079 // pointer-to-member type. If so, we need to build an appropriate
3080 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3081 // would refer to the member itself.
3082 if (ParamType->isMemberPointerType()) {
3083 QualType ClassType
3084 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3085 NestedNameSpecifier *Qualifier
John McCallb268a282010-08-23 23:25:46 +00003086 = NestedNameSpecifier::Create(Context, 0, false,
3087 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003088 CXXScopeSpec SS;
3089 SS.setScopeRep(Qualifier);
John McCalldadc5752010-08-24 06:29:42 +00003090 ExprResult RefExpr = BuildDeclRefExpr(VD,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003091 VD->getType().getNonReferenceType(),
3092 Loc,
3093 &SS);
3094 if (RefExpr.isInvalid())
3095 return ExprError();
3096
John McCalle3027922010-08-25 11:45:40 +00003097 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003098
3099 // We might need to perform a trailing qualification conversion, since
3100 // the element type on the parameter could be more qualified than the
3101 // element type in the expression we constructed.
3102 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3103 ParamType.getUnqualifiedType())) {
3104 Expr *RefE = RefExpr.takeAs<Expr>();
John McCalle3027922010-08-25 11:45:40 +00003105 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003106 RefExpr = Owned(RefE);
3107 }
3108
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003109 assert(!RefExpr.isInvalid() &&
3110 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003111 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003112 return move(RefExpr);
3113 }
3114 }
3115
3116 QualType T = VD->getType().getNonReferenceType();
3117 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003118 // When the non-type template parameter is a pointer, take the
3119 // address of the declaration.
John McCalldadc5752010-08-24 06:29:42 +00003120 ExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003121 if (RefExpr.isInvalid())
3122 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003123
3124 if (T->isFunctionType() || T->isArrayType()) {
3125 // Decay functions and arrays.
3126 Expr *RefE = (Expr *)RefExpr.get();
3127 DefaultFunctionArrayConversion(RefE);
3128 if (RefE != RefExpr.get()) {
3129 RefExpr.release();
3130 RefExpr = Owned(RefE);
3131 }
3132
3133 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003134 }
3135
Douglas Gregorb242683d2010-04-01 18:32:35 +00003136 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00003137 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003138 }
3139
3140 // If the non-type template parameter has reference type, qualify the
3141 // resulting declaration reference with the extra qualifiers on the
3142 // type that the reference refers to.
3143 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3144 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3145
3146 return BuildDeclRefExpr(VD, T, Loc);
3147}
3148
3149/// \brief Construct a new expression that refers to the given
3150/// integral template argument with the given source-location
3151/// information.
3152///
3153/// This routine takes care of the mapping from an integral template
3154/// argument (which may have any integral type) to the appropriate
3155/// literal value.
John McCalldadc5752010-08-24 06:29:42 +00003156ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003157Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3158 SourceLocation Loc) {
3159 assert(Arg.getKind() == TemplateArgument::Integral &&
3160 "Operation is only value for integral template arguments");
3161 QualType T = Arg.getIntegralType();
3162 if (T->isCharType() || T->isWideCharType())
3163 return Owned(new (Context) CharacterLiteral(
3164 Arg.getAsIntegral()->getZExtValue(),
3165 T->isWideCharType(),
3166 T,
3167 Loc));
3168 if (T->isBooleanType())
3169 return Owned(new (Context) CXXBoolLiteralExpr(
3170 Arg.getAsIntegral()->getBoolValue(),
3171 T,
3172 Loc));
3173
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003174 return Owned(IntegerLiteral::Create(Context, *Arg.getAsIntegral(), T, Loc));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003175}
3176
3177
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003178/// \brief Determine whether the given template parameter lists are
3179/// equivalent.
3180///
Mike Stump11289f42009-09-09 15:08:12 +00003181/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003182/// source code as part of a new template declaration.
3183///
3184/// \param Old The old template parameter list, typically found via
3185/// name lookup of the template declared with this template parameter
3186/// list.
3187///
3188/// \param Complain If true, this routine will produce a diagnostic if
3189/// the template parameter lists are not equivalent.
3190///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003191/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003192///
3193/// \param TemplateArgLoc If this source location is valid, then we
3194/// are actually checking the template parameter list of a template
3195/// argument (New) against the template parameter list of its
3196/// corresponding template template parameter (Old). We produce
3197/// slightly different diagnostics in this scenario.
3198///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003199/// \returns True if the template parameter lists are equal, false
3200/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003201bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003202Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3203 TemplateParameterList *Old,
3204 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003205 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003206 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003207 if (Old->size() != New->size()) {
3208 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003209 unsigned NextDiag = diag::err_template_param_list_different_arity;
3210 if (TemplateArgLoc.isValid()) {
3211 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3212 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003213 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003214 Diag(New->getTemplateLoc(), NextDiag)
3215 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003216 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003217 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003218 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003219 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003220 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3221 }
3222
3223 return false;
3224 }
3225
3226 for (TemplateParameterList::iterator OldParm = Old->begin(),
3227 OldParmEnd = Old->end(), NewParm = New->begin();
3228 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3229 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003230 if (Complain) {
3231 unsigned NextDiag = diag::err_template_param_different_kind;
3232 if (TemplateArgLoc.isValid()) {
3233 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3234 NextDiag = diag::note_template_param_different_kind;
3235 }
3236 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003237 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003238 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003239 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003240 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003241 return false;
3242 }
3243
Douglas Gregor2e87ca22010-06-04 08:34:32 +00003244 if (TemplateTypeParmDecl *OldTTP
3245 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3246 // Template type parameters are equivalent if either both are template
3247 // type parameter packs or neither are (since we know we're at the same
3248 // index).
3249 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3250 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3251 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3252 // allow one to match a template parameter pack in the template
3253 // parameter list of a template template parameter to one or more
3254 // template parameters in the template parameter list of the
3255 // corresponding template template argument.
3256 if (Complain) {
3257 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3258 if (TemplateArgLoc.isValid()) {
3259 Diag(TemplateArgLoc,
3260 diag::err_template_arg_template_params_mismatch);
3261 NextDiag = diag::note_template_parameter_pack_non_pack;
3262 }
3263 Diag(NewTTP->getLocation(), NextDiag)
3264 << 0 << NewTTP->isParameterPack();
3265 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3266 << 0 << OldTTP->isParameterPack();
3267 }
3268 return false;
3269 }
Mike Stump11289f42009-09-09 15:08:12 +00003270 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003271 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3272 // The types of non-type template parameters must agree.
3273 NonTypeTemplateParmDecl *NewNTTP
3274 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003275
3276 // If we are matching a template template argument to a template
3277 // template parameter and one of the non-type template parameter types
3278 // is dependent, then we must wait until template instantiation time
3279 // to actually compare the arguments.
3280 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3281 (OldNTTP->getType()->isDependentType() ||
3282 NewNTTP->getType()->isDependentType()))
3283 continue;
3284
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003285 if (Context.getCanonicalType(OldNTTP->getType()) !=
3286 Context.getCanonicalType(NewNTTP->getType())) {
3287 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003288 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3289 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003290 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003291 diag::err_template_arg_template_params_mismatch);
3292 NextDiag = diag::note_template_nontype_parm_different_type;
3293 }
3294 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003295 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003296 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003297 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003298 diag::note_template_nontype_parm_prev_declaration)
3299 << OldNTTP->getType();
3300 }
3301 return false;
3302 }
3303 } else {
3304 // The template parameter lists of template template
3305 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003306 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003307 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003308 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003309 = cast<TemplateTemplateParmDecl>(*OldParm);
3310 TemplateTemplateParmDecl *NewTTP
3311 = cast<TemplateTemplateParmDecl>(*NewParm);
3312 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3313 OldTTP->getTemplateParameters(),
3314 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003315 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003316 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003317 return false;
3318 }
3319 }
3320
3321 return true;
3322}
3323
3324/// \brief Check whether a template can be declared within this scope.
3325///
3326/// If the template declaration is valid in this scope, returns
3327/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003328bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003329Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003330 // Find the nearest enclosing declaration scope.
3331 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3332 (S->getFlags() & Scope::TemplateParamScope) != 0)
3333 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003334
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003335 // C++ [temp]p2:
3336 // A template-declaration can appear only as a namespace scope or
3337 // class scope declaration.
3338 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003339 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3340 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003341 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003342 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003343
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003344 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003345 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003346
3347 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3348 return false;
3349
Mike Stump11289f42009-09-09 15:08:12 +00003350 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003351 diag::err_template_outside_namespace_or_class_scope)
3352 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003353}
Douglas Gregor67a65642009-02-17 23:15:12 +00003354
Douglas Gregor54888652009-10-07 00:13:32 +00003355/// \brief Determine what kind of template specialization the given declaration
3356/// is.
3357static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3358 if (!D)
3359 return TSK_Undeclared;
3360
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003361 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3362 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003363 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3364 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003365 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3366 return Var->getTemplateSpecializationKind();
3367
Douglas Gregor54888652009-10-07 00:13:32 +00003368 return TSK_Undeclared;
3369}
3370
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003371/// \brief Check whether a specialization is well-formed in the current
3372/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003373///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003374/// This routine determines whether a template specialization can be declared
3375/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003376///
3377/// \param S the semantic analysis object for which this check is being
3378/// performed.
3379///
3380/// \param Specialized the entity being specialized or instantiated, which
3381/// may be a kind of template (class template, function template, etc.) or
3382/// a member of a class template (member function, static data member,
3383/// member class).
3384///
3385/// \param PrevDecl the previous declaration of this entity, if any.
3386///
3387/// \param Loc the location of the explicit specialization or instantiation of
3388/// this entity.
3389///
3390/// \param IsPartialSpecialization whether this is a partial specialization of
3391/// a class template.
3392///
Douglas Gregor54888652009-10-07 00:13:32 +00003393/// \returns true if there was an error that we cannot recover from, false
3394/// otherwise.
3395static bool CheckTemplateSpecializationScope(Sema &S,
3396 NamedDecl *Specialized,
3397 NamedDecl *PrevDecl,
3398 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003399 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003400 // Keep these "kind" numbers in sync with the %select statements in the
3401 // various diagnostics emitted by this routine.
3402 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003403 bool isTemplateSpecialization = false;
3404 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003405 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003406 isTemplateSpecialization = true;
3407 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003408 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003409 isTemplateSpecialization = true;
3410 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003411 EntityKind = 3;
3412 else if (isa<VarDecl>(Specialized))
3413 EntityKind = 4;
3414 else if (isa<RecordDecl>(Specialized))
3415 EntityKind = 5;
3416 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003417 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3418 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003419 return true;
3420 }
3421
Douglas Gregorf47b9112009-02-25 22:02:03 +00003422 // C++ [temp.expl.spec]p2:
3423 // An explicit specialization shall be declared in the namespace
3424 // of which the template is a member, or, for member templates, in
3425 // the namespace of which the enclosing class or enclosing class
3426 // template is a member. An explicit specialization of a member
3427 // function, member class or static data member of a class
3428 // template shall be declared in the namespace of which the class
3429 // template is a member. Such a declaration may also be a
3430 // definition. If the declaration is not a definition, the
3431 // specialization may be defined later in the name- space in which
3432 // the explicit specialization was declared, or in a namespace
3433 // that encloses the one in which the explicit specialization was
3434 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00003435 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00003436 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003437 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003438 return true;
3439 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003440
Douglas Gregor40fb7442009-10-07 17:30:37 +00003441 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3442 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003443 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003444 return true;
3445 }
3446
Douglas Gregore4b05162009-10-07 17:21:34 +00003447 // C++ [temp.class.spec]p6:
3448 // A class template partial specialization may be declared or redeclared
3449 // in any namespace scope in which its definition may be defined (14.5.1
3450 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003451 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003452 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003453 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003454 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003455 if ((!PrevDecl ||
3456 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3457 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregorb1aab432010-09-12 05:08:28 +00003458 // C++ [temp.exp.spec]p2:
3459 // An explicit specialization shall be declared in the namespace of which
3460 // the template is a member, or, for member templates, in the namespace
3461 // of which the enclosing class or enclosing class template is a member.
3462 // An explicit specialization of a member function, member class or
3463 // static data member of a class template shall be declared in the
3464 // namespace of which the class template is a member.
3465 //
3466 // C++0x [temp.expl.spec]p2:
3467 // An explicit specialization shall be declared in a namespace enclosing
3468 // the specialized template.
3469 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
3470 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
Douglas Gregor8ce63152010-09-12 05:24:55 +00003471 bool IsCPlusPlus0xExtension
3472 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003473 if (isa<TranslationUnitDecl>(SpecializedContext))
Douglas Gregor8ce63152010-09-12 05:24:55 +00003474 S.Diag(Loc, IsCPlusPlus0xExtension
3475 ? diag::ext_template_spec_decl_out_of_scope_global
3476 : diag::err_template_spec_decl_out_of_scope_global)
3477 << EntityKind << Specialized;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003478 else if (isa<NamespaceDecl>(SpecializedContext))
Douglas Gregor8ce63152010-09-12 05:24:55 +00003479 S.Diag(Loc, IsCPlusPlus0xExtension
3480 ? diag::ext_template_spec_decl_out_of_scope
3481 : diag::err_template_spec_decl_out_of_scope)
3482 << EntityKind << Specialized
3483 << cast<NamedDecl>(SpecializedContext);
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003484
3485 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3486 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003487 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003488 }
Douglas Gregor54888652009-10-07 00:13:32 +00003489
3490 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003491 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003492 // Note that HandleDeclarator() performs this check for explicit
3493 // specializations of function templates, static data members, and member
3494 // functions, so we skip the check here for those kinds of entities.
3495 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003496 // Should we refactor that check, so that it occurs later?
3497 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003498 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3499 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003500 if (isa<TranslationUnitDecl>(SpecializedContext))
3501 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3502 << EntityKind << Specialized;
3503 else if (isa<NamespaceDecl>(SpecializedContext))
3504 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3505 << EntityKind << Specialized
3506 << cast<NamedDecl>(SpecializedContext);
3507
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003508 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003509 }
Douglas Gregor54888652009-10-07 00:13:32 +00003510
3511 // FIXME: check for specialization-after-instantiation errors and such.
3512
Douglas Gregorf47b9112009-02-25 22:02:03 +00003513 return false;
3514}
Douglas Gregor54888652009-10-07 00:13:32 +00003515
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003516/// \brief Check the non-type template arguments of a class template
3517/// partial specialization according to C++ [temp.class.spec]p9.
3518///
Douglas Gregor09a30232009-06-12 22:08:06 +00003519/// \param TemplateParams the template parameters of the primary class
3520/// template.
3521///
3522/// \param TemplateArg the template arguments of the class template
3523/// partial specialization.
3524///
3525/// \param MirrorsPrimaryTemplate will be set true if the class
3526/// template partial specialization arguments are identical to the
3527/// implicit template arguments of the primary template. This is not
3528/// necessarily an error (C++0x), and it is left to the caller to diagnose
3529/// this condition when it is an error.
3530///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003531/// \returns true if there was an error, false otherwise.
3532bool Sema::CheckClassTemplatePartialSpecializationArgs(
3533 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003534 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003535 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003536 // FIXME: the interface to this function will have to change to
3537 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003538 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003539
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003540 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003541
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003542 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003543 // Determine whether the template argument list of the partial
3544 // specialization is identical to the implicit argument list of
3545 // the primary template. The caller may need to diagnostic this as
3546 // an error per C++ [temp.class.spec]p9b3.
3547 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003548 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003549 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3550 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003551 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003552 MirrorsPrimaryTemplate = false;
3553 } else if (TemplateTemplateParmDecl *TTP
3554 = dyn_cast<TemplateTemplateParmDecl>(
3555 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003556 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003557 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003558 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003559 if (!ArgDecl ||
3560 ArgDecl->getIndex() != TTP->getIndex() ||
3561 ArgDecl->getDepth() != TTP->getDepth())
3562 MirrorsPrimaryTemplate = false;
3563 }
3564 }
3565
Mike Stump11289f42009-09-09 15:08:12 +00003566 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003567 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003568 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003569 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003570 }
3571
Anders Carlsson40c1d492009-06-13 18:20:51 +00003572 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003573 if (!ArgExpr) {
3574 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003575 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003576 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003577
3578 // C++ [temp.class.spec]p8:
3579 // A non-type argument is non-specialized if it is the name of a
3580 // non-type parameter. All other non-type arguments are
3581 // specialized.
3582 //
3583 // Below, we check the two conditions that only apply to
3584 // specialized non-type arguments, so skip any non-specialized
3585 // arguments.
3586 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003587 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003588 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003589 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003590 (Param->getIndex() != NTTP->getIndex() ||
3591 Param->getDepth() != NTTP->getDepth()))
3592 MirrorsPrimaryTemplate = false;
3593
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003594 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003595 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003596
3597 // C++ [temp.class.spec]p9:
3598 // Within the argument list of a class template partial
3599 // specialization, the following restrictions apply:
3600 // -- A partially specialized non-type argument expression
3601 // shall not involve a template parameter of the partial
3602 // specialization except when the argument expression is a
3603 // simple identifier.
3604 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003605 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003606 diag::err_dependent_non_type_arg_in_partial_spec)
3607 << ArgExpr->getSourceRange();
3608 return true;
3609 }
3610
3611 // -- The type of a template parameter corresponding to a
3612 // specialized non-type argument shall not be dependent on a
3613 // parameter of the specialization.
3614 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003615 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003616 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3617 << Param->getType()
3618 << ArgExpr->getSourceRange();
3619 Diag(Param->getLocation(), diag::note_template_param_here);
3620 return true;
3621 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003622
3623 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003624 }
3625
3626 return false;
3627}
3628
Douglas Gregorc854c662010-02-26 06:03:23 +00003629/// \brief Retrieve the previous declaration of the given declaration.
3630static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3631 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3632 return VD->getPreviousDeclaration();
3633 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3634 return FD->getPreviousDeclaration();
3635 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3636 return TD->getPreviousDeclaration();
3637 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3638 return TD->getPreviousDeclaration();
3639 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3640 return FTD->getPreviousDeclaration();
3641 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3642 return CTD->getPreviousDeclaration();
3643 return 0;
3644}
3645
John McCall48871652010-08-21 09:40:31 +00003646DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003647Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3648 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003649 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003650 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003651 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003652 SourceLocation TemplateNameLoc,
3653 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003654 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003655 SourceLocation RAngleLoc,
3656 AttributeList *Attr,
3657 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003658 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003659
Douglas Gregor67a65642009-02-17 23:15:12 +00003660 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003661 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003662 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003663 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3664
3665 if (!ClassTemplate) {
3666 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3667 << (Name.getAsTemplateDecl() &&
3668 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3669 return true;
3670 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003671
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003672 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003673 bool isPartialSpecialization = false;
3674
Douglas Gregorf47b9112009-02-25 22:02:03 +00003675 // Check the validity of the template headers that introduce this
3676 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003677 // FIXME: We probably shouldn't complain about these headers for
3678 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003679 bool Invalid = false;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003680 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003681 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3682 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003683 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003684 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003685 isExplicitSpecialization,
3686 Invalid);
3687 if (Invalid)
3688 return true;
3689
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003690 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3691 if (TemplateParams)
3692 --NumMatchedTemplateParamLists;
3693
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003694 if (TemplateParams && TemplateParams->size() > 0) {
3695 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003696
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003697 // C++ [temp.class.spec]p10:
3698 // The template parameter list of a specialization shall not
3699 // contain default template argument values.
3700 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3701 Decl *Param = TemplateParams->getParam(I);
3702 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3703 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003704 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003705 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003706 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003707 }
3708 } else if (NonTypeTemplateParmDecl *NTTP
3709 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3710 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003711 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003712 diag::err_default_arg_in_partial_spec)
3713 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003714 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003715 }
3716 } else {
3717 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003718 if (TTP->hasDefaultArgument()) {
3719 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003720 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003721 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003722 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00003723 }
3724 }
3725 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003726 } else if (TemplateParams) {
3727 if (TUK == TUK_Friend)
3728 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003729 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003730 SourceRange(TemplateParams->getTemplateLoc(),
3731 TemplateParams->getRAngleLoc()))
3732 << SourceRange(LAngleLoc, RAngleLoc);
3733 else
3734 isExplicitSpecialization = true;
3735 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003736 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003737 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003738 isExplicitSpecialization = true;
3739 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003740
Douglas Gregor67a65642009-02-17 23:15:12 +00003741 // Check that the specialization uses the same tag kind as the
3742 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003743 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3744 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00003745 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003746 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003747 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003748 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003749 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003750 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003751 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003752 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003753 diag::note_previous_use);
3754 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3755 }
3756
Douglas Gregorc40290e2009-03-09 23:48:35 +00003757 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003758 TemplateArgumentListInfo TemplateArgs;
3759 TemplateArgs.setLAngleLoc(LAngleLoc);
3760 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003761 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003762
Douglas Gregor67a65642009-02-17 23:15:12 +00003763 // Check that the template argument list is well-formed for this
3764 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003765 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3766 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003767 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3768 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003769 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003770
Mike Stump11289f42009-09-09 15:08:12 +00003771 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003772 ClassTemplate->getTemplateParameters()->size()) &&
3773 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003774
Douglas Gregor2373c592009-05-31 09:31:02 +00003775 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003776 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00003777 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003778 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003779 if (CheckClassTemplatePartialSpecializationArgs(
3780 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003781 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003782 return true;
3783
Douglas Gregor09a30232009-06-12 22:08:06 +00003784 if (MirrorsPrimaryTemplate) {
3785 // C++ [temp.class.spec]p9b3:
3786 //
Mike Stump11289f42009-09-09 15:08:12 +00003787 // -- The argument list of the specialization shall not be identical
3788 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003789 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003790 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003791 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003792 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003793 ClassTemplate->getIdentifier(),
3794 TemplateNameLoc,
3795 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003796 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003797 AS_none);
3798 }
3799
Douglas Gregor2208a292009-09-26 20:57:03 +00003800 // FIXME: Diagnose friend partial specializations
3801
Douglas Gregor92354b62010-02-09 00:37:32 +00003802 if (!Name.isDependent() &&
3803 !TemplateSpecializationType::anyDependentTemplateArguments(
3804 TemplateArgs.getArgumentArray(),
3805 TemplateArgs.size())) {
3806 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3807 << ClassTemplate->getDeclName();
3808 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00003809 }
3810 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003811
Douglas Gregor67a65642009-02-17 23:15:12 +00003812 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003813 ClassTemplateSpecializationDecl *PrevDecl = 0;
3814
3815 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003816 // FIXME: Template parameter list matters, too
Douglas Gregor2373c592009-05-31 09:31:02 +00003817 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003818 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
3819 Converted.flatSize(),
3820 InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00003821 else
3822 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003823 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
3824 Converted.flatSize(), InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003825
3826 ClassTemplateSpecializationDecl *Specialization = 0;
3827
Douglas Gregorf47b9112009-02-25 22:02:03 +00003828 // Check whether we can declare a class template specialization in
3829 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003830 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003831 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003832 TemplateNameLoc,
3833 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003834 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003835
Douglas Gregor15301382009-07-30 17:40:51 +00003836 // The canonical type
3837 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003838 if (PrevDecl &&
3839 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003840 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003841 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003842 // arguments was referenced but not declared, or we're only
3843 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003844 // declaration node as our own, updating its source location to
3845 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003846 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003847 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003848 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003849 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003850 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003851 // Build the canonical type that describes the converted template
3852 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003853 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3854 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003855 Converted.getFlatArguments(),
3856 Converted.flatSize());
3857
Douglas Gregor2373c592009-05-31 09:31:02 +00003858 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003859 ClassTemplatePartialSpecializationDecl *PrevPartial
3860 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00003861 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003862 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump11289f42009-09-09 15:08:12 +00003863 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00003864 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00003865 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003866 TemplateNameLoc,
3867 TemplateParams,
3868 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003869 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003870 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003871 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00003872 PrevPartial,
3873 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00003874 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00003875 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003876 Partial->setTemplateParameterListsInfo(Context,
3877 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003878 (TemplateParameterList**) TemplateParameterLists.release());
3879 }
Douglas Gregor2373c592009-05-31 09:31:02 +00003880
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003881 if (!PrevPartial)
3882 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00003883 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003884
Douglas Gregor21610382009-10-29 00:04:11 +00003885 // If we are providing an explicit specialization of a member class
3886 // template specialization, make a note of that.
3887 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3888 PrevPartial->setMemberSpecialization();
3889
Douglas Gregor91772d12009-06-13 00:26:55 +00003890 // Check that all of the template parameters of the class template
3891 // partial specialization are deducible from the template
3892 // arguments. If not, this class template partial specialization
3893 // will never be used.
3894 llvm::SmallVector<bool, 8> DeducibleParams;
3895 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003896 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003897 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003898 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003899 unsigned NumNonDeducible = 0;
3900 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3901 if (!DeducibleParams[I])
3902 ++NumNonDeducible;
3903
3904 if (NumNonDeducible) {
3905 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3906 << (NumNonDeducible > 1)
3907 << SourceRange(TemplateNameLoc, RAngleLoc);
3908 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3909 if (!DeducibleParams[I]) {
3910 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3911 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003912 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003913 diag::note_partial_spec_unused_parameter)
3914 << Param->getDeclName();
3915 else
Mike Stump11289f42009-09-09 15:08:12 +00003916 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003917 diag::note_partial_spec_unused_parameter)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003918 << "<anonymous>";
Douglas Gregor91772d12009-06-13 00:26:55 +00003919 }
3920 }
3921 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003922 } else {
3923 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003924 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003925 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00003926 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00003927 ClassTemplate->getDeclContext(),
3928 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003929 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003930 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003931 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00003932 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00003933 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003934 Specialization->setTemplateParameterListsInfo(Context,
3935 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003936 (TemplateParameterList**) TemplateParameterLists.release());
3937 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003938
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00003939 if (!PrevDecl)
3940 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00003941
3942 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003943 }
3944
Douglas Gregor06db9f52009-10-12 20:18:28 +00003945 // C++ [temp.expl.spec]p6:
3946 // If a template, a member template or the member of a class template is
3947 // explicitly specialized then that specialization shall be declared
3948 // before the first use of that specialization that would cause an implicit
3949 // instantiation to take place, in every translation unit in which such a
3950 // use occurs; no diagnostic is required.
3951 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003952 bool Okay = false;
3953 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3954 // Is there any previous explicit specialization declaration?
3955 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3956 Okay = true;
3957 break;
3958 }
3959 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003960
Douglas Gregorc854c662010-02-26 06:03:23 +00003961 if (!Okay) {
3962 SourceRange Range(TemplateNameLoc, RAngleLoc);
3963 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3964 << Context.getTypeDeclType(Specialization) << Range;
3965
3966 Diag(PrevDecl->getPointOfInstantiation(),
3967 diag::note_instantiation_required_here)
3968 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003969 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003970 return true;
3971 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003972 }
3973
Douglas Gregor2208a292009-09-26 20:57:03 +00003974 // If this is not a friend, note that this is an explicit specialization.
3975 if (TUK != TUK_Friend)
3976 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003977
3978 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003979 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003980 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003981 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003982 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003983 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003984 Diag(Def->getLocation(), diag::note_previous_definition);
3985 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003986 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003987 }
3988 }
3989
Douglas Gregord56a91e2009-02-26 22:19:44 +00003990 // Build the fully-sugared type for this class template
3991 // specialization as the user wrote in the specialization
3992 // itself. This means that we'll pretty-print the type retrieved
3993 // from the specialization's declaration the way that the user
3994 // actually wrote the specialization, rather than formatting the
3995 // name based on the "canonical" representation used to store the
3996 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003997 TypeSourceInfo *WrittenTy
3998 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3999 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004000 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00004001 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregord890b732010-07-06 18:33:12 +00004002 if (TemplateParams)
4003 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnara8075c852010-06-12 07:44:57 +00004004 }
Douglas Gregorc40290e2009-03-09 23:48:35 +00004005 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00004006
Douglas Gregor1e249f82009-02-25 22:18:32 +00004007 // C++ [temp.expl.spec]p9:
4008 // A template explicit specialization is in the scope of the
4009 // namespace in which the template was defined.
4010 //
4011 // We actually implement this paragraph where we set the semantic
4012 // context (in the creation of the ClassTemplateSpecializationDecl),
4013 // but we also maintain the lexical context where the actual
4014 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00004015 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00004016
Douglas Gregor67a65642009-02-17 23:15:12 +00004017 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00004018 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00004019 Specialization->startDefinition();
4020
Douglas Gregor2208a292009-09-26 20:57:03 +00004021 if (TUK == TUK_Friend) {
4022 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4023 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00004024 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00004025 /*FIXME:*/KWLoc);
4026 Friend->setAccess(AS_public);
4027 CurContext->addDecl(Friend);
4028 } else {
4029 // Add the specialization into its lexical context, so that it can
4030 // be seen when iterating through the list of declarations in that
4031 // context. However, specializations are not found by name lookup.
4032 CurContext->addDecl(Specialization);
4033 }
John McCall48871652010-08-21 09:40:31 +00004034 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00004035}
Douglas Gregor333489b2009-03-27 23:10:48 +00004036
John McCall48871652010-08-21 09:40:31 +00004037Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004038 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004039 Declarator &D) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004040 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4041}
4042
John McCall48871652010-08-21 09:40:31 +00004043Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004044 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004045 Declarator &D) {
Douglas Gregor17a7c122009-06-24 00:54:41 +00004046 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4047 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4048 "Not a function declarator!");
4049 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00004050
Douglas Gregor17a7c122009-06-24 00:54:41 +00004051 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004052 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004053 }
Mike Stump11289f42009-09-09 15:08:12 +00004054
Douglas Gregor17a7c122009-06-24 00:54:41 +00004055 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004056
John McCall48871652010-08-21 09:40:31 +00004057 Decl *DP = HandleDeclarator(ParentScope, D,
4058 move(TemplateParameterLists),
4059 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004060 if (FunctionTemplateDecl *FunctionTemplate
John McCall48871652010-08-21 09:40:31 +00004061 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump11289f42009-09-09 15:08:12 +00004062 return ActOnStartOfFunctionDef(FnBodyScope,
John McCall48871652010-08-21 09:40:31 +00004063 FunctionTemplate->getTemplatedDecl());
4064 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4065 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4066 return 0;
Douglas Gregor17a7c122009-06-24 00:54:41 +00004067}
4068
John McCall4f7ced62010-02-11 01:33:53 +00004069/// \brief Strips various properties off an implicit instantiation
4070/// that has just been explicitly specialized.
4071static void StripImplicitInstantiation(NamedDecl *D) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004072 D->dropAttrs();
John McCall4f7ced62010-02-11 01:33:53 +00004073
4074 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4075 FD->setInlineSpecified(false);
4076 }
4077}
4078
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004079/// \brief Diagnose cases where we have an explicit template specialization
4080/// before/after an explicit template instantiation, producing diagnostics
4081/// for those cases where they are required and determining whether the
4082/// new specialization/instantiation will have any effect.
4083///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004084/// \param NewLoc the location of the new explicit specialization or
4085/// instantiation.
4086///
4087/// \param NewTSK the kind of the new explicit specialization or instantiation.
4088///
4089/// \param PrevDecl the previous declaration of the entity.
4090///
4091/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4092///
4093/// \param PrevPointOfInstantiation if valid, indicates where the previus
4094/// declaration was instantiated (either implicitly or explicitly).
4095///
Abramo Bagnara8075c852010-06-12 07:44:57 +00004096/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004097/// specialization or instantiation has no effect and should be ignored.
4098///
4099/// \returns true if there was an error that should prevent the introduction of
4100/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004101bool
4102Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4103 TemplateSpecializationKind NewTSK,
4104 NamedDecl *PrevDecl,
4105 TemplateSpecializationKind PrevTSK,
4106 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004107 bool &HasNoEffect) {
4108 HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004109
4110 switch (NewTSK) {
4111 case TSK_Undeclared:
4112 case TSK_ImplicitInstantiation:
4113 assert(false && "Don't check implicit instantiations here");
4114 return false;
4115
4116 case TSK_ExplicitSpecialization:
4117 switch (PrevTSK) {
4118 case TSK_Undeclared:
4119 case TSK_ExplicitSpecialization:
4120 // Okay, we're just specializing something that is either already
4121 // explicitly specialized or has merely been mentioned without any
4122 // instantiation.
4123 return false;
4124
4125 case TSK_ImplicitInstantiation:
4126 if (PrevPointOfInstantiation.isInvalid()) {
4127 // The declaration itself has not actually been instantiated, so it is
4128 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004129 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004130 return false;
4131 }
4132 // Fall through
4133
4134 case TSK_ExplicitInstantiationDeclaration:
4135 case TSK_ExplicitInstantiationDefinition:
4136 assert((PrevTSK == TSK_ImplicitInstantiation ||
4137 PrevPointOfInstantiation.isValid()) &&
4138 "Explicit instantiation without point of instantiation?");
4139
4140 // C++ [temp.expl.spec]p6:
4141 // If a template, a member template or the member of a class template
4142 // is explicitly specialized then that specialization shall be declared
4143 // before the first use of that specialization that would cause an
4144 // implicit instantiation to take place, in every translation unit in
4145 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004146 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4147 // Is there any previous explicit specialization declaration?
4148 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4149 return false;
4150 }
4151
Douglas Gregor1d957a32009-10-27 18:42:08 +00004152 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004153 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004154 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004155 << (PrevTSK != TSK_ImplicitInstantiation);
4156
4157 return true;
4158 }
4159 break;
4160
4161 case TSK_ExplicitInstantiationDeclaration:
4162 switch (PrevTSK) {
4163 case TSK_ExplicitInstantiationDeclaration:
4164 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00004165 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004166 return false;
4167
4168 case TSK_Undeclared:
4169 case TSK_ImplicitInstantiation:
4170 // We're explicitly instantiating something that may have already been
4171 // implicitly instantiated; that's fine.
4172 return false;
4173
4174 case TSK_ExplicitSpecialization:
4175 // C++0x [temp.explicit]p4:
4176 // For a given set of template parameters, if an explicit instantiation
4177 // of a template appears after a declaration of an explicit
4178 // specialization for that template, the explicit instantiation has no
4179 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00004180 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004181 return false;
4182
4183 case TSK_ExplicitInstantiationDefinition:
4184 // C++0x [temp.explicit]p10:
4185 // If an entity is the subject of both an explicit instantiation
4186 // declaration and an explicit instantiation definition in the same
4187 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004188 Diag(NewLoc,
4189 diag::err_explicit_instantiation_declaration_after_definition);
4190 Diag(PrevPointOfInstantiation,
4191 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004192 assert(PrevPointOfInstantiation.isValid() &&
4193 "Explicit instantiation without point of instantiation?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00004194 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004195 return false;
4196 }
4197 break;
4198
4199 case TSK_ExplicitInstantiationDefinition:
4200 switch (PrevTSK) {
4201 case TSK_Undeclared:
4202 case TSK_ImplicitInstantiation:
4203 // We're explicitly instantiating something that may have already been
4204 // implicitly instantiated; that's fine.
4205 return false;
4206
4207 case TSK_ExplicitSpecialization:
4208 // C++ DR 259, C++0x [temp.explicit]p4:
4209 // For a given set of template parameters, if an explicit
4210 // instantiation of a template appears after a declaration of
4211 // an explicit specialization for that template, the explicit
4212 // instantiation has no effect.
4213 //
4214 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004215 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004216 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004217 if (!getLangOptions().CPlusPlus0x) {
4218 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004219 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004220 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004221 diag::note_previous_template_specialization);
4222 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004223 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004224 return false;
4225
4226 case TSK_ExplicitInstantiationDeclaration:
4227 // We're explicity instantiating a definition for something for which we
4228 // were previously asked to suppress instantiations. That's fine.
4229 return false;
4230
4231 case TSK_ExplicitInstantiationDefinition:
4232 // C++0x [temp.spec]p5:
4233 // For a given template and a given set of template-arguments,
4234 // - an explicit instantiation definition shall appear at most once
4235 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004236 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004237 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004238 Diag(PrevPointOfInstantiation,
4239 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004240 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004241 return false;
4242 }
4243 break;
4244 }
4245
4246 assert(false && "Missing specialization/instantiation case?");
4247
4248 return false;
4249}
4250
John McCallb9c78482010-04-08 09:05:18 +00004251/// \brief Perform semantic analysis for the given dependent function
4252/// template specialization. The only possible way to get a dependent
4253/// function template specialization is with a friend declaration,
4254/// like so:
4255///
4256/// template <class T> void foo(T);
4257/// template <class T> class A {
4258/// friend void foo<>(T);
4259/// };
4260///
4261/// There really isn't any useful analysis we can do here, so we
4262/// just store the information.
4263bool
4264Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4265 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4266 LookupResult &Previous) {
4267 // Remove anything from Previous that isn't a function template in
4268 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00004269 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00004270 LookupResult::Filter F = Previous.makeFilter();
4271 while (F.hasNext()) {
4272 NamedDecl *D = F.next()->getUnderlyingDecl();
4273 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00004274 !FDLookupContext->InEnclosingNamespaceSetOf(
4275 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00004276 F.erase();
4277 }
4278 F.done();
4279
4280 // Should this be diagnosed here?
4281 if (Previous.empty()) return true;
4282
4283 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4284 ExplicitTemplateArgs);
4285 return false;
4286}
4287
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004288/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004289/// specialization.
4290///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004291/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004292/// explicit function template specialization. On successful completion,
4293/// the function declaration \p FD will become a function template
4294/// specialization.
4295///
4296/// \param FD the function declaration, which will be updated to become a
4297/// function template specialization.
4298///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004299/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4300/// if any. Note that this may be valid info even when 0 arguments are
4301/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4302/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004303///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004304/// \param PrevDecl the set of declarations that may be specialized by
4305/// this function specialization.
4306bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004307Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004308 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004309 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004310 // The set of function template specializations that could match this
4311 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004312 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004313
Sebastian Redl50c68252010-08-31 00:36:30 +00004314 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00004315 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4316 I != E; ++I) {
4317 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4318 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004319 // Only consider templates found within the same semantic lookup scope as
4320 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00004321 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4322 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004323 continue;
4324
4325 // C++ [temp.expl.spec]p11:
4326 // A trailing template-argument can be left unspecified in the
4327 // template-id naming an explicit function template specialization
4328 // provided it can be deduced from the function argument type.
4329 // Perform template argument deduction to determine whether we may be
4330 // specializing this template.
4331 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004332 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004333 FunctionDecl *Specialization = 0;
4334 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004335 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004336 FD->getType(),
4337 Specialization,
4338 Info)) {
4339 // FIXME: Template argument deduction failed; record why it failed, so
4340 // that we can provide nifty diagnostics.
4341 (void)TDK;
4342 continue;
4343 }
4344
4345 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004346 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004347 }
4348 }
4349
Douglas Gregor5de279c2009-09-26 03:41:46 +00004350 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004351 UnresolvedSetIterator Result
4352 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4353 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004354 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004355 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004356 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004357 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004358 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004359 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004360 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004361
4362 // Ignore access information; it doesn't figure into redeclaration checking.
4363 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004364 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004365
4366 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004367 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004368
4369 // If this is a friend declaration, then we're not really declaring
4370 // an explicit specialization.
4371 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004372
Douglas Gregor54888652009-10-07 00:13:32 +00004373 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004374 if (!isFriend &&
4375 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004376 Specialization->getPrimaryTemplate(),
4377 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004378 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004379 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004380
4381 // C++ [temp.expl.spec]p6:
4382 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004383 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004384 // before the first use of that specialization that would cause an implicit
4385 // instantiation to take place, in every translation unit in which such a
4386 // use occurs; no diagnostic is required.
4387 FunctionTemplateSpecializationInfo *SpecInfo
4388 = Specialization->getTemplateSpecializationInfo();
4389 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004390
Abramo Bagnara8075c852010-06-12 07:44:57 +00004391 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00004392 if (!isFriend &&
4393 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004394 TSK_ExplicitSpecialization,
4395 Specialization,
4396 SpecInfo->getTemplateSpecializationKind(),
4397 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004398 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004399 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004400
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004401 // Mark the prior declaration as an explicit specialization, so that later
4402 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004403 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00004404 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004405 MarkUnusedFileScopedDecl(Specialization);
4406 }
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004407
4408 // Turn the given function declaration into a function template
4409 // specialization, with the template arguments from the previous
4410 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004411 // Take copies of (semantic and syntactic) template argument lists.
4412 const TemplateArgumentList* TemplArgs = new (Context)
4413 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4414 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4415 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004416 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004417 TemplArgs, /*InsertPos=*/0,
4418 SpecInfo->getTemplateSpecializationKind(),
4419 TemplArgsAsWritten);
4420
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004421 // The "previous declaration" for this function template specialization is
4422 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004423 Previous.clear();
4424 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004425 return false;
4426}
4427
Douglas Gregor86d142a2009-10-08 07:24:58 +00004428/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004429/// specialization.
4430///
4431/// This routine performs all of the semantic analysis required for an
4432/// explicit member function specialization. On successful completion,
4433/// the function declaration \p FD will become a member function
4434/// specialization.
4435///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004436/// \param Member the member declaration, which will be updated to become a
4437/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004438///
John McCall1f82f242009-11-18 22:49:29 +00004439/// \param Previous the set of declarations, one of which may be specialized
4440/// by this function specialization; the set will be modified to contain the
4441/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004442bool
John McCall1f82f242009-11-18 22:49:29 +00004443Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004444 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004445
Douglas Gregor86d142a2009-10-08 07:24:58 +00004446 // Try to find the member we are instantiating.
4447 NamedDecl *Instantiation = 0;
4448 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004449 MemberSpecializationInfo *MSInfo = 0;
4450
John McCall1f82f242009-11-18 22:49:29 +00004451 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004452 // Nowhere to look anyway.
4453 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004454 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4455 I != E; ++I) {
4456 NamedDecl *D = (*I)->getUnderlyingDecl();
4457 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004458 if (Context.hasSameType(Function->getType(), Method->getType())) {
4459 Instantiation = Method;
4460 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004461 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004462 break;
4463 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004464 }
4465 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004466 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004467 VarDecl *PrevVar;
4468 if (Previous.isSingleResult() &&
4469 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004470 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004471 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004472 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004473 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004474 }
4475 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004476 CXXRecordDecl *PrevRecord;
4477 if (Previous.isSingleResult() &&
4478 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4479 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004480 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004481 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004482 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004483 }
4484
4485 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004486 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004487 // specializations are always out-of-line, the caller will complain about
4488 // this mismatch later.
4489 return false;
4490 }
John McCalle820e5e2010-04-13 20:37:33 +00004491
4492 // If this is a friend, just bail out here before we start turning
4493 // things into explicit specializations.
4494 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4495 // Preserve instantiation information.
4496 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4497 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4498 cast<CXXMethodDecl>(InstantiatedFrom),
4499 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4500 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4501 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4502 cast<CXXRecordDecl>(InstantiatedFrom),
4503 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4504 }
4505
4506 Previous.clear();
4507 Previous.addDecl(Instantiation);
4508 return false;
4509 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004510
Douglas Gregor86d142a2009-10-08 07:24:58 +00004511 // Make sure that this is a specialization of a member.
4512 if (!InstantiatedFrom) {
4513 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4514 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004515 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4516 return true;
4517 }
4518
Douglas Gregor06db9f52009-10-12 20:18:28 +00004519 // C++ [temp.expl.spec]p6:
4520 // If a template, a member template or the member of a class template is
4521 // explicitly specialized then that spe- cialization shall be declared
4522 // before the first use of that specialization that would cause an implicit
4523 // instantiation to take place, in every translation unit in which such a
4524 // use occurs; no diagnostic is required.
4525 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004526
Abramo Bagnara8075c852010-06-12 07:44:57 +00004527 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00004528 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4529 TSK_ExplicitSpecialization,
4530 Instantiation,
4531 MSInfo->getTemplateSpecializationKind(),
4532 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004533 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004534 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004535
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004536 // Check the scope of this explicit specialization.
4537 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004538 InstantiatedFrom,
4539 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004540 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004541 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004542
Douglas Gregor86d142a2009-10-08 07:24:58 +00004543 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004544 // the original declaration to note that it is an explicit specialization
4545 // (if it was previously an implicit instantiation). This latter step
4546 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004547 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004548 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4549 if (InstantiationFunction->getTemplateSpecializationKind() ==
4550 TSK_ImplicitInstantiation) {
4551 InstantiationFunction->setTemplateSpecializationKind(
4552 TSK_ExplicitSpecialization);
4553 InstantiationFunction->setLocation(Member->getLocation());
4554 }
4555
Douglas Gregor86d142a2009-10-08 07:24:58 +00004556 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4557 cast<CXXMethodDecl>(InstantiatedFrom),
4558 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004559 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004560 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004561 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4562 if (InstantiationVar->getTemplateSpecializationKind() ==
4563 TSK_ImplicitInstantiation) {
4564 InstantiationVar->setTemplateSpecializationKind(
4565 TSK_ExplicitSpecialization);
4566 InstantiationVar->setLocation(Member->getLocation());
4567 }
4568
Douglas Gregor86d142a2009-10-08 07:24:58 +00004569 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4570 cast<VarDecl>(InstantiatedFrom),
4571 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004572 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004573 } else {
4574 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004575 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4576 if (InstantiationClass->getTemplateSpecializationKind() ==
4577 TSK_ImplicitInstantiation) {
4578 InstantiationClass->setTemplateSpecializationKind(
4579 TSK_ExplicitSpecialization);
4580 InstantiationClass->setLocation(Member->getLocation());
4581 }
4582
Douglas Gregor86d142a2009-10-08 07:24:58 +00004583 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004584 cast<CXXRecordDecl>(InstantiatedFrom),
4585 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004586 }
4587
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004588 // Save the caller the trouble of having to figure out which declaration
4589 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004590 Previous.clear();
4591 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004592 return false;
4593}
4594
Douglas Gregore47f5a72009-10-14 23:41:34 +00004595/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004596///
4597/// \returns true if a serious error occurs, false otherwise.
4598static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00004599 SourceLocation InstLoc,
4600 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00004601 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
4602 DeclContext *CurContext = S.CurContext->getRedeclContext();
Douglas Gregore47f5a72009-10-14 23:41:34 +00004603
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004604 if (CurContext->isRecord()) {
4605 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4606 << D;
4607 return true;
4608 }
4609
Douglas Gregore47f5a72009-10-14 23:41:34 +00004610 // C++0x [temp.explicit]p2:
4611 // An explicit instantiation shall appear in an enclosing namespace of its
4612 // template.
4613 //
4614 // This is DR275, which we do not retroactively apply to C++98/03.
4615 if (S.getLangOptions().CPlusPlus0x &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004616 !CurContext->Encloses(OrigContext)) {
4617 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004618 S.Diag(InstLoc,
4619 S.getLangOptions().CPlusPlus0x?
4620 diag::err_explicit_instantiation_out_of_scope
4621 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004622 << D << NS;
4623 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004624 S.Diag(InstLoc,
4625 S.getLangOptions().CPlusPlus0x?
4626 diag::err_explicit_instantiation_must_be_global
4627 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004628 << D;
4629 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004630 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004631 }
Sebastian Redl50c68252010-08-31 00:36:30 +00004632
Douglas Gregore47f5a72009-10-14 23:41:34 +00004633 // C++0x [temp.explicit]p2:
4634 // If the name declared in the explicit instantiation is an unqualified
4635 // name, the explicit instantiation shall appear in the namespace where
4636 // its template is declared or, if that namespace is inline (7.3.1), any
4637 // namespace from its enclosing namespace set.
4638 if (WasQualifiedName)
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004639 return false;
Sebastian Redl50c68252010-08-31 00:36:30 +00004640
4641 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004642 return false;
Sebastian Redl50c68252010-08-31 00:36:30 +00004643
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004644 S.Diag(InstLoc,
4645 S.getLangOptions().CPlusPlus0x?
4646 diag::err_explicit_instantiation_unqualified_wrong_namespace
4647 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Sebastian Redl50c68252010-08-31 00:36:30 +00004648 << D << OrigContext;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004649 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004650 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004651}
4652
4653/// \brief Determine whether the given scope specifier has a template-id in it.
4654static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4655 if (!SS.isSet())
4656 return false;
4657
4658 // C++0x [temp.explicit]p2:
4659 // If the explicit instantiation is for a member function, a member class
4660 // or a static data member of a class template specialization, the name of
4661 // the class template specialization in the qualified-id for the member
4662 // name shall be a simple-template-id.
4663 //
4664 // C++98 has the same restriction, just worded differently.
4665 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4666 NNS; NNS = NNS->getPrefix())
4667 if (Type *T = NNS->getAsType())
4668 if (isa<TemplateSpecializationType>(T))
4669 return true;
4670
4671 return false;
4672}
4673
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004674// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00004675DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004676Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004677 SourceLocation ExternLoc,
4678 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004679 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004680 SourceLocation KWLoc,
4681 const CXXScopeSpec &SS,
4682 TemplateTy TemplateD,
4683 SourceLocation TemplateNameLoc,
4684 SourceLocation LAngleLoc,
4685 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004686 SourceLocation RAngleLoc,
4687 AttributeList *Attr) {
4688 // Find the class template we're specializing
4689 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004690 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004691 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4692
4693 // Check that the specialization uses the same tag kind as the
4694 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004695 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4696 assert(Kind != TTK_Enum &&
4697 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004698 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004699 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004700 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004701 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004702 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004703 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004704 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004705 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004706 diag::note_previous_use);
4707 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4708 }
4709
Douglas Gregore47f5a72009-10-14 23:41:34 +00004710 // C++0x [temp.explicit]p2:
4711 // There are two forms of explicit instantiation: an explicit instantiation
4712 // definition and an explicit instantiation declaration. An explicit
4713 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004714 TemplateSpecializationKind TSK
4715 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4716 : TSK_ExplicitInstantiationDeclaration;
4717
Douglas Gregora1f49972009-05-13 00:25:59 +00004718 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004719 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004720 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004721
4722 // Check that the template argument list is well-formed for this
4723 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004724 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4725 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004726 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4727 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004728 return true;
4729
Mike Stump11289f42009-09-09 15:08:12 +00004730 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004731 ClassTemplate->getTemplateParameters()->size()) &&
4732 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004733
Douglas Gregora1f49972009-05-13 00:25:59 +00004734 // Find the class template specialization declaration that
4735 // corresponds to these arguments.
Douglas Gregora1f49972009-05-13 00:25:59 +00004736 void *InsertPos = 0;
4737 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004738 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4739 Converted.flatSize(), InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004740
Abramo Bagnara8075c852010-06-12 07:44:57 +00004741 TemplateSpecializationKind PrevDecl_TSK
4742 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4743
Douglas Gregor54888652009-10-07 00:13:32 +00004744 // C++0x [temp.explicit]p2:
4745 // [...] An explicit instantiation shall appear in an enclosing
4746 // namespace of its template. [...]
4747 //
4748 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004749 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4750 SS.isSet()))
4751 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004752
Douglas Gregora1f49972009-05-13 00:25:59 +00004753 ClassTemplateSpecializationDecl *Specialization = 0;
4754
Douglas Gregor0681a352009-11-25 06:01:46 +00004755 bool ReusedDecl = false;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004756 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004757 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00004758 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004759 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004760 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004761 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00004762 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00004763
Abramo Bagnara8075c852010-06-12 07:44:57 +00004764 // Even though HasNoEffect == true means that this explicit instantiation
4765 // has no effect on semantics, we go on to put its syntax in the AST.
4766
4767 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4768 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004769 // Since the only prior class template specialization with these
4770 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00004771 // declaration node as our own, updating the source location
4772 // for the template name to reflect our new declaration.
4773 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004774 Specialization = PrevDecl;
4775 Specialization->setLocation(TemplateNameLoc);
4776 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004777 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004778 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004779 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004780
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004781 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004782 // Create a new class template specialization declaration node for
4783 // this explicit specialization.
4784 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004785 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00004786 ClassTemplate->getDeclContext(),
4787 TemplateNameLoc,
4788 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004789 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004790 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004791
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004792 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00004793 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004794 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004795 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004796 }
4797
4798 // Build the fully-sugared type for this explicit instantiation as
4799 // the user wrote in the explicit instantiation itself. This means
4800 // that we'll pretty-print the type retrieved from the
4801 // specialization's declaration the way that the user actually wrote
4802 // the explicit instantiation, rather than formatting the name based
4803 // on the "canonical" representation used to store the template
4804 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004805 TypeSourceInfo *WrittenTy
4806 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4807 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004808 Context.getTypeDeclType(Specialization));
4809 Specialization->setTypeAsWritten(WrittenTy);
4810 TemplateArgsIn.release();
4811
Abramo Bagnara8075c852010-06-12 07:44:57 +00004812 // Set source locations for keywords.
4813 Specialization->setExternLoc(ExternLoc);
4814 Specialization->setTemplateKeywordLoc(TemplateLoc);
4815
4816 // Add the explicit instantiation into its lexical context. However,
4817 // since explicit instantiations are never found by name lookup, we
4818 // just put it into the declaration context directly.
4819 Specialization->setLexicalDeclContext(CurContext);
4820 CurContext->addDecl(Specialization);
4821
4822 // Syntax is now OK, so return if it has no other effect on semantics.
4823 if (HasNoEffect) {
4824 // Set the template specialization kind.
4825 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00004826 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00004827 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004828
4829 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004830 // A definition of a class template or class member template
4831 // shall be in scope at the point of the explicit instantiation of
4832 // the class template or class member template.
4833 //
4834 // This check comes when we actually try to perform the
4835 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004836 ClassTemplateSpecializationDecl *Def
4837 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004838 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004839 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004840 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004841 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00004842 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004843 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
4844 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004845
Douglas Gregor1d957a32009-10-27 18:42:08 +00004846 // Instantiate the members of this class template specialization.
4847 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004848 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004849 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004850 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4851
4852 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4853 // TSK_ExplicitInstantiationDefinition
4854 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4855 TSK == TSK_ExplicitInstantiationDefinition)
4856 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004857
Douglas Gregor12e49d32009-10-15 22:53:21 +00004858 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004859 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004860
Abramo Bagnara8075c852010-06-12 07:44:57 +00004861 // Set the template specialization kind.
4862 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00004863 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00004864}
4865
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004866// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00004867DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004868Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004869 SourceLocation ExternLoc,
4870 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004871 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004872 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004873 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004874 IdentifierInfo *Name,
4875 SourceLocation NameLoc,
4876 AttributeList *Attr) {
4877
Douglas Gregord6ab8742009-05-28 23:31:59 +00004878 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004879 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00004880 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00004881 KWLoc, SS, Name, NameLoc, Attr, AS_none,
4882 MultiTemplateParamsArg(*this, 0, 0),
Douglas Gregor0bf31402010-10-08 23:50:27 +00004883 Owned, IsDependent, false,
4884 TypeResult());
John McCall7f41d982009-09-11 04:59:25 +00004885 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4886
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004887 if (!TagD)
4888 return true;
4889
John McCall48871652010-08-21 09:40:31 +00004890 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004891 if (Tag->isEnum()) {
4892 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4893 << Context.getTypeDeclType(Tag);
4894 return true;
4895 }
4896
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004897 if (Tag->isInvalidDecl())
4898 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004899
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004900 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4901 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4902 if (!Pattern) {
4903 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4904 << Context.getTypeDeclType(Record);
4905 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4906 return true;
4907 }
4908
Douglas Gregore47f5a72009-10-14 23:41:34 +00004909 // C++0x [temp.explicit]p2:
4910 // If the explicit instantiation is for a class or member class, the
4911 // elaborated-type-specifier in the declaration shall include a
4912 // simple-template-id.
4913 //
4914 // C++98 has the same restriction, just worded differently.
4915 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00004916 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004917 << Record << SS.getRange();
4918
4919 // C++0x [temp.explicit]p2:
4920 // There are two forms of explicit instantiation: an explicit instantiation
4921 // definition and an explicit instantiation declaration. An explicit
4922 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004923 TemplateSpecializationKind TSK
4924 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4925 : TSK_ExplicitInstantiationDeclaration;
4926
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004927 // C++0x [temp.explicit]p2:
4928 // [...] An explicit instantiation shall appear in an enclosing
4929 // namespace of its template. [...]
4930 //
4931 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004932 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004933
4934 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004935 CXXRecordDecl *PrevDecl
4936 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004937 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004938 PrevDecl = Record;
4939 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004940 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00004941 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004942 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004943 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004944 PrevDecl,
4945 MSInfo->getTemplateSpecializationKind(),
4946 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004947 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004948 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004949 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004950 return TagD;
4951 }
4952
Douglas Gregor12e49d32009-10-15 22:53:21 +00004953 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004954 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004955 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004956 // C++ [temp.explicit]p3:
4957 // A definition of a member class of a class template shall be in scope
4958 // at the point of an explicit instantiation of the member class.
4959 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004960 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004961 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004962 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4963 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004964 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4965 << Pattern;
4966 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004967 } else {
4968 if (InstantiateClass(NameLoc, Record, Def,
4969 getTemplateInstantiationArgs(Record),
4970 TSK))
4971 return true;
4972
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004973 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004974 if (!RecordDef)
4975 return true;
4976 }
4977 }
4978
4979 // Instantiate all of the members of the class.
4980 InstantiateClassMembers(NameLoc, RecordDef,
4981 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004982
Douglas Gregor88d292c2010-05-13 16:44:06 +00004983 if (TSK == TSK_ExplicitInstantiationDefinition)
4984 MarkVTableUsed(NameLoc, RecordDef, true);
4985
Mike Stump87c57ac2009-05-16 07:39:55 +00004986 // FIXME: We don't have any representation for explicit instantiations of
4987 // member classes. Such a representation is not needed for compilation, but it
4988 // should be available for clients that want to see all of the declarations in
4989 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004990 return TagD;
4991}
4992
John McCallfaf5fb42010-08-26 23:41:50 +00004993DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4994 SourceLocation ExternLoc,
4995 SourceLocation TemplateLoc,
4996 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004997 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004998 // TODO: check if/when DNInfo should replace Name.
4999 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5000 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00005001 if (!Name) {
5002 if (!D.isInvalidType())
5003 Diag(D.getDeclSpec().getSourceRange().getBegin(),
5004 diag::err_explicit_instantiation_requires_name)
5005 << D.getDeclSpec().getSourceRange()
5006 << D.getSourceRange();
5007
5008 return true;
5009 }
5010
5011 // The scope passed in may not be a decl scope. Zip up the scope tree until
5012 // we find one that is.
5013 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5014 (S->getFlags() & Scope::TemplateParamScope) != 0)
5015 S = S->getParent();
5016
5017 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00005018 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5019 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00005020 if (R.isNull())
5021 return true;
5022
5023 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5024 // Cannot explicitly instantiate a typedef.
5025 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5026 << Name;
5027 return true;
5028 }
5029
Douglas Gregor3c74d412009-10-14 20:14:33 +00005030 // C++0x [temp.explicit]p1:
5031 // [...] An explicit instantiation of a function template shall not use the
5032 // inline or constexpr specifiers.
5033 // Presumably, this also applies to member functions of class templates as
5034 // well.
5035 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5036 Diag(D.getDeclSpec().getInlineSpecLoc(),
5037 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00005038 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00005039
5040 // FIXME: check for constexpr specifier.
5041
Douglas Gregore47f5a72009-10-14 23:41:34 +00005042 // C++0x [temp.explicit]p2:
5043 // There are two forms of explicit instantiation: an explicit instantiation
5044 // definition and an explicit instantiation declaration. An explicit
5045 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00005046 TemplateSpecializationKind TSK
5047 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5048 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005049
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005050 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005051 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00005052
5053 if (!R->isFunctionType()) {
5054 // C++ [temp.explicit]p1:
5055 // A [...] static data member of a class template can be explicitly
5056 // instantiated from the member definition associated with its class
5057 // template.
John McCall27b18f82009-11-17 02:14:36 +00005058 if (Previous.isAmbiguous())
5059 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00005060
John McCall67c00872009-12-02 08:25:40 +00005061 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005062 if (!Prev || !Prev->isStaticDataMember()) {
5063 // We expect to see a data data member here.
5064 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5065 << Name;
5066 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5067 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005068 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005069 return true;
5070 }
5071
5072 if (!Prev->getInstantiatedFromStaticDataMember()) {
5073 // FIXME: Check for explicit specialization?
5074 Diag(D.getIdentifierLoc(),
5075 diag::err_explicit_instantiation_data_member_not_instantiated)
5076 << Prev;
5077 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5078 // FIXME: Can we provide a note showing where this was declared?
5079 return true;
5080 }
5081
Douglas Gregore47f5a72009-10-14 23:41:34 +00005082 // C++0x [temp.explicit]p2:
5083 // If the explicit instantiation is for a member function, a member class
5084 // or a static data member of a class template specialization, the name of
5085 // the class template specialization in the qualified-id for the member
5086 // name shall be a simple-template-id.
5087 //
5088 // C++98 has the same restriction, just worded differently.
5089 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5090 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005091 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005092 << Prev << D.getCXXScopeSpec().getRange();
5093
5094 // Check the scope of this explicit instantiation.
5095 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5096
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005097 // Verify that it is okay to explicitly instantiate here.
5098 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5099 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00005100 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005101 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005102 MSInfo->getTemplateSpecializationKind(),
5103 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005104 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005105 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005106 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005107 return (Decl*) 0;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005108
Douglas Gregor450f00842009-09-25 18:43:00 +00005109 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005110 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005111 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005112 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregor450f00842009-09-25 18:43:00 +00005113
5114 // FIXME: Create an ExplicitInstantiation node?
John McCall48871652010-08-21 09:40:31 +00005115 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005116 }
5117
Douglas Gregor0e876e02009-09-25 23:53:26 +00005118 // If the declarator is a template-id, translate the parser's template
5119 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005120 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005121 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005122 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5123 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005124 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5125 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005126 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5127 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005128 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005129 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005130 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005131 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005132 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005133
Douglas Gregor450f00842009-09-25 18:43:00 +00005134 // C++ [temp.explicit]p1:
5135 // A [...] function [...] can be explicitly instantiated from its template.
5136 // A member function [...] of a class template can be explicitly
5137 // instantiated from the member definition associated with its class
5138 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005139 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005140 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5141 P != PEnd; ++P) {
5142 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005143 if (!HasExplicitTemplateArgs) {
5144 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5145 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5146 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005147
John McCall58cc69d2010-01-27 01:50:18 +00005148 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005149 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5150 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005151 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005152 }
5153 }
5154
5155 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5156 if (!FunTmpl)
5157 continue;
5158
John McCallbc077cf2010-02-08 23:07:23 +00005159 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005160 FunctionDecl *Specialization = 0;
5161 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005162 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005163 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005164 R, Specialization, Info)) {
5165 // FIXME: Keep track of almost-matches?
5166 (void)TDK;
5167 continue;
5168 }
5169
John McCall58cc69d2010-01-27 01:50:18 +00005170 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005171 }
5172
5173 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005174 UnresolvedSetIterator Result
5175 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005176 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005177 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5178 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5179 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005180
John McCall58cc69d2010-01-27 01:50:18 +00005181 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005182 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005183
5184 // Ignore access control bits, we don't need them for redeclaration checking.
5185 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005186
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005187 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005188 Diag(D.getIdentifierLoc(),
5189 diag::err_explicit_instantiation_member_function_not_instantiated)
5190 << Specialization
5191 << (Specialization->getTemplateSpecializationKind() ==
5192 TSK_ExplicitSpecialization);
5193 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5194 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005195 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005196
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005197 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005198 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5199 PrevDecl = Specialization;
5200
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005201 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005202 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005203 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005204 PrevDecl,
5205 PrevDecl->getTemplateSpecializationKind(),
5206 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005207 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005208 return true;
5209
5210 // FIXME: We may still want to build some representation of this
5211 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00005212 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005213 return (Decl*) 0;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005214 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005215
5216 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005217
5218 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005219 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005220
Douglas Gregore47f5a72009-10-14 23:41:34 +00005221 // C++0x [temp.explicit]p2:
5222 // If the explicit instantiation is for a member function, a member class
5223 // or a static data member of a class template specialization, the name of
5224 // the class template specialization in the qualified-id for the member
5225 // name shall be a simple-template-id.
5226 //
5227 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005228 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005229 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005230 D.getCXXScopeSpec().isSet() &&
5231 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5232 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005233 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005234 << Specialization << D.getCXXScopeSpec().getRange();
5235
5236 CheckExplicitInstantiationScope(*this,
5237 FunTmpl? (NamedDecl *)FunTmpl
5238 : Specialization->getInstantiatedFromMemberFunction(),
5239 D.getIdentifierLoc(),
5240 D.getCXXScopeSpec().isSet());
5241
Douglas Gregor450f00842009-09-25 18:43:00 +00005242 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCall48871652010-08-21 09:40:31 +00005243 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005244}
5245
John McCallfaf5fb42010-08-26 23:41:50 +00005246TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005247Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5248 const CXXScopeSpec &SS, IdentifierInfo *Name,
5249 SourceLocation TagLoc, SourceLocation NameLoc) {
5250 // This has to hold, because SS is expected to be defined.
5251 assert(Name && "Expected a name in a dependent tag");
5252
5253 NestedNameSpecifier *NNS
5254 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5255 if (!NNS)
5256 return true;
5257
Abramo Bagnara6150c882010-05-11 21:36:43 +00005258 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005259
Douglas Gregorba41d012010-04-24 16:38:41 +00005260 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5261 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005262 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005263 return true;
5264 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005265
5266 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallba7bf592010-08-24 05:47:05 +00005267 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCall7f41d982009-09-11 04:59:25 +00005268}
5269
John McCallfaf5fb42010-08-26 23:41:50 +00005270TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005271Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5272 const CXXScopeSpec &SS, const IdentifierInfo &II,
5273 SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005274 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005275 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5276 if (!NNS)
5277 return true;
5278
Douglas Gregorf7d77712010-06-16 22:31:08 +00005279 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5280 !getLangOptions().CPlusPlus0x)
5281 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5282 << FixItHint::CreateRemoval(TypenameLoc);
5283
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005284 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005285 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005286 if (T.isNull())
5287 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005288
5289 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5290 if (isa<DependentNameType>(T)) {
5291 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005292 TL.setKeywordLoc(TypenameLoc);
5293 TL.setQualifierRange(SS.getRange());
5294 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005295 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005296 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005297 TL.setKeywordLoc(TypenameLoc);
5298 TL.setQualifierRange(SS.getRange());
5299 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005300 }
5301
John McCallba7bf592010-08-24 05:47:05 +00005302 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00005303}
5304
John McCallfaf5fb42010-08-26 23:41:50 +00005305TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005306Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5307 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallba7bf592010-08-24 05:47:05 +00005308 ParsedType Ty) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00005309 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5310 !getLangOptions().CPlusPlus0x)
5311 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5312 << FixItHint::CreateRemoval(TypenameLoc);
5313
John McCallf7bcc812010-05-28 23:32:21 +00005314 TypeSourceInfo *InnerTSI = 0;
5315 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCallf7bcc812010-05-28 23:32:21 +00005316
5317 assert(isa<TemplateSpecializationType>(T) &&
5318 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005319
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005320 if (computeDeclContext(SS, false)) {
5321 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005322 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005323 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005324
5325 // Push the inner type, preserving its source locations if possible.
5326 TypeLocBuilder Builder;
5327 if (InnerTSI)
5328 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5329 else
5330 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5331
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005332 /* Note: NNS already embedded in template specialization type T. */
5333 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCallf7bcc812010-05-28 23:32:21 +00005334 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5335 TL.setKeywordLoc(TypenameLoc);
5336 TL.setQualifierRange(SS.getRange());
5337
5338 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallba7bf592010-08-24 05:47:05 +00005339 return CreateParsedType(T, TSI);
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005340 }
Mike Stump11289f42009-09-09 15:08:12 +00005341
John McCallc392f372010-06-11 00:33:02 +00005342 // TODO: it's really silly that we make a template specialization
5343 // type earlier only to drop it again here.
5344 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5345 DependentTemplateName *DTN =
5346 TST->getTemplateName().getAsDependentTemplateName();
5347 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005348 assert(DTN->getQualifier()
5349 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5350 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5351 DTN->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00005352 DTN->getIdentifier(),
5353 TST->getNumArgs(),
5354 TST->getArgs());
John McCall99b2fe52010-04-29 23:50:39 +00005355 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCallc392f372010-06-11 00:33:02 +00005356 DependentTemplateSpecializationTypeLoc TL =
5357 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5358 if (InnerTSI) {
5359 TemplateSpecializationTypeLoc TSTL =
5360 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5361 TL.setLAngleLoc(TSTL.getLAngleLoc());
5362 TL.setRAngleLoc(TSTL.getRAngleLoc());
5363 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5364 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5365 } else {
5366 TL.initializeLocal(SourceLocation());
5367 }
John McCallf7bcc812010-05-28 23:32:21 +00005368 TL.setKeywordLoc(TypenameLoc);
5369 TL.setQualifierRange(SS.getRange());
John McCallba7bf592010-08-24 05:47:05 +00005370 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00005371}
5372
Douglas Gregor333489b2009-03-27 23:10:48 +00005373/// \brief Build the type that describes a C++ typename specifier,
5374/// e.g., "typename T::type".
5375QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005376Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5377 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005378 SourceLocation KeywordLoc, SourceRange NNSRange,
5379 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005380 CXXScopeSpec SS;
5381 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005382 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005383
John McCall0b66eb32010-05-01 00:40:08 +00005384 DeclContext *Ctx = computeDeclContext(SS);
5385 if (!Ctx) {
5386 // If the nested-name-specifier is dependent and couldn't be
5387 // resolved to a type, build a typename type.
5388 assert(NNS->isDependent());
5389 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005390 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005391
John McCall0b66eb32010-05-01 00:40:08 +00005392 // If the nested-name-specifier refers to the current instantiation,
5393 // the "typename" keyword itself is superfluous. In C++03, the
5394 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5395 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00005396 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005397
John McCall0b66eb32010-05-01 00:40:08 +00005398 if (RequireCompleteDeclContext(SS, Ctx))
5399 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005400
5401 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005402 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005403 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005404 unsigned DiagID = 0;
5405 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005406 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005407 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005408 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005409 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005410
5411 case LookupResult::NotFoundInCurrentInstantiation:
5412 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005413 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005414
5415 case LookupResult::Found:
Douglas Gregorf7d77712010-06-16 22:31:08 +00005416 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005417 // We found a type. Build an ElaboratedType, since the
5418 // typename-specifier was just sugar.
5419 return Context.getElaboratedType(ETK_Typename, NNS,
5420 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005421 }
5422
5423 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005424 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005425 break;
5426
John McCalle61f2ba2009-11-18 02:36:19 +00005427 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005428 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005429 return QualType();
5430
Douglas Gregor333489b2009-03-27 23:10:48 +00005431 case LookupResult::FoundOverloaded:
5432 DiagID = diag::err_typename_nested_not_type;
5433 Referenced = *Result.begin();
5434 break;
5435
John McCall6538c932009-10-10 05:48:19 +00005436 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005437 return QualType();
5438 }
5439
5440 // If we get here, it's because name lookup did not find a
5441 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005442 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5443 IILoc);
5444 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005445 if (Referenced)
5446 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5447 << Name;
5448 return QualType();
5449}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005450
5451namespace {
5452 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005453 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005454 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005455 SourceLocation Loc;
5456 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005457
Douglas Gregor15acfb92009-08-06 16:20:37 +00005458 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005459 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5460
Mike Stump11289f42009-09-09 15:08:12 +00005461 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005462 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005463 DeclarationName Entity)
5464 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005465 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005466
5467 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005468 /// transformed.
5469 ///
5470 /// For the purposes of type reconstruction, a type has already been
5471 /// transformed if it is NULL or if it is not dependent.
5472 bool AlreadyTransformed(QualType T) {
5473 return T.isNull() || !T->isDependentType();
5474 }
Mike Stump11289f42009-09-09 15:08:12 +00005475
5476 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005477 /// rebuilt.
5478 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005479
Douglas Gregor15acfb92009-08-06 16:20:37 +00005480 /// \brief Returns the name of the entity whose type is being rebuilt.
5481 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005482
Douglas Gregoref6ab412009-10-27 06:26:26 +00005483 /// \brief Sets the "base" location and entity when that
5484 /// information is known based on another transformation.
5485 void setBase(SourceLocation Loc, DeclarationName Entity) {
5486 this->Loc = Loc;
5487 this->Entity = Entity;
5488 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00005489 };
5490}
5491
Douglas Gregor15acfb92009-08-06 16:20:37 +00005492/// \brief Rebuilds a type within the context of the current instantiation.
5493///
Mike Stump11289f42009-09-09 15:08:12 +00005494/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005495/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005496/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005497/// partial specialization thereof). This routine will rebuild that type now
5498/// that we have entered the declarator's scope, which may produce different
5499/// canonical types, e.g.,
5500///
5501/// \code
5502/// template<typename T>
5503/// struct X {
5504/// typedef T* pointer;
5505/// pointer data();
5506/// };
5507///
5508/// template<typename T>
5509/// typename X<T>::pointer X<T>::data() { ... }
5510/// \endcode
5511///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005512/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005513/// since we do not know that we can look into X<T> when we parsed the type.
5514/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005515/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005516/// as the canonical type of T*, allowing the return types of the out-of-line
5517/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005518TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5519 SourceLocation Loc,
5520 DeclarationName Name) {
5521 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005522 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005523
Douglas Gregor15acfb92009-08-06 16:20:37 +00005524 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5525 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005526}
Douglas Gregorbe999392009-09-15 16:23:51 +00005527
John McCalldadc5752010-08-24 06:29:42 +00005528ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00005529 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5530 DeclarationName());
5531 return Rebuilder.TransformExpr(E);
5532}
5533
John McCall99b2fe52010-04-29 23:50:39 +00005534bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5535 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005536
5537 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5538 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5539 DeclarationName());
5540 NestedNameSpecifier *Rebuilt =
5541 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005542 if (!Rebuilt) return true;
5543
5544 SS.setScopeRep(Rebuilt);
5545 return false;
John McCall2408e322010-04-27 00:57:59 +00005546}
5547
Douglas Gregorbe999392009-09-15 16:23:51 +00005548/// \brief Produces a formatted string that describes the binding of
5549/// template parameters to template arguments.
5550std::string
5551Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5552 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005553 // FIXME: For variadic templates, we'll need to get the structured list.
5554 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5555 Args.flat_size());
5556}
5557
5558std::string
5559Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5560 const TemplateArgument *Args,
5561 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005562 std::string Result;
5563
Douglas Gregore62e6a02009-11-11 19:13:48 +00005564 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005565 return Result;
5566
5567 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005568 if (I >= NumArgs)
5569 break;
5570
Douglas Gregorbe999392009-09-15 16:23:51 +00005571 if (I == 0)
5572 Result += "[with ";
5573 else
5574 Result += ", ";
5575
5576 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5577 Result += Id->getName();
5578 } else {
5579 Result += '$';
5580 Result += llvm::utostr(I);
5581 }
5582
5583 Result += " = ";
5584
5585 switch (Args[I].getKind()) {
5586 case TemplateArgument::Null:
5587 Result += "<no value>";
5588 break;
5589
5590 case TemplateArgument::Type: {
5591 std::string TypeStr;
5592 Args[I].getAsType().getAsStringInternal(TypeStr,
5593 Context.PrintingPolicy);
5594 Result += TypeStr;
5595 break;
5596 }
5597
5598 case TemplateArgument::Declaration: {
5599 bool Unnamed = true;
5600 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5601 if (ND->getDeclName()) {
5602 Unnamed = false;
5603 Result += ND->getNameAsString();
5604 }
5605 }
5606
5607 if (Unnamed) {
5608 Result += "<anonymous>";
5609 }
5610 break;
5611 }
5612
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005613 case TemplateArgument::Template: {
5614 std::string Str;
5615 llvm::raw_string_ostream OS(Str);
5616 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5617 Result += OS.str();
5618 break;
5619 }
5620
Douglas Gregorbe999392009-09-15 16:23:51 +00005621 case TemplateArgument::Integral: {
5622 Result += Args[I].getAsIntegral()->toString(10);
5623 break;
5624 }
5625
5626 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005627 // FIXME: This is non-optimal, since we're regurgitating the
5628 // expression we were given.
5629 std::string Str;
5630 {
5631 llvm::raw_string_ostream OS(Str);
5632 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5633 Context.PrintingPolicy);
5634 }
5635 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005636 break;
5637 }
5638
5639 case TemplateArgument::Pack:
5640 // FIXME: Format template argument packs
5641 Result += "<template argument pack>";
5642 break;
5643 }
5644 }
5645
5646 Result += ']';
5647 return Result;
5648}