blob: 6434333fbe9b317baa6485d10d9700ef36282f2b [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"
Douglas Gregor7731d3f2010-10-13 00:27:52 +000023#include "clang/AST/TypeVisitor.h"
John McCall8b0666c2010-08-20 18:27:03 +000024#include "clang/Sema/DeclSpec.h"
25#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000026#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000027#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000028#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000029using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000030using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000031
Douglas Gregorb7bfe792009-09-02 22:59:36 +000032/// \brief Determine whether the declaration found is acceptable as the name
33/// of a template and, if so, return that template declaration. Otherwise,
34/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000035static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
36 NamedDecl *Orig) {
37 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000038
Douglas Gregorb7bfe792009-09-02 22:59:36 +000039 if (isa<TemplateDecl>(D))
John McCalle9cccd82010-06-16 08:42:20 +000040 return Orig;
Mike Stump11289f42009-09-09 15:08:12 +000041
Douglas Gregorb7bfe792009-09-02 22:59:36 +000042 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
43 // C++ [temp.local]p1:
44 // Like normal (non-template) classes, class templates have an
45 // injected-class-name (Clause 9). The injected-class-name
46 // can be used with or without a template-argument-list. When
47 // it is used without a template-argument-list, it is
48 // equivalent to the injected-class-name followed by the
49 // template-parameters of the class template enclosed in
50 // <>. When it is used with a template-argument-list, it
51 // refers to the specified class template specialization,
52 // which could be the current specialization or another
53 // specialization.
54 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000055 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000056 if (Record->getDescribedClassTemplate())
57 return Record->getDescribedClassTemplate();
58
59 if (ClassTemplateSpecializationDecl *Spec
60 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
61 return Spec->getSpecializedTemplate();
62 }
Mike Stump11289f42009-09-09 15:08:12 +000063
Douglas Gregorb7bfe792009-09-02 22:59:36 +000064 return 0;
65 }
Mike Stump11289f42009-09-09 15:08:12 +000066
Douglas Gregorb7bfe792009-09-02 22:59:36 +000067 return 0;
68}
69
John McCalle66edc12009-11-24 19:00:30 +000070static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor41f90302010-04-12 20:54:26 +000071 // The set of class templates we've already seen.
72 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000073 LookupResult::Filter filter = R.makeFilter();
74 while (filter.hasNext()) {
75 NamedDecl *Orig = filter.next();
John McCalle9cccd82010-06-16 08:42:20 +000076 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
John McCalle66edc12009-11-24 19:00:30 +000077 if (!Repl)
78 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +000079 else if (Repl != Orig) {
80
81 // C++ [temp.local]p3:
82 // A lookup that finds an injected-class-name (10.2) can result in an
83 // ambiguity in certain cases (for example, if it is found in more than
84 // one base class). If all of the injected-class-names that are found
85 // refer to specializations of the same class template, and if the name
86 // is followed by a template-argument-list, the reference refers to the
87 // class template itself and not a specialization thereof, and is not
88 // ambiguous.
89 //
90 // FIXME: Will we eventually have to do the same for alias templates?
91 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
92 if (!ClassTemplates.insert(ClassTmpl)) {
93 filter.erase();
94 continue;
95 }
John McCallbd8062d2010-08-13 07:02:08 +000096
97 // FIXME: we promote access to public here as a workaround to
98 // the fact that LookupResult doesn't let us remember that we
99 // found this template through a particular injected class name,
100 // which means we end up doing nasty things to the invariants.
101 // Pretending that access is public is *much* safer.
102 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000103 }
John McCalle66edc12009-11-24 19:00:30 +0000104 }
105 filter.done();
106}
107
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000108TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000109 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000110 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000111 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000112 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000113 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000114 TemplateTy &TemplateResult,
115 bool &MemberOfUnknownSpecialization) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000116 assert(getLangOptions().CPlusPlus && "No template names in C!");
117
Douglas Gregor3cf81312009-11-03 23:16:33 +0000118 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000119 MemberOfUnknownSpecialization = false;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000120
121 switch (Name.getKind()) {
122 case UnqualifiedId::IK_Identifier:
123 TName = DeclarationName(Name.Identifier);
124 break;
125
126 case UnqualifiedId::IK_OperatorFunctionId:
127 TName = Context.DeclarationNames.getCXXOperatorName(
128 Name.OperatorFunctionId.Operator);
129 break;
130
Alexis Hunted0530f2009-11-28 08:58:14 +0000131 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000132 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
133 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000134
Douglas Gregor3cf81312009-11-03 23:16:33 +0000135 default:
136 return TNK_Non_template;
137 }
Mike Stump11289f42009-09-09 15:08:12 +0000138
John McCallba7bf592010-08-24 05:47:05 +0000139 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000140
Douglas Gregorff18cc12009-12-31 08:11:17 +0000141 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
142 LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000143 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
144 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000145 if (R.empty()) return TNK_Non_template;
146 if (R.isAmbiguous()) {
147 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000148 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000149
150 // FIXME: we might have ambiguous templates, in which case we
151 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000152 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000153 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000154
John McCalld28ae272009-12-02 08:04:21 +0000155 TemplateName Template;
156 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000157
John McCalld28ae272009-12-02 08:04:21 +0000158 unsigned ResultCount = R.end() - R.begin();
159 if (ResultCount > 1) {
160 // We assume that we'll preserve the qualifier from a function
161 // template name in other ways.
162 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
163 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000164
165 // We'll do this lookup again later.
166 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000167 } else {
John McCalld28ae272009-12-02 08:04:21 +0000168 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
169
170 if (SS.isSet() && !SS.isInvalid()) {
171 NestedNameSpecifier *Qualifier
172 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000173 Template = Context.getQualifiedTemplateName(Qualifier,
174 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000175 } else {
176 Template = TemplateName(TD);
177 }
178
John McCalldcc71402010-08-13 02:23:42 +0000179 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000180 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000181
182 // We'll do this lookup again later.
183 R.suppressDiagnostics();
184 } else {
John McCalld28ae272009-12-02 08:04:21 +0000185 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
186 TemplateKind = TNK_Type_template;
187 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000188 }
Mike Stump11289f42009-09-09 15:08:12 +0000189
John McCalld28ae272009-12-02 08:04:21 +0000190 TemplateResult = TemplateTy::make(Template);
191 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000192}
193
Douglas Gregor18473f32010-01-12 21:28:44 +0000194bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
195 SourceLocation IILoc,
196 Scope *S,
197 const CXXScopeSpec *SS,
198 TemplateTy &SuggestedTemplate,
199 TemplateNameKind &SuggestedKind) {
200 // We can't recover unless there's a dependent scope specifier preceding the
201 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000202 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000203 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
204 computeDeclContext(*SS))
205 return false;
206
207 // The code is missing a 'template' keyword prior to the dependent template
208 // name.
209 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
210 Diag(IILoc, diag::err_template_kw_missing)
211 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000212 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor18473f32010-01-12 21:28:44 +0000213 SuggestedTemplate
214 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
215 SuggestedKind = TNK_Dependent_template_name;
216 return true;
217}
218
John McCalle66edc12009-11-24 19:00:30 +0000219void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000220 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000221 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000222 bool EnteringContext,
223 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000224 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000225 MemberOfUnknownSpecialization = false;
John McCalle66edc12009-11-24 19:00:30 +0000226 DeclContext *LookupCtx = 0;
227 bool isDependent = false;
228 if (!ObjectType.isNull()) {
229 // This nested-name-specifier occurs in a member access expression, e.g.,
230 // x->B::f, and we are looking into the type of the object.
231 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
232 LookupCtx = computeDeclContext(ObjectType);
233 isDependent = ObjectType->isDependentType();
234 assert((isDependent || !ObjectType->isIncompleteType()) &&
235 "Caller should have completed object type");
236 } else if (SS.isSet()) {
237 // This nested-name-specifier occurs after another nested-name-specifier,
238 // so long into the context associated with the prior nested-name-specifier.
239 LookupCtx = computeDeclContext(SS, EnteringContext);
240 isDependent = isDependentScopeSpecifier(SS);
241
242 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000243 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000244 return;
245 }
246
247 bool ObjectTypeSearchedInScope = false;
248 if (LookupCtx) {
249 // Perform "qualified" name lookup into the declaration context we
250 // computed, which is either the type of the base of a member access
251 // expression or the declaration context associated with a prior
252 // nested-name-specifier.
253 LookupQualifiedName(Found, LookupCtx);
254
255 if (!ObjectType.isNull() && Found.empty()) {
256 // C++ [basic.lookup.classref]p1:
257 // In a class member access expression (5.2.5), if the . or -> token is
258 // immediately followed by an identifier followed by a <, the
259 // identifier must be looked up to determine whether the < is the
260 // beginning of a template argument list (14.2) or a less-than operator.
261 // The identifier is first looked up in the class of the object
262 // expression. If the identifier is not found, it is then looked up in
263 // the context of the entire postfix-expression and shall name a class
264 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000265 if (S) LookupName(Found, S);
266 ObjectTypeSearchedInScope = true;
267 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000268 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000269 // We cannot look into a dependent object type or nested nme
270 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000271 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000272 return;
273 } else {
274 // Perform unqualified name lookup in the current scope.
275 LookupName(Found, S);
276 }
277
Douglas Gregorc119dd52010-01-12 17:06:20 +0000278 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000279 // If we did not find any names, attempt to correct any typos.
280 DeclarationName Name = Found.getLookupName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000281 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregorc048c522010-06-29 19:27:42 +0000282 false, CTC_CXXCasts)) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000283 FilterAcceptableTemplateNames(Context, Found);
John McCalle9cccd82010-06-16 08:42:20 +0000284 if (!Found.empty()) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000285 if (LookupCtx)
286 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
287 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000288 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000289 Found.getLookupName().getAsString());
290 else
291 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
292 << Name << Found.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +0000293 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000294 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000295 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
296 Diag(Template->getLocation(), diag::note_previous_decl)
297 << Template->getDeclName();
John McCalle9cccd82010-06-16 08:42:20 +0000298 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000299 } else {
300 Found.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +0000301 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000302 }
303 }
304
John McCalle66edc12009-11-24 19:00:30 +0000305 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000306 if (Found.empty()) {
307 if (isDependent)
308 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000309 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000310 }
John McCalle66edc12009-11-24 19:00:30 +0000311
312 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
313 // C++ [basic.lookup.classref]p1:
314 // [...] If the lookup in the class of the object expression finds a
315 // template, the name is also looked up in the context of the entire
316 // postfix-expression and [...]
317 //
318 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
319 LookupOrdinaryName);
320 LookupName(FoundOuter, S);
321 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor41f90302010-04-12 20:54:26 +0000322
John McCalle66edc12009-11-24 19:00:30 +0000323 if (FoundOuter.empty()) {
324 // - if the name is not found, the name found in the class of the
325 // object expression is used, otherwise
326 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
327 // - if the name is found in the context of the entire
328 // postfix-expression and does not name a class template, the name
329 // found in the class of the object expression is used, otherwise
John McCalle9cccd82010-06-16 08:42:20 +0000330 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000331 // - if the name found is a class template, it must refer to the same
332 // entity as the one found in the class of the object expression,
333 // otherwise the program is ill-formed.
334 if (!Found.isSingleResult() ||
335 Found.getFoundDecl()->getCanonicalDecl()
336 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
337 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000338 diag::ext_nested_name_member_ref_lookup_ambiguous)
339 << Found.getLookupName()
340 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000341 Diag(Found.getRepresentativeDecl()->getLocation(),
342 diag::note_ambig_member_ref_object_type)
343 << ObjectType;
344 Diag(FoundOuter.getFoundDecl()->getLocation(),
345 diag::note_ambig_member_ref_scope);
346
347 // Recover by taking the template that we found in the object
348 // expression's type.
349 }
350 }
351 }
352}
353
John McCallcd4b4772009-12-02 03:53:29 +0000354/// ActOnDependentIdExpression - Handle a dependent id-expression that
355/// was just parsed. This is only possible with an explicit scope
356/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000357ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000358Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000359 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000360 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000361 const TemplateArgumentListInfo *TemplateArgs) {
362 NestedNameSpecifier *Qualifier
363 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall87fe5d52010-05-20 01:18:31 +0000364
365 DeclContext *DC = getFunctionLevelDeclContext();
John McCalle66edc12009-11-24 19:00:30 +0000366
John McCallcd4b4772009-12-02 03:53:29 +0000367 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000368 isa<CXXMethodDecl>(DC) &&
369 cast<CXXMethodDecl>(DC)->isInstance()) {
370 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCallcd4b4772009-12-02 03:53:29 +0000371
John McCalle66edc12009-11-24 19:00:30 +0000372 // Since the 'this' expression is synthesized, we don't need to
373 // perform the double-lookup check.
374 NamedDecl *FirstQualifierInScope = 0;
375
John McCall2d74de92009-12-01 22:10:20 +0000376 return Owned(CXXDependentScopeMemberExpr::Create(Context,
377 /*This*/ 0, ThisType,
378 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000379 /*Op*/ SourceLocation(),
380 Qualifier, SS.getRange(),
381 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000382 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000383 TemplateArgs));
384 }
385
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000386 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000387}
388
John McCalldadc5752010-08-24 06:29:42 +0000389ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000390Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000391 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000392 const TemplateArgumentListInfo *TemplateArgs) {
393 return Owned(DependentScopeDeclRefExpr::Create(Context,
394 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
395 SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000396 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000397 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000398}
399
Douglas Gregor5101c242008-12-05 18:15:24 +0000400/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
401/// that the template parameter 'PrevDecl' is being shadowed by a new
402/// declaration at location Loc. Returns true to indicate that this is
403/// an error, and false otherwise.
404bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000405 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000406
407 // Microsoft Visual C++ permits template parameters to be shadowed.
408 if (getLangOptions().Microsoft)
409 return false;
410
411 // C++ [temp.local]p4:
412 // A template-parameter shall not be redeclared within its
413 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000414 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000415 << cast<NamedDecl>(PrevDecl)->getDeclName();
416 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
417 return true;
418}
419
Douglas Gregor463421d2009-03-03 04:44:36 +0000420/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000421/// the parameter D to reference the templated declaration and return a pointer
422/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000423TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
424 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
425 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000426 return Temp;
427 }
428 return 0;
429}
430
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000431static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
432 const ParsedTemplateArgument &Arg) {
433
434 switch (Arg.getKind()) {
435 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000436 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000437 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
438 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000439 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000440 return TemplateArgumentLoc(TemplateArgument(T), DI);
441 }
442
443 case ParsedTemplateArgument::NonType: {
444 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
445 return TemplateArgumentLoc(TemplateArgument(E), E);
446 }
447
448 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000449 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000450 return TemplateArgumentLoc(TemplateArgument(Template),
451 Arg.getScopeSpec().getRange(),
452 Arg.getLocation());
453 }
454 }
455
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000456 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000457 return TemplateArgumentLoc();
458}
459
460/// \brief Translates template arguments as provided by the parser
461/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000462void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
463 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000464 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000465 TemplateArgs.addArgument(translateTemplateArgument(*this,
466 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000467}
468
Douglas Gregor5101c242008-12-05 18:15:24 +0000469/// ActOnTypeParameter - Called when a C++ template type parameter
470/// (e.g., "typename T") has been parsed. Typename specifies whether
471/// the keyword "typename" was used to declare the type parameter
472/// (otherwise, "class" was used), and KeyLoc is the location of the
473/// "class" or "typename" keyword. ParamName is the name of the
474/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregor2ebcae12010-06-16 15:23:05 +0000475/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000476/// If the type parameter has a default argument, it will be added
477/// later via ActOnTypeParameterDefault.
John McCall48871652010-08-21 09:40:31 +0000478Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
479 SourceLocation EllipsisLoc,
480 SourceLocation KeyLoc,
481 IdentifierInfo *ParamName,
482 SourceLocation ParamNameLoc,
483 unsigned Depth, unsigned Position,
484 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000485 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000486 assert(S->isTemplateParamScope() &&
487 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000488 bool Invalid = false;
489
490 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000491 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000492 LookupOrdinaryName,
493 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000494 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000495 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000496 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000497 }
498
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000499 SourceLocation Loc = ParamNameLoc;
500 if (!ParamName)
501 Loc = KeyLoc;
502
Douglas Gregor5101c242008-12-05 18:15:24 +0000503 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000504 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
505 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000506 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000507 if (Invalid)
508 Param->setInvalidDecl();
509
510 if (ParamName) {
511 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000512 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000513 IdResolver.AddDecl(Param);
514 }
515
Douglas Gregordc13ded2010-07-01 00:00:45 +0000516 // Handle the default argument, if provided.
517 if (DefaultArg) {
518 TypeSourceInfo *DefaultTInfo;
519 GetTypeFromParser(DefaultArg, &DefaultTInfo);
520
521 assert(DefaultTInfo && "expected source information for type");
522
523 // C++0x [temp.param]p9:
524 // A default template-argument may be specified for any kind of
525 // template-parameter that is not a template parameter pack.
526 if (Ellipsis) {
527 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
John McCall48871652010-08-21 09:40:31 +0000528 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000529 }
530
531 // Check the template argument itself.
532 if (CheckTemplateArgument(Param, DefaultTInfo)) {
533 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000534 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000535 }
536
537 Param->setDefaultArgument(DefaultTInfo, false);
538 }
539
John McCall48871652010-08-21 09:40:31 +0000540 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000541}
542
Douglas Gregor463421d2009-03-03 04:44:36 +0000543/// \brief Check that the type of a non-type template parameter is
544/// well-formed.
545///
546/// \returns the (possibly-promoted) parameter type if valid;
547/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000548QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000549Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000550 // We don't allow variably-modified types as the type of non-type template
551 // parameters.
552 if (T->isVariablyModifiedType()) {
553 Diag(Loc, diag::err_variably_modified_nontype_template_param)
554 << T;
555 return QualType();
556 }
557
Douglas Gregor463421d2009-03-03 04:44:36 +0000558 // C++ [temp.param]p4:
559 //
560 // A non-type template-parameter shall have one of the following
561 // (optionally cv-qualified) types:
562 //
563 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000564 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000565 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000566 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000567 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000568 T->isReferenceType() ||
569 // -- pointer to member.
570 T->isMemberPointerType() ||
571 // If T is a dependent type, we can't do the check now, so we
572 // assume that it is well-formed.
573 T->isDependentType())
574 return T;
575 // C++ [temp.param]p8:
576 //
577 // A non-type template-parameter of type "array of T" or
578 // "function returning T" is adjusted to be of type "pointer to
579 // T" or "pointer to function returning T", respectively.
580 else if (T->isArrayType())
581 // FIXME: Keep the type prior to promotion?
582 return Context.getArrayDecayedType(T);
583 else if (T->isFunctionType())
584 // FIXME: Keep the type prior to promotion?
585 return Context.getPointerType(T);
Douglas Gregor959d5a02010-05-22 16:17:30 +0000586
Douglas Gregor463421d2009-03-03 04:44:36 +0000587 Diag(Loc, diag::err_template_nontype_parm_bad_type)
588 << T;
589
590 return QualType();
591}
592
John McCall48871652010-08-21 09:40:31 +0000593Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
594 unsigned Depth,
595 unsigned Position,
596 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000597 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000598 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
599 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000600
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000601 assert(S->isTemplateParamScope() &&
602 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000603 bool Invalid = false;
604
605 IdentifierInfo *ParamName = D.getIdentifier();
606 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000607 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000608 LookupOrdinaryName,
609 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000610 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000611 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000612 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000613 }
614
Douglas Gregor463421d2009-03-03 04:44:36 +0000615 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000616 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000617 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000618 Invalid = true;
619 }
Douglas Gregor81338792009-02-10 17:43:50 +0000620
Douglas Gregor5101c242008-12-05 18:15:24 +0000621 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000622 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
623 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000624 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000625 if (Invalid)
626 Param->setInvalidDecl();
627
628 if (D.getIdentifier()) {
629 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000630 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000631 IdResolver.AddDecl(Param);
632 }
Douglas Gregordc13ded2010-07-01 00:00:45 +0000633
634 // Check the well-formedness of the default template argument, if provided.
John McCallb268a282010-08-23 23:25:46 +0000635 if (Default) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000636 TemplateArgument Converted;
637 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
638 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000639 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000640 }
641
John McCallb268a282010-08-23 23:25:46 +0000642 Param->setDefaultArgument(Default, false);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000643 }
644
John McCall48871652010-08-21 09:40:31 +0000645 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000646}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000647
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000648/// ActOnTemplateTemplateParameter - Called when a C++ template template
649/// parameter (e.g. T in template <template <typename> class T> class array)
650/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000651Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
652 SourceLocation TmpLoc,
653 TemplateParamsTy *Params,
654 IdentifierInfo *Name,
655 SourceLocation NameLoc,
656 unsigned Depth,
657 unsigned Position,
658 SourceLocation EqualLoc,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000659 const ParsedTemplateArgument &Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000660 assert(S->isTemplateParamScope() &&
661 "Template template parameter not in template parameter scope!");
662
663 // Construct the parameter object.
664 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000665 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Douglas Gregor713602b2010-08-31 17:01:39 +0000666 NameLoc.isInvalid()? TmpLoc : NameLoc,
667 Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000668 (TemplateParameterList*)Params);
669
Douglas Gregordc13ded2010-07-01 00:00:45 +0000670 // If the template template parameter has a name, then link the identifier
671 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000672 if (Name) {
John McCall48871652010-08-21 09:40:31 +0000673 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000674 IdResolver.AddDecl(Param);
675 }
676
Douglas Gregordc13ded2010-07-01 00:00:45 +0000677 if (!Default.isInvalid()) {
678 // Check only that we have a template template argument. We don't want to
679 // try to check well-formedness now, because our template template parameter
680 // might have dependent types in its template parameters, which we wouldn't
681 // be able to match now.
682 //
683 // If none of the template template parameter's template arguments mention
684 // other template parameters, we could actually perform more checking here.
685 // However, it isn't worth doing.
686 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
687 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
688 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
689 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000690 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000691 }
692
693 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000694 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000695
John McCall48871652010-08-21 09:40:31 +0000696 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000697}
698
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000699/// ActOnTemplateParameterList - Builds a TemplateParameterList that
700/// contains the template parameters in Params/NumParams.
701Sema::TemplateParamsTy *
702Sema::ActOnTemplateParameterList(unsigned Depth,
703 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000704 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000705 SourceLocation LAngleLoc,
John McCall48871652010-08-21 09:40:31 +0000706 Decl **Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000707 SourceLocation RAngleLoc) {
708 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000709 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000710
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000711 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000712 (NamedDecl**)Params, NumParams,
713 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000714}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000715
John McCall3e11ebe2010-03-15 10:12:16 +0000716static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
717 if (SS.isSet())
718 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
719 SS.getRange());
720}
721
John McCallfaf5fb42010-08-26 23:41:50 +0000722DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000723Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000724 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000725 IdentifierInfo *Name, SourceLocation NameLoc,
726 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000727 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000728 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000729 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000730 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000731 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000732 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000733
734 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000735 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000736 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000737
Abramo Bagnara6150c882010-05-11 21:36:43 +0000738 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
739 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000740
741 // There is no such thing as an unnamed class template.
742 if (!Name) {
743 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000744 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000745 }
746
747 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000748 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000749 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000750 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000751 if (SS.isNotEmpty() && !SS.isInvalid()) {
752 SemanticContext = computeDeclContext(SS, true);
753 if (!SemanticContext) {
754 // FIXME: Produce a reasonable diagnostic here
755 return true;
756 }
Mike Stump11289f42009-09-09 15:08:12 +0000757
John McCall0b66eb32010-05-01 00:40:08 +0000758 if (RequireCompleteDeclContext(SS, SemanticContext))
759 return true;
760
John McCall27b18f82009-11-17 02:14:36 +0000761 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000762 } else {
763 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000764 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000765 }
Mike Stump11289f42009-09-09 15:08:12 +0000766
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000767 if (Previous.isAmbiguous())
768 return true;
769
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000770 NamedDecl *PrevDecl = 0;
771 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000772 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000773
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000774 // If there is a previous declaration with the same name, check
775 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000776 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000777 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000778
779 // We may have found the injected-class-name of a class template,
780 // class template partial specialization, or class template specialization.
781 // In these cases, grab the template that is being defined or specialized.
782 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
783 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
784 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
785 PrevClassTemplate
786 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
787 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
788 PrevClassTemplate
789 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
790 ->getSpecializedTemplate();
791 }
792 }
793
John McCalld43784f2009-12-18 11:25:59 +0000794 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000795 // C++ [namespace.memdef]p3:
796 // [...] When looking for a prior declaration of a class or a function
797 // declared as a friend, and when the name of the friend class or
798 // function is neither a qualified name nor a template-id, scopes outside
799 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000800 if (!SS.isSet()) {
801 DeclContext *OutermostContext = CurContext;
802 while (!OutermostContext->isFileContext())
803 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000804
Douglas Gregorb74b1032010-04-18 17:37:40 +0000805 if (PrevDecl &&
806 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
807 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
808 SemanticContext = PrevDecl->getDeclContext();
809 } else {
810 // Declarations in outer scopes don't matter. However, the outermost
811 // context we computed is the semantic context for our new
812 // declaration.
813 PrevDecl = PrevClassTemplate = 0;
814 SemanticContext = OutermostContext;
815 }
John McCall90d3bb92009-12-17 23:21:11 +0000816 }
Douglas Gregorb74b1032010-04-18 17:37:40 +0000817
John McCall90d3bb92009-12-17 23:21:11 +0000818 if (CurContext->isDependentContext()) {
819 // If this is a dependent context, we don't want to link the friend
820 // class template to the template in scope, because that would perform
821 // checking of the template parameter lists that can't be performed
822 // until the outer context is instantiated.
823 PrevDecl = PrevClassTemplate = 0;
824 }
825 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
826 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000827
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000828 if (PrevClassTemplate) {
829 // Ensure that the template parameter lists are compatible.
830 if (!TemplateParameterListsAreEqual(TemplateParams,
831 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000832 /*Complain=*/true,
833 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000834 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000835
836 // C++ [temp.class]p4:
837 // In a redeclaration, partial specialization, explicit
838 // specialization or explicit instantiation of a class template,
839 // the class-key shall agree in kind with the original class
840 // template declaration (7.1.5.3).
841 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000842 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000843 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000844 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000845 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000846 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000847 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000848 }
849
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000850 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000851 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000852 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000853 Diag(NameLoc, diag::err_redefinition) << Name;
854 Diag(Def->getLocation(), diag::note_previous_definition);
855 // FIXME: Would it make sense to try to "forget" the previous
856 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000857 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000858 }
859 }
860 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
861 // Maybe we will complain about the shadowed template parameter.
862 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
863 // Just pretend that we didn't see the previous declaration.
864 PrevDecl = 0;
865 } else if (PrevDecl) {
866 // C++ [temp]p5:
867 // A class template shall not have the same name as any other
868 // template, class, function, object, enumeration, enumerator,
869 // namespace, or type in the same scope (3.3), except as specified
870 // in (14.5.4).
871 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
872 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000873 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000874 }
875
Douglas Gregordba32632009-02-10 19:49:53 +0000876 // Check the template parameter list of this declaration, possibly
877 // merging in the template parameter list from the previous class
878 // template declaration.
879 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000880 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
881 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000882 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000883
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000884 if (SS.isSet()) {
885 // If the name of the template was qualified, we must be defining the
886 // template out-of-line.
887 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
888 !(TUK == TUK_Friend && CurContext->isDependentContext()))
889 Diag(NameLoc, diag::err_member_def_does_not_match)
890 << Name << SemanticContext << SS.getRange();
891 }
892
Mike Stump11289f42009-09-09 15:08:12 +0000893 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000894 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000895 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000896 PrevClassTemplate->getTemplatedDecl() : 0,
897 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000898 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000899
900 ClassTemplateDecl *NewTemplate
901 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
902 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000903 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000904 NewClass->setDescribedClassTemplate(NewTemplate);
905
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000906 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000907 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +0000908 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000909 assert(T->isDependentType() && "Class template type is not dependent?");
910 (void)T;
911
Douglas Gregorcf915552009-10-13 16:30:37 +0000912 // If we are providing an explicit specialization of a member that is a
913 // class template, make a note of that.
914 if (PrevClassTemplate &&
915 PrevClassTemplate->getInstantiatedFromMemberTemplate())
916 PrevClassTemplate->setMemberSpecialization();
917
Anders Carlsson137108d2009-03-26 01:24:28 +0000918 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000919 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000920 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000921
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000922 // Set the lexical context of these templates
923 NewClass->setLexicalDeclContext(CurContext);
924 NewTemplate->setLexicalDeclContext(CurContext);
925
John McCall9bb74a52009-07-31 02:45:11 +0000926 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000927 NewClass->startDefinition();
928
929 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000930 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000931
John McCall27b5c252009-09-14 21:59:20 +0000932 if (TUK != TUK_Friend)
933 PushOnScopeChains(NewTemplate, S);
934 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000935 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000936 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000937 NewClass->setAccess(PrevClassTemplate->getAccess());
938 }
John McCall27b5c252009-09-14 21:59:20 +0000939
Douglas Gregor3dad8422009-09-26 06:47:28 +0000940 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
941 PrevClassTemplate != NULL);
942
John McCall27b5c252009-09-14 21:59:20 +0000943 // Friend templates are visible in fairly strange ways.
944 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000945 DeclContext *DC = SemanticContext->getRedeclContext();
John McCall27b5c252009-09-14 21:59:20 +0000946 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
947 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
948 PushOnScopeChains(NewTemplate, EnclosingScope,
949 /* AddToContext = */ false);
950 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000951
952 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
953 NewClass->getLocation(),
954 NewTemplate,
955 /*FIXME:*/NewClass->getLocation());
956 Friend->setAccess(AS_public);
957 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000958 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000959
Douglas Gregordba32632009-02-10 19:49:53 +0000960 if (Invalid) {
961 NewTemplate->setInvalidDecl();
962 NewClass->setInvalidDecl();
963 }
John McCall48871652010-08-21 09:40:31 +0000964 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000965}
966
Douglas Gregored5731f2009-11-25 17:50:39 +0000967/// \brief Diagnose the presence of a default template argument on a
968/// template parameter, which is ill-formed in certain contexts.
969///
970/// \returns true if the default template argument should be dropped.
971static bool DiagnoseDefaultTemplateArgument(Sema &S,
972 Sema::TemplateParamListContext TPC,
973 SourceLocation ParamLoc,
974 SourceRange DefArgRange) {
975 switch (TPC) {
976 case Sema::TPC_ClassTemplate:
977 return false;
978
979 case Sema::TPC_FunctionTemplate:
980 // C++ [temp.param]p9:
981 // A default template-argument shall not be specified in a
982 // function template declaration or a function template
983 // definition [...]
984 // (This sentence is not in C++0x, per DR226).
985 if (!S.getLangOptions().CPlusPlus0x)
986 S.Diag(ParamLoc,
987 diag::err_template_parameter_default_in_function_template)
988 << DefArgRange;
989 return false;
990
991 case Sema::TPC_ClassTemplateMember:
992 // C++0x [temp.param]p9:
993 // A default template-argument shall not be specified in the
994 // template-parameter-lists of the definition of a member of a
995 // class template that appears outside of the member's class.
996 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
997 << DefArgRange;
998 return true;
999
1000 case Sema::TPC_FriendFunctionTemplate:
1001 // C++ [temp.param]p9:
1002 // A default template-argument shall not be specified in a
1003 // friend template declaration.
1004 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1005 << DefArgRange;
1006 return true;
1007
1008 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1009 // for friend function templates if there is only a single
1010 // declaration (and it is a definition). Strange!
1011 }
1012
1013 return false;
1014}
1015
Douglas Gregordba32632009-02-10 19:49:53 +00001016/// \brief Checks the validity of a template parameter list, possibly
1017/// considering the template parameter list from a previous
1018/// declaration.
1019///
1020/// If an "old" template parameter list is provided, it must be
1021/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1022/// template parameter list.
1023///
1024/// \param NewParams Template parameter list for a new template
1025/// declaration. This template parameter list will be updated with any
1026/// default arguments that are carried through from the previous
1027/// template parameter list.
1028///
1029/// \param OldParams If provided, template parameter list from a
1030/// previous declaration of the same template. Default template
1031/// arguments will be merged from the old template parameter list to
1032/// the new template parameter list.
1033///
Douglas Gregored5731f2009-11-25 17:50:39 +00001034/// \param TPC Describes the context in which we are checking the given
1035/// template parameter list.
1036///
Douglas Gregordba32632009-02-10 19:49:53 +00001037/// \returns true if an error occurred, false otherwise.
1038bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001039 TemplateParameterList *OldParams,
1040 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001041 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001042
Douglas Gregordba32632009-02-10 19:49:53 +00001043 // C++ [temp.param]p10:
1044 // The set of default template-arguments available for use with a
1045 // template declaration or definition is obtained by merging the
1046 // default arguments from the definition (if in scope) and all
1047 // declarations in scope in the same way default function
1048 // arguments are (8.3.6).
1049 bool SawDefaultArgument = false;
1050 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001051
Anders Carlsson327865d2009-06-12 23:20:15 +00001052 bool SawParameterPack = false;
1053 SourceLocation ParameterPackLoc;
1054
Mike Stumpc89c8e32009-02-11 23:03:27 +00001055 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001056 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001057 if (OldParams)
1058 OldParam = OldParams->begin();
1059
1060 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1061 NewParamEnd = NewParams->end();
1062 NewParam != NewParamEnd; ++NewParam) {
1063 // Variables used to diagnose redundant default arguments
1064 bool RedundantDefaultArg = false;
1065 SourceLocation OldDefaultLoc;
1066 SourceLocation NewDefaultLoc;
1067
1068 // Variables used to diagnose missing default arguments
1069 bool MissingDefaultArg = false;
1070
Anders Carlsson327865d2009-06-12 23:20:15 +00001071 // C++0x [temp.param]p11:
1072 // If a template parameter of a class template is a template parameter pack,
1073 // it must be the last template parameter.
1074 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001075 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001076 diag::err_template_param_pack_must_be_last_template_parameter);
1077 Invalid = true;
1078 }
1079
Douglas Gregordba32632009-02-10 19:49:53 +00001080 if (TemplateTypeParmDecl *NewTypeParm
1081 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001082 // Check the presence of a default argument here.
1083 if (NewTypeParm->hasDefaultArgument() &&
1084 DiagnoseDefaultTemplateArgument(*this, TPC,
1085 NewTypeParm->getLocation(),
1086 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001087 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001088 NewTypeParm->removeDefaultArgument();
1089
1090 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001091 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001092 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001093
Anders Carlsson327865d2009-06-12 23:20:15 +00001094 if (NewTypeParm->isParameterPack()) {
1095 assert(!NewTypeParm->hasDefaultArgument() &&
1096 "Parameter packs can't have a default argument!");
1097 SawParameterPack = true;
1098 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001099 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001100 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001101 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1102 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1103 SawDefaultArgument = true;
1104 RedundantDefaultArg = true;
1105 PreviousDefaultArgLoc = NewDefaultLoc;
1106 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1107 // Merge the default argument from the old declaration to the
1108 // new declaration.
1109 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001110 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001111 true);
1112 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1113 } else if (NewTypeParm->hasDefaultArgument()) {
1114 SawDefaultArgument = true;
1115 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1116 } else if (SawDefaultArgument)
1117 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001118 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001119 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001120 // Check the presence of a default argument here.
1121 if (NewNonTypeParm->hasDefaultArgument() &&
1122 DiagnoseDefaultTemplateArgument(*this, TPC,
1123 NewNonTypeParm->getLocation(),
1124 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001125 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001126 }
1127
Mike Stump12b8ce12009-08-04 21:02:39 +00001128 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001129 NonTypeTemplateParmDecl *OldNonTypeParm
1130 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001131 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001132 NewNonTypeParm->hasDefaultArgument()) {
1133 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1134 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1135 SawDefaultArgument = true;
1136 RedundantDefaultArg = true;
1137 PreviousDefaultArgLoc = NewDefaultLoc;
1138 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1139 // Merge the default argument from the old declaration to the
1140 // new declaration.
1141 SawDefaultArgument = true;
1142 // FIXME: We need to create a new kind of "default argument"
1143 // expression that points to a previous template template
1144 // parameter.
1145 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001146 OldNonTypeParm->getDefaultArgument(),
1147 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001148 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1149 } else if (NewNonTypeParm->hasDefaultArgument()) {
1150 SawDefaultArgument = true;
1151 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1152 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001153 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001154 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001155 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001156 TemplateTemplateParmDecl *NewTemplateParm
1157 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001158 if (NewTemplateParm->hasDefaultArgument() &&
1159 DiagnoseDefaultTemplateArgument(*this, TPC,
1160 NewTemplateParm->getLocation(),
1161 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001162 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001163
1164 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001165 TemplateTemplateParmDecl *OldTemplateParm
1166 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001167 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001168 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001169 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1170 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001171 SawDefaultArgument = true;
1172 RedundantDefaultArg = true;
1173 PreviousDefaultArgLoc = NewDefaultLoc;
1174 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1175 // Merge the default argument from the old declaration to the
1176 // new declaration.
1177 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001178 // FIXME: We need to create a new kind of "default argument" expression
1179 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001180 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001181 OldTemplateParm->getDefaultArgument(),
1182 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001183 PreviousDefaultArgLoc
1184 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001185 } else if (NewTemplateParm->hasDefaultArgument()) {
1186 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001187 PreviousDefaultArgLoc
1188 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001189 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001190 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001191 }
1192
1193 if (RedundantDefaultArg) {
1194 // C++ [temp.param]p12:
1195 // A template-parameter shall not be given default arguments
1196 // by two different declarations in the same scope.
1197 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1198 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1199 Invalid = true;
1200 } else if (MissingDefaultArg) {
1201 // C++ [temp.param]p11:
1202 // If a template-parameter has a default template-argument,
1203 // all subsequent template-parameters shall have a default
1204 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001205 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001206 diag::err_template_param_default_arg_missing);
1207 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1208 Invalid = true;
1209 }
1210
1211 // If we have an old template parameter list that we're merging
1212 // in, move on to the next parameter.
1213 if (OldParams)
1214 ++OldParam;
1215 }
1216
1217 return Invalid;
1218}
Douglas Gregord32e0282009-02-09 23:23:08 +00001219
Mike Stump11289f42009-09-09 15:08:12 +00001220/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001221/// specifier, returning the template parameter list that applies to the
1222/// name.
1223///
1224/// \param DeclStartLoc the start of the declaration that has a scope
1225/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001226///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001227/// \param SS the scope specifier that will be matched to the given template
1228/// parameter lists. This scope specifier precedes a qualified name that is
1229/// being declared.
1230///
1231/// \param ParamLists the template parameter lists, from the outermost to the
1232/// innermost template parameter lists.
1233///
1234/// \param NumParamLists the number of template parameter lists in ParamLists.
1235///
John McCalle820e5e2010-04-13 20:37:33 +00001236/// \param IsFriend Whether to apply the slightly different rules for
1237/// matching template parameters to scope specifiers in friend
1238/// declarations.
1239///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001240/// \param IsExplicitSpecialization will be set true if the entity being
1241/// declared is an explicit specialization, false otherwise.
1242///
Mike Stump11289f42009-09-09 15:08:12 +00001243/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001244/// name that is preceded by the scope specifier @p SS. This template
1245/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001246/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001247/// template specialization), or may be NULL (if we were's declaring isn't
1248/// itself a template).
1249TemplateParameterList *
1250Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1251 const CXXScopeSpec &SS,
1252 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001253 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001254 bool IsFriend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001255 bool &IsExplicitSpecialization,
1256 bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001257 IsExplicitSpecialization = false;
1258
Douglas Gregord8d297c2009-07-21 23:53:31 +00001259 // Find the template-ids that occur within the nested-name-specifier. These
1260 // template-ids will match up with the template parameter lists.
1261 llvm::SmallVector<const TemplateSpecializationType *, 4>
1262 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001263 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1264 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001265 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1266 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001267 const Type *T = NNS->getAsType();
1268 if (!T) break;
1269
1270 // C++0x [temp.expl.spec]p17:
1271 // A member or a member template may be nested within many
1272 // enclosing class templates. In an explicit specialization for
1273 // such a member, the member declaration shall be preceded by a
1274 // template<> for each enclosing class template that is
1275 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001276 //
1277 // Following the existing practice of GNU and EDG, we allow a typedef of a
1278 // template specialization type.
1279 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1280 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001281
Mike Stump11289f42009-09-09 15:08:12 +00001282 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001283 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001284 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1285 if (!Template)
1286 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001287
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001288 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001289 ClassTemplateSpecializationDecl *SpecDecl
1290 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1291 // If the nested name specifier refers to an explicit specialization,
1292 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001293 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1294 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001295 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001296 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001297 }
Mike Stump11289f42009-09-09 15:08:12 +00001298
Douglas Gregord8d297c2009-07-21 23:53:31 +00001299 TemplateIdsInSpecifier.push_back(SpecType);
1300 }
1301 }
Mike Stump11289f42009-09-09 15:08:12 +00001302
Douglas Gregord8d297c2009-07-21 23:53:31 +00001303 // Reverse the list of template-ids in the scope specifier, so that we can
1304 // more easily match up the template-ids and the template parameter lists.
1305 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001306
Douglas Gregord8d297c2009-07-21 23:53:31 +00001307 SourceLocation FirstTemplateLoc = DeclStartLoc;
1308 if (NumParamLists)
1309 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001310
Douglas Gregord8d297c2009-07-21 23:53:31 +00001311 // Match the template-ids found in the specifier to the template parameter
1312 // lists.
1313 unsigned Idx = 0;
1314 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1315 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001316 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1317 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001318 if (Idx >= NumParamLists) {
1319 // We have a template-id without a corresponding template parameter
1320 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001321
1322 // ...which is fine if this is a friend declaration.
1323 if (IsFriend) {
1324 IsExplicitSpecialization = true;
1325 break;
1326 }
1327
Douglas Gregord8d297c2009-07-21 23:53:31 +00001328 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001329 // FIXME: the location information here isn't great.
1330 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001331 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001332 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001333 << SS.getRange();
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001334 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001335 } else {
1336 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1337 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001338 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001339 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001340 }
1341 return 0;
1342 }
Mike Stump11289f42009-09-09 15:08:12 +00001343
Douglas Gregord8d297c2009-07-21 23:53:31 +00001344 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001345 if (DependentTemplateId) {
John McCall2408e322010-04-27 00:57:59 +00001346 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00001347
John McCall2408e322010-04-27 00:57:59 +00001348 // Are there cases in (e.g.) friends where this won't match?
1349 if (const InjectedClassNameType *Injected
1350 = TemplateId->getAs<InjectedClassNameType>()) {
1351 CXXRecordDecl *Record = Injected->getDecl();
1352 if (ClassTemplatePartialSpecializationDecl *Partial =
1353 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1354 ExpectedTemplateParams = Partial->getTemplateParameters();
1355 else
1356 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1357 ->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001358 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001359
John McCall2408e322010-04-27 00:57:59 +00001360 if (ExpectedTemplateParams)
1361 TemplateParameterListsAreEqual(ParamLists[Idx],
1362 ExpectedTemplateParams,
1363 true, TPL_TemplateMatch);
1364
Douglas Gregored5731f2009-11-25 17:50:39 +00001365 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001366 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001367 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001368 diag::err_template_param_list_matches_nontemplate)
1369 << TemplateId
1370 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001371 else
1372 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001373 }
Mike Stump11289f42009-09-09 15:08:12 +00001374
Douglas Gregord8d297c2009-07-21 23:53:31 +00001375 // If there were at least as many template-ids as there were template
1376 // parameter lists, then there are no template parameter lists remaining for
1377 // the declaration itself.
John McCallde3fd222010-10-12 23:13:28 +00001378 if (Idx >= NumParamLists) {
1379 // Silently drop template member friend declarations.
1380 // TODO: implement these
1381 if (IsFriend && NumParamLists) Invalid = true;
1382
Douglas Gregord8d297c2009-07-21 23:53:31 +00001383 return 0;
John McCallde3fd222010-10-12 23:13:28 +00001384 }
Mike Stump11289f42009-09-09 15:08:12 +00001385
Douglas Gregord8d297c2009-07-21 23:53:31 +00001386 // If there were too many template parameter lists, complain about that now.
1387 if (Idx != NumParamLists - 1) {
1388 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001389 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001390 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001391 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1392 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001393 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1394 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001395
1396 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1397 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1398 diag::note_explicit_template_spec_does_not_need_header)
1399 << ExplicitSpecializationsInSpecifier.back();
1400 ExplicitSpecializationsInSpecifier.pop_back();
1401 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001402
1403 // We have a template parameter list with no corresponding scope, which
1404 // means that the resulting template declaration can't be instantiated
1405 // properly (we'll end up with dependent nodes when we shouldn't).
1406 if (!isExplicitSpecHeader)
1407 Invalid = true;
1408
Douglas Gregord8d297c2009-07-21 23:53:31 +00001409 ++Idx;
1410 }
1411 }
Mike Stump11289f42009-09-09 15:08:12 +00001412
John McCallde3fd222010-10-12 23:13:28 +00001413 // Silently drop template member template friend declarations.
1414 // TODO: implement these
1415 if (IsFriend && NumParamLists > 1)
1416 Invalid = true;
1417
Douglas Gregord8d297c2009-07-21 23:53:31 +00001418 // Return the last template parameter list, which corresponds to the
1419 // entity being declared.
1420 return ParamLists[NumParamLists - 1];
1421}
1422
Douglas Gregordc572a32009-03-30 22:58:21 +00001423QualType Sema::CheckTemplateIdType(TemplateName Name,
1424 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001425 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001426 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001427 if (!Template) {
1428 // The template name does not resolve to a template, so we just
1429 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001430 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001431 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001432
Douglas Gregorc40290e2009-03-09 23:48:35 +00001433 // Check that the template argument list is well-formed for this
1434 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001435 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001436 TemplateArgs.size());
1437 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001438 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001439 return QualType();
1440
Mike Stump11289f42009-09-09 15:08:12 +00001441 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001442 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001443 "Converted template argument list is too short!");
1444
1445 QualType CanonType;
1446
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001447 if (Name.isDependent() ||
1448 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001449 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001450 // This class template specialization is a dependent
1451 // type. Therefore, its canonical type is another class template
1452 // specialization type that contains all of the converted
1453 // arguments in canonical form. This ensures that, e.g., A<T> and
1454 // A<T, T> have identical types when A is declared as:
1455 //
1456 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001457 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001458 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001459 Converted.getFlatArguments(),
1460 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001461
Douglas Gregora8e02e72009-07-28 23:00:59 +00001462 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001463 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001464 // In the future, we need to teach getTemplateSpecializationType to only
1465 // build the canonical type and return that to us.
1466 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001467
1468 // This might work out to be a current instantiation, in which
1469 // case the canonical type needs to be the InjectedClassNameType.
1470 //
1471 // TODO: in theory this could be a simple hashtable lookup; most
1472 // changes to CurContext don't change the set of current
1473 // instantiations.
1474 if (isa<ClassTemplateDecl>(Template)) {
1475 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1476 // If we get out to a namespace, we're done.
1477 if (Ctx->isFileContext()) break;
1478
1479 // If this isn't a record, keep looking.
1480 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1481 if (!Record) continue;
1482
1483 // Look for one of the two cases with InjectedClassNameTypes
1484 // and check whether it's the same template.
1485 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1486 !Record->getDescribedClassTemplate())
1487 continue;
1488
1489 // Fetch the injected class name type and check whether its
1490 // injected type is equal to the type we just built.
1491 QualType ICNT = Context.getTypeDeclType(Record);
1492 QualType Injected = cast<InjectedClassNameType>(ICNT)
1493 ->getInjectedSpecializationType();
1494
1495 if (CanonType != Injected->getCanonicalTypeInternal())
1496 continue;
1497
1498 // If so, the canonical type of this TST is the injected
1499 // class name type of the record we just found.
1500 assert(ICNT.isCanonical());
1501 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00001502 break;
1503 }
1504 }
Mike Stump11289f42009-09-09 15:08:12 +00001505 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001506 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001507 // Find the class template specialization declaration that
1508 // corresponds to these arguments.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001509 void *InsertPos = 0;
1510 ClassTemplateSpecializationDecl *Decl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001511 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
1512 Converted.flatSize(), InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001513 if (!Decl) {
1514 // This is the first time we have referenced this class template
1515 // specialization. Create the canonical declaration and add it to
1516 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001517 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001518 ClassTemplate->getTemplatedDecl()->getTagKind(),
1519 ClassTemplate->getDeclContext(),
1520 ClassTemplate->getLocation(),
1521 ClassTemplate,
1522 Converted, 0);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001523 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001524 Decl->setLexicalDeclContext(CurContext);
1525 }
1526
1527 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001528 assert(isa<RecordType>(CanonType) &&
1529 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001530 }
Mike Stump11289f42009-09-09 15:08:12 +00001531
Douglas Gregorc40290e2009-03-09 23:48:35 +00001532 // Build the fully-sugared type for this class template
1533 // specialization, which refers back to the class template
1534 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00001535 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001536}
1537
John McCallfaf5fb42010-08-26 23:41:50 +00001538TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001539Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001540 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001541 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001542 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001543 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001544
Douglas Gregorc40290e2009-03-09 23:48:35 +00001545 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001546 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001547 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001548
John McCall6b51f282009-11-23 01:53:49 +00001549 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001550 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001551
1552 if (Result.isNull())
1553 return true;
1554
John McCallbcd03502009-12-07 02:54:59 +00001555 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001556 TemplateSpecializationTypeLoc TL
1557 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1558 TL.setTemplateNameLoc(TemplateLoc);
1559 TL.setLAngleLoc(LAngleLoc);
1560 TL.setRAngleLoc(RAngleLoc);
1561 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1562 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1563
John McCallba7bf592010-08-24 05:47:05 +00001564 return CreateParsedType(Result, DI);
John McCalld8fe9af2009-09-08 17:47:29 +00001565}
John McCall06f6fe8d2009-09-04 01:14:41 +00001566
John McCallfaf5fb42010-08-26 23:41:50 +00001567TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1568 TagUseKind TUK,
1569 TypeSpecifierType TagSpec,
1570 SourceLocation TagLoc) {
John McCalld8fe9af2009-09-08 17:47:29 +00001571 if (TypeResult.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00001572 return ::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001573
John McCall0ad16662009-10-29 08:12:44 +00001574 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001575 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001576 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001577
John McCalld8fe9af2009-09-08 17:47:29 +00001578 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001579 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001580
John McCalld8fe9af2009-09-08 17:47:29 +00001581 if (const RecordType *RT = Type->getAs<RecordType>()) {
1582 RecordDecl *D = RT->getDecl();
1583
1584 IdentifierInfo *Id = D->getIdentifier();
1585 assert(Id && "templated class must have an identifier");
1586
1587 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1588 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001589 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001590 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001591 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001592 }
1593 }
1594
Abramo Bagnara6150c882010-05-11 21:36:43 +00001595 ElaboratedTypeKeyword Keyword
1596 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1597 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001598
John McCallba7bf592010-08-24 05:47:05 +00001599 return ParsedType::make(ElabType);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001600}
1601
John McCalldadc5752010-08-24 06:29:42 +00001602ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001603 LookupResult &R,
1604 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001605 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001606 // FIXME: Can we do any checking at this point? I guess we could check the
1607 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001608 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001609 // though.
John McCalle66edc12009-11-24 19:00:30 +00001610
1611 // These should be filtered out by our callers.
1612 assert(!R.empty() && "empty lookup results when building templateid");
1613 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1614
1615 NestedNameSpecifier *Qualifier = 0;
1616 SourceRange QualifierRange;
1617 if (SS.isSet()) {
1618 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1619 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001620 }
John McCall58cc69d2010-01-27 01:50:18 +00001621
1622 // We don't want lookup warnings at this point.
1623 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001624
John McCalle66edc12009-11-24 19:00:30 +00001625 bool Dependent
1626 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1627 &TemplateArgs);
1628 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001629 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001630 Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001631 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001632 RequiresADL, TemplateArgs,
1633 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001634
1635 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001636}
1637
John McCalle66edc12009-11-24 19:00:30 +00001638// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00001639ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001640Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001641 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +00001642 const TemplateArgumentListInfo &TemplateArgs) {
1643 DeclContext *DC;
1644 if (!(DC = computeDeclContext(SS, false)) ||
1645 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001646 RequireCompleteDeclContext(SS, DC))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001647 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001648
Douglas Gregor786123d2010-05-21 23:18:07 +00001649 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001650 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00001651 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1652 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00001653
John McCalle66edc12009-11-24 19:00:30 +00001654 if (R.isAmbiguous())
1655 return ExprError();
1656
1657 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001658 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1659 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001660 return ExprError();
1661 }
1662
1663 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001664 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1665 << (NestedNameSpecifier*) SS.getScopeRep()
1666 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001667 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1668 return ExprError();
1669 }
1670
1671 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001672}
1673
Douglas Gregorb67535d2009-03-31 00:43:58 +00001674/// \brief Form a dependent template name.
1675///
1676/// This action forms a dependent template name given the template
1677/// name and its (presumably dependent) scope specifier. For
1678/// example, given "MetaFun::template apply", the scope specifier \p
1679/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1680/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregorbb119652010-06-16 23:00:59 +00001681TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1682 SourceLocation TemplateKWLoc,
1683 CXXScopeSpec &SS,
1684 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00001685 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00001686 bool EnteringContext,
1687 TemplateTy &Result) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00001688 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1689 !getLangOptions().CPlusPlus0x)
1690 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1691 << FixItHint::CreateRemoval(TemplateKWLoc);
1692
Douglas Gregor9abe2372010-01-19 16:01:07 +00001693 DeclContext *LookupCtx = 0;
1694 if (SS.isSet())
1695 LookupCtx = computeDeclContext(SS, EnteringContext);
1696 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00001697 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00001698 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001699 // C++0x [temp.names]p5:
1700 // If a name prefixed by the keyword template is not the name of
1701 // a template, the program is ill-formed. [Note: the keyword
1702 // template may not be applied to non-template members of class
1703 // templates. -end note ] [ Note: as is the case with the
1704 // typename prefix, the template prefix is allowed in cases
1705 // where it is not strictly necessary; i.e., when the
1706 // nested-name-specifier or the expression on the left of the ->
1707 // or . is not dependent on a template-parameter, or the use
1708 // does not appear in the scope of a template. -end note]
1709 //
1710 // Note: C++03 was more strict here, because it banned the use of
1711 // the "template" keyword prior to a template-name that was not a
1712 // dependent name. C++ DR468 relaxed this requirement (the
1713 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00001714 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00001715 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001716 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1717 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00001718 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001719 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1720 isa<CXXRecordDecl>(LookupCtx) &&
1721 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregorbb119652010-06-16 23:00:59 +00001722 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00001723 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001724 Diag(Name.getSourceRange().getBegin(),
1725 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001726 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001727 << Name.getSourceRange()
1728 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001729 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00001730 } else {
1731 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00001732 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001733 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001734 }
1735
Mike Stump11289f42009-09-09 15:08:12 +00001736 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001737 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001738
1739 switch (Name.getKind()) {
1740 case UnqualifiedId::IK_Identifier:
Douglas Gregorbb119652010-06-16 23:00:59 +00001741 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1742 Name.Identifier));
1743 return TNK_Dependent_template_name;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001744
Douglas Gregor71395fa2009-11-04 00:56:37 +00001745 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00001746 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00001747 Name.OperatorFunctionId.Operator));
Douglas Gregorbb119652010-06-16 23:00:59 +00001748 return TNK_Dependent_template_name;
Alexis Hunted0530f2009-11-28 08:58:14 +00001749
1750 case UnqualifiedId::IK_LiteralOperatorId:
1751 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1752
Douglas Gregor3cf81312009-11-03 23:16:33 +00001753 default:
1754 break;
1755 }
1756
1757 Diag(Name.getSourceRange().getBegin(),
1758 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001759 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001760 << Name.getSourceRange()
1761 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001762 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001763}
1764
Mike Stump11289f42009-09-09 15:08:12 +00001765bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001766 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001767 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001768 const TemplateArgument &Arg = AL.getArgument();
1769
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001770 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001771 switch(Arg.getKind()) {
1772 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001773 // C++ [temp.arg.type]p1:
1774 // A template-argument for a template-parameter which is a
1775 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001776 break;
1777 case TemplateArgument::Template: {
1778 // We have a template type parameter but the template argument
1779 // is a template without any arguments.
1780 SourceRange SR = AL.getSourceRange();
1781 TemplateName Name = Arg.getAsTemplate();
1782 Diag(SR.getBegin(), diag::err_template_missing_args)
1783 << Name << SR;
1784 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1785 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001786
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001787 return true;
1788 }
1789 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001790 // We have a template type parameter but the template argument
1791 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001792 SourceRange SR = AL.getSourceRange();
1793 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001794 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001795
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001796 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001797 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001798 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001799
John McCallbcd03502009-12-07 02:54:59 +00001800 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001801 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001802
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001803 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001804 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001805 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001806 return false;
1807}
1808
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001809/// \brief Substitute template arguments into the default template argument for
1810/// the given template type parameter.
1811///
1812/// \param SemaRef the semantic analysis object for which we are performing
1813/// the substitution.
1814///
1815/// \param Template the template that we are synthesizing template arguments
1816/// for.
1817///
1818/// \param TemplateLoc the location of the template name that started the
1819/// template-id we are checking.
1820///
1821/// \param RAngleLoc the location of the right angle bracket ('>') that
1822/// terminates the template-id.
1823///
1824/// \param Param the template template parameter whose default we are
1825/// substituting into.
1826///
1827/// \param Converted the list of template arguments provided for template
1828/// parameters that precede \p Param in the template parameter list.
1829///
1830/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001831static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001832SubstDefaultTemplateArgument(Sema &SemaRef,
1833 TemplateDecl *Template,
1834 SourceLocation TemplateLoc,
1835 SourceLocation RAngleLoc,
1836 TemplateTypeParmDecl *Param,
1837 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001838 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001839
1840 // If the argument type is dependent, instantiate it now based
1841 // on the previously-computed template arguments.
1842 if (ArgType->getType()->isDependentType()) {
1843 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1844 /*TakeArgs=*/false);
1845
1846 MultiLevelTemplateArgumentList AllTemplateArgs
1847 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1848
1849 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1850 Template, Converted.getFlatArguments(),
1851 Converted.flatSize(),
1852 SourceRange(TemplateLoc, RAngleLoc));
1853
1854 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1855 Param->getDefaultArgumentLoc(),
1856 Param->getDeclName());
1857 }
1858
1859 return ArgType;
1860}
1861
1862/// \brief Substitute template arguments into the default template argument for
1863/// the given non-type template parameter.
1864///
1865/// \param SemaRef the semantic analysis object for which we are performing
1866/// the substitution.
1867///
1868/// \param Template the template that we are synthesizing template arguments
1869/// for.
1870///
1871/// \param TemplateLoc the location of the template name that started the
1872/// template-id we are checking.
1873///
1874/// \param RAngleLoc the location of the right angle bracket ('>') that
1875/// terminates the template-id.
1876///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001877/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001878/// substituting into.
1879///
1880/// \param Converted the list of template arguments provided for template
1881/// parameters that precede \p Param in the template parameter list.
1882///
1883/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00001884static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001885SubstDefaultTemplateArgument(Sema &SemaRef,
1886 TemplateDecl *Template,
1887 SourceLocation TemplateLoc,
1888 SourceLocation RAngleLoc,
1889 NonTypeTemplateParmDecl *Param,
1890 TemplateArgumentListBuilder &Converted) {
1891 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1892 /*TakeArgs=*/false);
1893
1894 MultiLevelTemplateArgumentList AllTemplateArgs
1895 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1896
1897 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1898 Template, Converted.getFlatArguments(),
1899 Converted.flatSize(),
1900 SourceRange(TemplateLoc, RAngleLoc));
1901
1902 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1903}
1904
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001905/// \brief Substitute template arguments into the default template argument for
1906/// the given template template parameter.
1907///
1908/// \param SemaRef the semantic analysis object for which we are performing
1909/// the substitution.
1910///
1911/// \param Template the template that we are synthesizing template arguments
1912/// for.
1913///
1914/// \param TemplateLoc the location of the template name that started the
1915/// template-id we are checking.
1916///
1917/// \param RAngleLoc the location of the right angle bracket ('>') that
1918/// terminates the template-id.
1919///
1920/// \param Param the template template parameter whose default we are
1921/// substituting into.
1922///
1923/// \param Converted the list of template arguments provided for template
1924/// parameters that precede \p Param in the template parameter list.
1925///
1926/// \returns the substituted template argument, or NULL if an error occurred.
1927static TemplateName
1928SubstDefaultTemplateArgument(Sema &SemaRef,
1929 TemplateDecl *Template,
1930 SourceLocation TemplateLoc,
1931 SourceLocation RAngleLoc,
1932 TemplateTemplateParmDecl *Param,
1933 TemplateArgumentListBuilder &Converted) {
1934 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1935 /*TakeArgs=*/false);
1936
1937 MultiLevelTemplateArgumentList AllTemplateArgs
1938 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1939
1940 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1941 Template, Converted.getFlatArguments(),
1942 Converted.flatSize(),
1943 SourceRange(TemplateLoc, RAngleLoc));
1944
1945 return SemaRef.SubstTemplateName(
1946 Param->getDefaultArgument().getArgument().getAsTemplate(),
1947 Param->getDefaultArgument().getTemplateNameLoc(),
1948 AllTemplateArgs);
1949}
1950
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001951/// \brief If the given template parameter has a default template
1952/// argument, substitute into that default template argument and
1953/// return the corresponding template argument.
1954TemplateArgumentLoc
1955Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1956 SourceLocation TemplateLoc,
1957 SourceLocation RAngleLoc,
1958 Decl *Param,
1959 TemplateArgumentListBuilder &Converted) {
1960 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1961 if (!TypeParm->hasDefaultArgument())
1962 return TemplateArgumentLoc();
1963
John McCallbcd03502009-12-07 02:54:59 +00001964 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001965 TemplateLoc,
1966 RAngleLoc,
1967 TypeParm,
1968 Converted);
1969 if (DI)
1970 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1971
1972 return TemplateArgumentLoc();
1973 }
1974
1975 if (NonTypeTemplateParmDecl *NonTypeParm
1976 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1977 if (!NonTypeParm->hasDefaultArgument())
1978 return TemplateArgumentLoc();
1979
John McCalldadc5752010-08-24 06:29:42 +00001980 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001981 TemplateLoc,
1982 RAngleLoc,
1983 NonTypeParm,
1984 Converted);
1985 if (Arg.isInvalid())
1986 return TemplateArgumentLoc();
1987
1988 Expr *ArgE = Arg.takeAs<Expr>();
1989 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1990 }
1991
1992 TemplateTemplateParmDecl *TempTempParm
1993 = cast<TemplateTemplateParmDecl>(Param);
1994 if (!TempTempParm->hasDefaultArgument())
1995 return TemplateArgumentLoc();
1996
1997 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1998 TemplateLoc,
1999 RAngleLoc,
2000 TempTempParm,
2001 Converted);
2002 if (TName.isNull())
2003 return TemplateArgumentLoc();
2004
2005 return TemplateArgumentLoc(TemplateArgument(TName),
2006 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2007 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2008}
2009
Douglas Gregorda0fb532009-11-11 19:31:23 +00002010/// \brief Check that the given template argument corresponds to the given
2011/// template parameter.
2012bool Sema::CheckTemplateArgument(NamedDecl *Param,
2013 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002014 TemplateDecl *Template,
2015 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002016 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002017 TemplateArgumentListBuilder &Converted,
2018 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00002019 // Check template type parameters.
2020 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002021 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002022
Douglas Gregoreebed722009-11-11 19:41:09 +00002023 // Check non-type template parameters.
2024 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00002025 // Do substitution on the type of the non-type template parameter
2026 // with the template arguments we've seen thus far.
2027 QualType NTTPType = NTTP->getType();
2028 if (NTTPType->isDependentType()) {
2029 // Do substitution on the type of the non-type template parameter.
2030 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2031 NTTP, Converted.getFlatArguments(),
2032 Converted.flatSize(),
2033 SourceRange(TemplateLoc, RAngleLoc));
2034
2035 TemplateArgumentList TemplateArgs(Context, Converted,
2036 /*TakeArgs=*/false);
2037 NTTPType = SubstType(NTTPType,
2038 MultiLevelTemplateArgumentList(TemplateArgs),
2039 NTTP->getLocation(),
2040 NTTP->getDeclName());
2041 // If that worked, check the non-type template parameter type
2042 // for validity.
2043 if (!NTTPType.isNull())
2044 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2045 NTTP->getLocation());
2046 if (NTTPType.isNull())
2047 return true;
2048 }
2049
2050 switch (Arg.getArgument().getKind()) {
2051 case TemplateArgument::Null:
2052 assert(false && "Should never see a NULL template argument here");
2053 return true;
2054
2055 case TemplateArgument::Expression: {
2056 Expr *E = Arg.getArgument().getAsExpr();
2057 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002058 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002059 return true;
2060
2061 Converted.Append(Result);
2062 break;
2063 }
2064
2065 case TemplateArgument::Declaration:
2066 case TemplateArgument::Integral:
2067 // We've already checked this template argument, so just copy
2068 // it to the list of converted arguments.
2069 Converted.Append(Arg.getArgument());
2070 break;
2071
2072 case TemplateArgument::Template:
2073 // We were given a template template argument. It may not be ill-formed;
2074 // see below.
2075 if (DependentTemplateName *DTN
2076 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2077 // We have a template argument such as \c T::template X, which we
2078 // parsed as a template template argument. However, since we now
2079 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002080 // template name into an expression.
2081
2082 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2083 Arg.getTemplateNameLoc());
2084
John McCalle66edc12009-11-24 19:00:30 +00002085 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2086 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002087 Arg.getTemplateQualifierRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002088 NameInfo);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002089
2090 TemplateArgument Result;
2091 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2092 return true;
2093
2094 Converted.Append(Result);
2095 break;
2096 }
2097
2098 // We have a template argument that actually does refer to a class
2099 // template, template alias, or template template parameter, and
2100 // therefore cannot be a non-type template argument.
2101 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2102 << Arg.getSourceRange();
2103
2104 Diag(Param->getLocation(), diag::note_template_param_here);
2105 return true;
2106
2107 case TemplateArgument::Type: {
2108 // We have a non-type template parameter but the template
2109 // argument is a type.
2110
2111 // C++ [temp.arg]p2:
2112 // In a template-argument, an ambiguity between a type-id and
2113 // an expression is resolved to a type-id, regardless of the
2114 // form of the corresponding template-parameter.
2115 //
2116 // We warn specifically about this case, since it can be rather
2117 // confusing for users.
2118 QualType T = Arg.getArgument().getAsType();
2119 SourceRange SR = Arg.getSourceRange();
2120 if (T->isFunctionType())
2121 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2122 else
2123 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2124 Diag(Param->getLocation(), diag::note_template_param_here);
2125 return true;
2126 }
2127
2128 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002129 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002130 break;
2131 }
2132
2133 return false;
2134 }
2135
2136
2137 // Check template template parameters.
2138 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2139
2140 // Substitute into the template parameter list of the template
2141 // template parameter, since previously-supplied template arguments
2142 // may appear within the template template parameter.
2143 {
2144 // Set up a template instantiation context.
2145 LocalInstantiationScope Scope(*this);
2146 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2147 TempParm, Converted.getFlatArguments(),
2148 Converted.flatSize(),
2149 SourceRange(TemplateLoc, RAngleLoc));
2150
2151 TemplateArgumentList TemplateArgs(Context, Converted,
2152 /*TakeArgs=*/false);
2153 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2154 SubstDecl(TempParm, CurContext,
2155 MultiLevelTemplateArgumentList(TemplateArgs)));
2156 if (!TempParm)
2157 return true;
2158
2159 // FIXME: TempParam is leaked.
2160 }
2161
2162 switch (Arg.getArgument().getKind()) {
2163 case TemplateArgument::Null:
2164 assert(false && "Should never see a NULL template argument here");
2165 return true;
2166
2167 case TemplateArgument::Template:
2168 if (CheckTemplateArgument(TempParm, Arg))
2169 return true;
2170
2171 Converted.Append(Arg.getArgument());
2172 break;
2173
2174 case TemplateArgument::Expression:
2175 case TemplateArgument::Type:
2176 // We have a template template parameter but the template
2177 // argument does not refer to a template.
2178 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2179 return true;
2180
2181 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002182 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002183 "Declaration argument with template template parameter");
2184 break;
2185 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002186 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002187 "Integral argument with template template parameter");
2188 break;
2189
2190 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002191 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002192 break;
2193 }
2194
2195 return false;
2196}
2197
Douglas Gregord32e0282009-02-09 23:23:08 +00002198/// \brief Check that the given template argument list is well-formed
2199/// for specializing the given template.
2200bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2201 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002202 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002203 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002204 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002205 TemplateParameterList *Params = Template->getTemplateParameters();
2206 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002207 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002208 bool Invalid = false;
2209
John McCall6b51f282009-11-23 01:53:49 +00002210 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2211
Mike Stump11289f42009-09-09 15:08:12 +00002212 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002213 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002214
Anders Carlsson15201f12009-06-13 02:08:00 +00002215 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002216 (NumArgs < Params->getMinRequiredArguments() &&
2217 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002218 // FIXME: point at either the first arg beyond what we can handle,
2219 // or the '>', depending on whether we have too many or too few
2220 // arguments.
2221 SourceRange Range;
2222 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002223 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002224 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2225 << (NumArgs > NumParams)
2226 << (isa<ClassTemplateDecl>(Template)? 0 :
2227 isa<FunctionTemplateDecl>(Template)? 1 :
2228 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2229 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002230 Diag(Template->getLocation(), diag::note_template_decl_here)
2231 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002232 Invalid = true;
2233 }
Mike Stump11289f42009-09-09 15:08:12 +00002234
2235 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002236 // [...] The type and form of each template-argument specified in
2237 // a template-id shall match the type and form specified for the
2238 // corresponding parameter declared by the template in its
2239 // template-parameter-list.
2240 unsigned ArgIdx = 0;
2241 for (TemplateParameterList::iterator Param = Params->begin(),
2242 ParamEnd = Params->end();
2243 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002244 if (ArgIdx > NumArgs && PartialTemplateArgs)
2245 break;
Mike Stump11289f42009-09-09 15:08:12 +00002246
Douglas Gregoreebed722009-11-11 19:41:09 +00002247 // If we have a template parameter pack, check every remaining template
2248 // argument against that template parameter pack.
2249 if ((*Param)->isTemplateParameterPack()) {
2250 Converted.BeginPack();
2251 for (; ArgIdx < NumArgs; ++ArgIdx) {
2252 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2253 TemplateLoc, RAngleLoc, Converted)) {
2254 Invalid = true;
2255 break;
2256 }
2257 }
2258 Converted.EndPack();
2259 continue;
2260 }
2261
Douglas Gregor84d49a22009-11-11 21:54:23 +00002262 if (ArgIdx < NumArgs) {
2263 // Check the template argument we were given.
2264 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2265 TemplateLoc, RAngleLoc, Converted))
2266 return true;
2267
2268 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002269 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002270
Douglas Gregor84d49a22009-11-11 21:54:23 +00002271 // We have a default template argument that we will use.
2272 TemplateArgumentLoc Arg;
2273
2274 // Retrieve the default template argument from the template
2275 // parameter. For each kind of template parameter, we substitute the
2276 // template arguments provided thus far and any "outer" template arguments
2277 // (when the template parameter was part of a nested template) into
2278 // the default argument.
2279 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2280 if (!TTP->hasDefaultArgument()) {
2281 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2282 break;
2283 }
2284
John McCallbcd03502009-12-07 02:54:59 +00002285 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002286 Template,
2287 TemplateLoc,
2288 RAngleLoc,
2289 TTP,
2290 Converted);
2291 if (!ArgType)
2292 return true;
2293
2294 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2295 ArgType);
2296 } else if (NonTypeTemplateParmDecl *NTTP
2297 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2298 if (!NTTP->hasDefaultArgument()) {
2299 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2300 break;
2301 }
2302
John McCalldadc5752010-08-24 06:29:42 +00002303 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002304 TemplateLoc,
2305 RAngleLoc,
2306 NTTP,
2307 Converted);
2308 if (E.isInvalid())
2309 return true;
2310
2311 Expr *Ex = E.takeAs<Expr>();
2312 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2313 } else {
2314 TemplateTemplateParmDecl *TempParm
2315 = cast<TemplateTemplateParmDecl>(*Param);
2316
2317 if (!TempParm->hasDefaultArgument()) {
2318 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2319 break;
2320 }
2321
2322 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2323 TemplateLoc,
2324 RAngleLoc,
2325 TempParm,
2326 Converted);
2327 if (Name.isNull())
2328 return true;
2329
2330 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2331 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2332 TempParm->getDefaultArgument().getTemplateNameLoc());
2333 }
2334
2335 // Introduce an instantiation record that describes where we are using
2336 // the default template argument.
2337 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2338 Converted.getFlatArguments(),
2339 Converted.flatSize(),
2340 SourceRange(TemplateLoc, RAngleLoc));
2341
2342 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002343 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002344 RAngleLoc, Converted))
2345 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002346 }
2347
2348 return Invalid;
2349}
2350
Douglas Gregor7731d3f2010-10-13 00:27:52 +00002351namespace {
2352 class UnnamedLocalNoLinkageFinder
2353 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
2354 {
2355 Sema &S;
2356 SourceRange SR;
2357
2358 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
2359
2360 public:
2361 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
2362
2363 bool Visit(QualType T) {
2364 return inherited::Visit(T.getTypePtr());
2365 }
2366
2367#define TYPE(Class, Parent) \
2368 bool Visit##Class##Type(const Class##Type *);
2369#define ABSTRACT_TYPE(Class, Parent) \
2370 bool Visit##Class##Type(const Class##Type *) { return false; }
2371#define NON_CANONICAL_TYPE(Class, Parent) \
2372 bool Visit##Class##Type(const Class##Type *) { return false; }
2373#include "clang/AST/TypeNodes.def"
2374
2375 bool VisitTagDecl(const TagDecl *Tag);
2376 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
2377 };
2378}
2379
2380bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
2381 return false;
2382}
2383
2384bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
2385 return Visit(T->getElementType());
2386}
2387
2388bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
2389 return Visit(T->getPointeeType());
2390}
2391
2392bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
2393 const BlockPointerType* T) {
2394 return Visit(T->getPointeeType());
2395}
2396
2397bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
2398 const LValueReferenceType* T) {
2399 return Visit(T->getPointeeType());
2400}
2401
2402bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
2403 const RValueReferenceType* T) {
2404 return Visit(T->getPointeeType());
2405}
2406
2407bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
2408 const MemberPointerType* T) {
2409 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
2410}
2411
2412bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
2413 const ConstantArrayType* T) {
2414 return Visit(T->getElementType());
2415}
2416
2417bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
2418 const IncompleteArrayType* T) {
2419 return Visit(T->getElementType());
2420}
2421
2422bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
2423 const VariableArrayType* T) {
2424 return Visit(T->getElementType());
2425}
2426
2427bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
2428 const DependentSizedArrayType* T) {
2429 return Visit(T->getElementType());
2430}
2431
2432bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
2433 const DependentSizedExtVectorType* T) {
2434 return Visit(T->getElementType());
2435}
2436
2437bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
2438 return Visit(T->getElementType());
2439}
2440
2441bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
2442 return Visit(T->getElementType());
2443}
2444
2445bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
2446 const FunctionProtoType* T) {
2447 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
2448 AEnd = T->arg_type_end();
2449 A != AEnd; ++A) {
2450 if (Visit(*A))
2451 return true;
2452 }
2453
2454 return Visit(T->getResultType());
2455}
2456
2457bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
2458 const FunctionNoProtoType* T) {
2459 return Visit(T->getResultType());
2460}
2461
2462bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
2463 const UnresolvedUsingType*) {
2464 return false;
2465}
2466
2467bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
2468 return false;
2469}
2470
2471bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
2472 return Visit(T->getUnderlyingType());
2473}
2474
2475bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
2476 return false;
2477}
2478
2479bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
2480 return VisitTagDecl(T->getDecl());
2481}
2482
2483bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
2484 return VisitTagDecl(T->getDecl());
2485}
2486
2487bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
2488 const TemplateTypeParmType*) {
2489 return false;
2490}
2491
2492bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
2493 const TemplateSpecializationType*) {
2494 return false;
2495}
2496
2497bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
2498 const InjectedClassNameType* T) {
2499 return VisitTagDecl(T->getDecl());
2500}
2501
2502bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
2503 const DependentNameType* T) {
2504 return VisitNestedNameSpecifier(T->getQualifier());
2505}
2506
2507bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
2508 const DependentTemplateSpecializationType* T) {
2509 return VisitNestedNameSpecifier(T->getQualifier());
2510}
2511
2512bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
2513 return false;
2514}
2515
2516bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
2517 const ObjCInterfaceType *) {
2518 return false;
2519}
2520
2521bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
2522 const ObjCObjectPointerType *) {
2523 return false;
2524}
2525
2526bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
2527 if (Tag->getDeclContext()->isFunctionOrMethod()) {
2528 S.Diag(SR.getBegin(), diag::ext_template_arg_local_type)
2529 << S.Context.getTypeDeclType(Tag) << SR;
2530 return true;
2531 }
2532
2533 if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl()) {
2534 S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
2535 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
2536 return true;
2537 }
2538
2539 return false;
2540}
2541
2542bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
2543 NestedNameSpecifier *NNS) {
2544 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
2545 return true;
2546
2547 switch (NNS->getKind()) {
2548 case NestedNameSpecifier::Identifier:
2549 case NestedNameSpecifier::Namespace:
2550 case NestedNameSpecifier::Global:
2551 return false;
2552
2553 case NestedNameSpecifier::TypeSpec:
2554 case NestedNameSpecifier::TypeSpecWithTemplate:
2555 return Visit(QualType(NNS->getAsType(), 0));
2556 }
2557}
2558
2559
Douglas Gregord32e0282009-02-09 23:23:08 +00002560/// \brief Check a template argument against its corresponding
2561/// template type parameter.
2562///
2563/// This routine implements the semantics of C++ [temp.arg.type]. It
2564/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002565bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002566 TypeSourceInfo *ArgInfo) {
2567 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002568 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00002569 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00002570
2571 if (Arg->isVariablyModifiedType()) {
2572 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002573 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002574 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002575 }
2576
Douglas Gregor7731d3f2010-10-13 00:27:52 +00002577 // C++03 [temp.arg.type]p2:
2578 // A local type, a type with no linkage, an unnamed type or a type
2579 // compounded from any of these types shall not be used as a
2580 // template-argument for a template type-parameter.
2581 //
2582 // C++0x allows these, and even in C++03 we allow them as an extension with
2583 // a warning.
2584 if (!LangOpts.CPlusPlus0x) {
2585 UnnamedLocalNoLinkageFinder Finder(*this, SR);
2586 (void)Finder.Visit(Context.getCanonicalType(Arg));
2587 }
2588
Douglas Gregord32e0282009-02-09 23:23:08 +00002589 return false;
2590}
2591
Douglas Gregorccb07762009-02-11 19:52:55 +00002592/// \brief Checks whether the given template argument is the address
2593/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002594static bool
2595CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2596 NonTypeTemplateParmDecl *Param,
2597 QualType ParamType,
2598 Expr *ArgIn,
2599 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002600 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002601 Expr *Arg = ArgIn;
2602 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002603
2604 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002605 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002606 Arg = Cast->getSubExpr();
2607
2608 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002609 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002610 // A template-argument for a non-type, non-template
2611 // template-parameter shall be one of: [...]
2612 //
2613 // -- the address of an object or function with external
2614 // linkage, including function templates and function
2615 // template-ids but excluding non-static class members,
2616 // expressed as & id-expression where the & is optional if
2617 // the name refers to a function or array, or if the
2618 // corresponding template-parameter is a reference; or
2619 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002620
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002621 // In C++98/03 mode, give an extension warning on any extra parentheses.
2622 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2623 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002624 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002625 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002626 S.Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002627 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002628 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002629 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002630 }
2631
2632 Arg = Parens->getSubExpr();
2633 }
2634
Douglas Gregorb242683d2010-04-01 18:32:35 +00002635 bool AddressTaken = false;
2636 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002637 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00002638 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002639 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002640 AddressTaken = true;
2641 AddrOpLoc = UnOp->getOperatorLoc();
2642 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002643 } else
2644 DRE = dyn_cast<DeclRefExpr>(Arg);
2645
Douglas Gregorb242683d2010-04-01 18:32:35 +00002646 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002647 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2648 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002649 S.Diag(Param->getLocation(), diag::note_template_param_here);
2650 return true;
2651 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002652
2653 // Stop checking the precise nature of the argument if it is value dependent,
2654 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002655 if (Arg->isValueDependent()) {
2656 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002657 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002658 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002659
Douglas Gregorb242683d2010-04-01 18:32:35 +00002660 if (!isa<ValueDecl>(DRE->getDecl())) {
2661 S.Diag(Arg->getSourceRange().getBegin(),
2662 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002663 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002664 S.Diag(Param->getLocation(), diag::note_template_param_here);
2665 return true;
2666 }
2667
2668 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002669
2670 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002671 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2672 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002673 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002674 S.Diag(Param->getLocation(), diag::note_template_param_here);
2675 return true;
2676 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002677
2678 // Cannot refer to non-static member functions
2679 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002680 if (!Method->isStatic()) {
2681 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002682 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002683 S.Diag(Param->getLocation(), diag::note_template_param_here);
2684 return true;
2685 }
Mike Stump11289f42009-09-09 15:08:12 +00002686
Douglas Gregorccb07762009-02-11 19:52:55 +00002687 // Functions must have external linkage.
2688 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002689 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002690 S.Diag(Arg->getSourceRange().getBegin(),
2691 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002692 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002693 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002694 << true;
2695 return true;
2696 }
2697
2698 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002699 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002700
Douglas Gregorb242683d2010-04-01 18:32:35 +00002701 // If the template parameter has pointer type, the function decays.
2702 if (ParamType->isPointerType() && !AddressTaken)
2703 ArgType = S.Context.getPointerType(Func->getType());
2704 else if (AddressTaken && ParamType->isReferenceType()) {
2705 // If we originally had an address-of operator, but the
2706 // parameter has reference type, complain and (if things look
2707 // like they will work) drop the address-of operator.
2708 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2709 ParamType.getNonReferenceType())) {
2710 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2711 << ParamType;
2712 S.Diag(Param->getLocation(), diag::note_template_param_here);
2713 return true;
2714 }
2715
2716 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2717 << ParamType
2718 << FixItHint::CreateRemoval(AddrOpLoc);
2719 S.Diag(Param->getLocation(), diag::note_template_param_here);
2720
2721 ArgType = Func->getType();
2722 }
2723 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002724 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002725 S.Diag(Arg->getSourceRange().getBegin(),
2726 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002727 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002728 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002729 << true;
2730 return true;
2731 }
2732
Douglas Gregorb242683d2010-04-01 18:32:35 +00002733 // A value of reference type is not an object.
2734 if (Var->getType()->isReferenceType()) {
2735 S.Diag(Arg->getSourceRange().getBegin(),
2736 diag::err_template_arg_reference_var)
2737 << Var->getType() << Arg->getSourceRange();
2738 S.Diag(Param->getLocation(), diag::note_template_param_here);
2739 return true;
2740 }
2741
Douglas Gregorccb07762009-02-11 19:52:55 +00002742 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002743 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002744
2745 // If the template parameter has pointer type, we must have taken
2746 // the address of this object.
2747 if (ParamType->isReferenceType()) {
2748 if (AddressTaken) {
2749 // If we originally had an address-of operator, but the
2750 // parameter has reference type, complain and (if things look
2751 // like they will work) drop the address-of operator.
2752 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2753 ParamType.getNonReferenceType())) {
2754 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2755 << ParamType;
2756 S.Diag(Param->getLocation(), diag::note_template_param_here);
2757 return true;
2758 }
2759
2760 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2761 << ParamType
2762 << FixItHint::CreateRemoval(AddrOpLoc);
2763 S.Diag(Param->getLocation(), diag::note_template_param_here);
2764
2765 ArgType = Var->getType();
2766 }
2767 } else if (!AddressTaken && ParamType->isPointerType()) {
2768 if (Var->getType()->isArrayType()) {
2769 // Array-to-pointer decay.
2770 ArgType = S.Context.getArrayDecayedType(Var->getType());
2771 } else {
2772 // If the template parameter has pointer type but the address of
2773 // this object was not taken, complain and (possibly) recover by
2774 // taking the address of the entity.
2775 ArgType = S.Context.getPointerType(Var->getType());
2776 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2777 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2778 << ParamType;
2779 S.Diag(Param->getLocation(), diag::note_template_param_here);
2780 return true;
2781 }
2782
2783 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2784 << ParamType
2785 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2786
2787 S.Diag(Param->getLocation(), diag::note_template_param_here);
2788 }
2789 }
2790 } else {
2791 // We found something else, but we don't know specifically what it is.
2792 S.Diag(Arg->getSourceRange().getBegin(),
2793 diag::err_template_arg_not_object_or_func)
2794 << Arg->getSourceRange();
2795 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2796 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002797 }
Mike Stump11289f42009-09-09 15:08:12 +00002798
Douglas Gregorb242683d2010-04-01 18:32:35 +00002799 if (ParamType->isPointerType() &&
2800 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2801 S.IsQualificationConversion(ArgType, ParamType)) {
2802 // For pointer-to-object types, qualification conversions are
2803 // permitted.
2804 } else {
2805 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2806 if (!ParamRef->getPointeeType()->isFunctionType()) {
2807 // C++ [temp.arg.nontype]p5b3:
2808 // For a non-type template-parameter of type reference to
2809 // object, no conversions apply. The type referred to by the
2810 // reference may be more cv-qualified than the (otherwise
2811 // identical) type of the template- argument. The
2812 // template-parameter is bound directly to the
2813 // template-argument, which shall be an lvalue.
2814
2815 // FIXME: Other qualifiers?
2816 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2817 unsigned ArgQuals = ArgType.getCVRQualifiers();
2818
2819 if ((ParamQuals | ArgQuals) != ParamQuals) {
2820 S.Diag(Arg->getSourceRange().getBegin(),
2821 diag::err_template_arg_ref_bind_ignores_quals)
2822 << ParamType << Arg->getType()
2823 << Arg->getSourceRange();
2824 S.Diag(Param->getLocation(), diag::note_template_param_here);
2825 return true;
2826 }
2827 }
2828 }
2829
2830 // At this point, the template argument refers to an object or
2831 // function with external linkage. We now need to check whether the
2832 // argument and parameter types are compatible.
2833 if (!S.Context.hasSameUnqualifiedType(ArgType,
2834 ParamType.getNonReferenceType())) {
2835 // We can't perform this conversion or binding.
2836 if (ParamType->isReferenceType())
2837 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2838 << ParamType << Arg->getType() << Arg->getSourceRange();
2839 else
2840 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2841 << Arg->getType() << ParamType << Arg->getSourceRange();
2842 S.Diag(Param->getLocation(), diag::note_template_param_here);
2843 return true;
2844 }
2845 }
2846
2847 // Create the template argument.
2848 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002849 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002850 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002851}
2852
2853/// \brief Checks whether the given template argument is a pointer to
2854/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002855bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2856 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002857 bool Invalid = false;
2858
2859 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002860 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002861 Arg = Cast->getSubExpr();
2862
2863 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002864 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002865 // A template-argument for a non-type, non-template
2866 // template-parameter shall be one of: [...]
2867 //
2868 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002869 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002870
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002871 // In C++98/03 mode, give an extension warning on any extra parentheses.
2872 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2873 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002874 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002875 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00002876 Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002877 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002878 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002879 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002880 }
2881
2882 Arg = Parens->getSubExpr();
2883 }
2884
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002885 // A pointer-to-member constant written &Class::member.
2886 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00002887 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002888 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2889 if (DRE && !DRE->getQualifier())
2890 DRE = 0;
2891 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002892 }
2893 // A constant of pointer-to-member type.
2894 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2895 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2896 if (VD->getType()->isMemberPointerType()) {
2897 if (isa<NonTypeTemplateParmDecl>(VD) ||
2898 (isa<VarDecl>(VD) &&
2899 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2900 if (Arg->isTypeDependent() || Arg->isValueDependent())
2901 Converted = TemplateArgument(Arg->Retain());
2902 else
2903 Converted = TemplateArgument(VD->getCanonicalDecl());
2904 return Invalid;
2905 }
2906 }
2907 }
2908
2909 DRE = 0;
2910 }
2911
Douglas Gregorccb07762009-02-11 19:52:55 +00002912 if (!DRE)
2913 return Diag(Arg->getSourceRange().getBegin(),
2914 diag::err_template_arg_not_pointer_to_member_form)
2915 << Arg->getSourceRange();
2916
2917 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2918 assert((isa<FieldDecl>(DRE->getDecl()) ||
2919 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2920 "Only non-static member pointers can make it here");
2921
2922 // Okay: this is the address of a non-static member, and therefore
2923 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002924 if (Arg->isTypeDependent() || Arg->isValueDependent())
2925 Converted = TemplateArgument(Arg->Retain());
2926 else
2927 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002928 return Invalid;
2929 }
2930
2931 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002932 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002933 diag::err_template_arg_not_pointer_to_member_form)
2934 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002935 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002936 diag::note_template_arg_refers_here);
2937 return true;
2938}
2939
Douglas Gregord32e0282009-02-09 23:23:08 +00002940/// \brief Check a template argument against its corresponding
2941/// non-type template parameter.
2942///
Douglas Gregor463421d2009-03-03 04:44:36 +00002943/// This routine implements the semantics of C++ [temp.arg.nontype].
2944/// It returns true if an error occurred, and false otherwise. \p
2945/// InstantiatedParamType is the type of the non-type template
2946/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002947///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002948/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002949bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002950 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002951 TemplateArgument &Converted,
2952 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002953 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2954
Douglas Gregor86560402009-02-10 23:36:10 +00002955 // If either the parameter has a dependent type or the argument is
2956 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002957 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2958 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002959 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002960 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002961 }
Douglas Gregor86560402009-02-10 23:36:10 +00002962
2963 // C++ [temp.arg.nontype]p5:
2964 // The following conversions are performed on each expression used
2965 // as a non-type template-argument. If a non-type
2966 // template-argument cannot be converted to the type of the
2967 // corresponding template-parameter then the program is
2968 // ill-formed.
2969 //
2970 // -- for a non-type template-parameter of integral or
2971 // enumeration type, integral promotions (4.5) and integral
2972 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002973 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002974 QualType ArgType = Arg->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +00002975 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002976 // C++ [temp.arg.nontype]p1:
2977 // A template-argument for a non-type, non-template
2978 // template-parameter shall be one of:
2979 //
2980 // -- an integral constant-expression of integral or enumeration
2981 // type; or
2982 // -- the name of a non-type template-parameter; or
2983 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002984 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00002985 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002986 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002987 diag::err_template_arg_not_integral_or_enumeral)
2988 << ArgType << Arg->getSourceRange();
2989 Diag(Param->getLocation(), diag::note_template_param_here);
2990 return true;
2991 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002992 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002993 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2994 << ArgType << Arg->getSourceRange();
2995 return true;
2996 }
2997
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002998 // From here on out, all we care about are the unqualified forms
2999 // of the parameter and argument types.
3000 ParamType = ParamType.getUnqualifiedType();
3001 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00003002
3003 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00003004 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00003005 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003006 } else if (CTAK == CTAK_Deduced) {
3007 // C++ [temp.deduct.type]p17:
3008 // If, in the declaration of a function template with a non-type
3009 // template-parameter, the non-type template- parameter is used
3010 // in an expression in the function parameter-list and, if the
3011 // corresponding template-argument is deduced, the
3012 // template-argument type shall match the type of the
3013 // template-parameter exactly, except that a template-argument
3014 // deduced from an array bound may be of any integral type.
3015 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3016 << ArgType << ParamType;
3017 Diag(Param->getLocation(), diag::note_template_param_here);
3018 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00003019 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3020 !ParamType->isEnumeralType()) {
3021 // This is an integral promotion or conversion.
John McCalle3027922010-08-25 11:45:40 +00003022 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00003023 } else {
3024 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003025 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00003026 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003027 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00003028 Diag(Param->getLocation(), diag::note_template_param_here);
3029 return true;
3030 }
3031
Douglas Gregor52aba872009-03-14 00:20:21 +00003032 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00003033 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003034 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00003035
3036 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00003037 llvm::APSInt OldValue = Value;
3038
3039 // Coerce the template argument's value to the value it will have
3040 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00003041 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00003042 if (Value.getBitWidth() != AllowedBits)
3043 Value.extOrTrunc(AllowedBits);
3044 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00003045
3046 // Complain if an unsigned parameter received a negative value.
3047 if (IntegerType->isUnsignedIntegerType()
3048 && (OldValue.isSigned() && OldValue.isNegative())) {
3049 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3050 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3051 << Arg->getSourceRange();
3052 Diag(Param->getLocation(), diag::note_template_param_here);
3053 }
3054
3055 // Complain if we overflowed the template parameter's type.
3056 unsigned RequiredBits;
3057 if (IntegerType->isUnsignedIntegerType())
3058 RequiredBits = OldValue.getActiveBits();
3059 else if (OldValue.isUnsigned())
3060 RequiredBits = OldValue.getActiveBits() + 1;
3061 else
3062 RequiredBits = OldValue.getMinSignedBits();
3063 if (RequiredBits > AllowedBits) {
3064 Diag(Arg->getSourceRange().getBegin(),
3065 diag::warn_template_arg_too_large)
3066 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3067 << Arg->getSourceRange();
3068 Diag(Param->getLocation(), diag::note_template_param_here);
3069 }
Douglas Gregor52aba872009-03-14 00:20:21 +00003070 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003071
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003072 // Add the value of this argument to the list of converted
3073 // arguments. We use the bitwidth and signedness of the template
3074 // parameter.
3075 if (Arg->isValueDependent()) {
3076 // The argument is value-dependent. Create a new
3077 // TemplateArgument with the converted expression.
3078 Converted = TemplateArgument(Arg);
3079 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003080 }
3081
John McCall0ad16662009-10-29 08:12:44 +00003082 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00003083 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003084 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00003085 return false;
3086 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003087
John McCall16df1e52010-03-30 21:47:33 +00003088 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3089
Douglas Gregorb242683d2010-04-01 18:32:35 +00003090 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3091 // from a template argument of type std::nullptr_t to a non-type
3092 // template parameter of type pointer to object, pointer to
3093 // function, or pointer-to-member, respectively.
3094 if (ArgType->isNullPtrType() &&
3095 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
3096 Converted = TemplateArgument((NamedDecl *)0);
3097 return false;
3098 }
3099
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003100 // Handle pointer-to-function, reference-to-function, and
3101 // pointer-to-member-function all in (roughly) the same way.
3102 if (// -- For a non-type template-parameter of type pointer to
3103 // function, only the function-to-pointer conversion (4.3) is
3104 // applied. If the template-argument represents a set of
3105 // overloaded functions (or a pointer to such), the matching
3106 // function is selected from the set (13.4).
3107 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003108 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003109 // -- For a non-type template-parameter of type reference to
3110 // function, no conversions apply. If the template-argument
3111 // represents a set of overloaded functions, the matching
3112 // function is selected from the set (13.4).
3113 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003114 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003115 // -- For a non-type template-parameter of type pointer to
3116 // member function, no conversions apply. If the
3117 // template-argument represents a set of overloaded member
3118 // functions, the matching member function is selected from
3119 // the set (13.4).
3120 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003121 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003122 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003123
Douglas Gregor064fdb22010-04-14 23:11:21 +00003124 if (Arg->getType() == Context.OverloadTy) {
3125 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
3126 true,
3127 FoundResult)) {
3128 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3129 return true;
3130
3131 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3132 ArgType = Arg->getType();
3133 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00003134 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003135 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00003136
Douglas Gregorb242683d2010-04-01 18:32:35 +00003137 if (!ParamType->isMemberPointerType())
3138 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3139 ParamType,
3140 Arg, Converted);
3141
3142 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCalle3027922010-08-25 11:45:40 +00003143 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb242683d2010-04-01 18:32:35 +00003144 } else if (!Context.hasSameUnqualifiedType(ArgType,
3145 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003146 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003147 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003148 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003149 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003150 Diag(Param->getLocation(), diag::note_template_param_here);
3151 return true;
3152 }
Mike Stump11289f42009-09-09 15:08:12 +00003153
Douglas Gregorb242683d2010-04-01 18:32:35 +00003154 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003155 }
3156
Chris Lattner696197c2009-02-20 21:37:53 +00003157 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003158 // -- for a non-type template-parameter of type pointer to
3159 // object, qualification conversions (4.4) and the
3160 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00003161 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00003162 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003163 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00003164
Douglas Gregorb242683d2010-04-01 18:32:35 +00003165 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3166 ParamType,
3167 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00003168 }
Mike Stump11289f42009-09-09 15:08:12 +00003169
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003170 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003171 // -- For a non-type template-parameter of type reference to
3172 // object, no conversions apply. The type referred to by the
3173 // reference may be more cv-qualified than the (otherwise
3174 // identical) type of the template-argument. The
3175 // template-parameter is bound directly to the
3176 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00003177 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003178 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00003179
Douglas Gregor064fdb22010-04-14 23:11:21 +00003180 if (Arg->getType() == Context.OverloadTy) {
3181 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
3182 ParamRefType->getPointeeType(),
3183 true,
3184 FoundResult)) {
3185 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3186 return true;
3187
3188 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3189 ArgType = Arg->getType();
3190 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00003191 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003192 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00003193
Douglas Gregorb242683d2010-04-01 18:32:35 +00003194 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3195 ParamType,
3196 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003197 }
Douglas Gregor0e558532009-02-11 16:16:59 +00003198
3199 // -- For a non-type template-parameter of type pointer to data
3200 // member, qualification conversions (4.4) are applied.
3201 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3202
Douglas Gregor1515f762009-02-11 18:22:40 +00003203 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00003204 // Types match exactly: nothing more to do here.
3205 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCalle3027922010-08-25 11:45:40 +00003206 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor0e558532009-02-11 16:16:59 +00003207 } else {
3208 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003209 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00003210 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003211 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00003212 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003213 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00003214 }
3215
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00003216 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00003217}
3218
3219/// \brief Check a template argument against its corresponding
3220/// template template parameter.
3221///
3222/// This routine implements the semantics of C++ [temp.arg.template].
3223/// It returns true if an error occurred, and false otherwise.
3224bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003225 const TemplateArgumentLoc &Arg) {
3226 TemplateName Name = Arg.getArgument().getAsTemplate();
3227 TemplateDecl *Template = Name.getAsTemplateDecl();
3228 if (!Template) {
3229 // Any dependent template name is fine.
3230 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3231 return false;
3232 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003233
3234 // C++ [temp.arg.template]p1:
3235 // A template-argument for a template template-parameter shall be
3236 // the name of a class template, expressed as id-expression. Only
3237 // primary class templates are considered when matching the
3238 // template template argument with the corresponding parameter;
3239 // partial specializations are not considered even if their
3240 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003241 //
3242 // Note that we also allow template template parameters here, which
3243 // will happen when we are dealing with, e.g., class template
3244 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003245 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003246 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003247 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003248 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003249 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003250 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003251 << Template;
3252 }
3253
3254 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3255 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003256 true,
3257 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003258 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003259}
3260
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003261/// \brief Given a non-type template argument that refers to a
3262/// declaration and the type of its corresponding non-type template
3263/// parameter, produce an expression that properly refers to that
3264/// declaration.
John McCalldadc5752010-08-24 06:29:42 +00003265ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003266Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3267 QualType ParamType,
3268 SourceLocation Loc) {
3269 assert(Arg.getKind() == TemplateArgument::Declaration &&
3270 "Only declaration template arguments permitted here");
3271 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3272
3273 if (VD->getDeclContext()->isRecord() &&
3274 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3275 // If the value is a class member, we might have a pointer-to-member.
3276 // Determine whether the non-type template template parameter is of
3277 // pointer-to-member type. If so, we need to build an appropriate
3278 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3279 // would refer to the member itself.
3280 if (ParamType->isMemberPointerType()) {
3281 QualType ClassType
3282 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3283 NestedNameSpecifier *Qualifier
John McCallb268a282010-08-23 23:25:46 +00003284 = NestedNameSpecifier::Create(Context, 0, false,
3285 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003286 CXXScopeSpec SS;
3287 SS.setScopeRep(Qualifier);
John McCalldadc5752010-08-24 06:29:42 +00003288 ExprResult RefExpr = BuildDeclRefExpr(VD,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003289 VD->getType().getNonReferenceType(),
3290 Loc,
3291 &SS);
3292 if (RefExpr.isInvalid())
3293 return ExprError();
3294
John McCalle3027922010-08-25 11:45:40 +00003295 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003296
3297 // We might need to perform a trailing qualification conversion, since
3298 // the element type on the parameter could be more qualified than the
3299 // element type in the expression we constructed.
3300 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3301 ParamType.getUnqualifiedType())) {
3302 Expr *RefE = RefExpr.takeAs<Expr>();
John McCalle3027922010-08-25 11:45:40 +00003303 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003304 RefExpr = Owned(RefE);
3305 }
3306
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003307 assert(!RefExpr.isInvalid() &&
3308 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003309 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003310 return move(RefExpr);
3311 }
3312 }
3313
3314 QualType T = VD->getType().getNonReferenceType();
3315 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003316 // When the non-type template parameter is a pointer, take the
3317 // address of the declaration.
John McCalldadc5752010-08-24 06:29:42 +00003318 ExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003319 if (RefExpr.isInvalid())
3320 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003321
3322 if (T->isFunctionType() || T->isArrayType()) {
3323 // Decay functions and arrays.
3324 Expr *RefE = (Expr *)RefExpr.get();
3325 DefaultFunctionArrayConversion(RefE);
3326 if (RefE != RefExpr.get()) {
3327 RefExpr.release();
3328 RefExpr = Owned(RefE);
3329 }
3330
3331 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003332 }
3333
Douglas Gregorb242683d2010-04-01 18:32:35 +00003334 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00003335 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003336 }
3337
3338 // If the non-type template parameter has reference type, qualify the
3339 // resulting declaration reference with the extra qualifiers on the
3340 // type that the reference refers to.
3341 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3342 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3343
3344 return BuildDeclRefExpr(VD, T, Loc);
3345}
3346
3347/// \brief Construct a new expression that refers to the given
3348/// integral template argument with the given source-location
3349/// information.
3350///
3351/// This routine takes care of the mapping from an integral template
3352/// argument (which may have any integral type) to the appropriate
3353/// literal value.
John McCalldadc5752010-08-24 06:29:42 +00003354ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003355Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3356 SourceLocation Loc) {
3357 assert(Arg.getKind() == TemplateArgument::Integral &&
3358 "Operation is only value for integral template arguments");
3359 QualType T = Arg.getIntegralType();
3360 if (T->isCharType() || T->isWideCharType())
3361 return Owned(new (Context) CharacterLiteral(
3362 Arg.getAsIntegral()->getZExtValue(),
3363 T->isWideCharType(),
3364 T,
3365 Loc));
3366 if (T->isBooleanType())
3367 return Owned(new (Context) CXXBoolLiteralExpr(
3368 Arg.getAsIntegral()->getBoolValue(),
3369 T,
3370 Loc));
3371
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003372 return Owned(IntegerLiteral::Create(Context, *Arg.getAsIntegral(), T, Loc));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003373}
3374
3375
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003376/// \brief Determine whether the given template parameter lists are
3377/// equivalent.
3378///
Mike Stump11289f42009-09-09 15:08:12 +00003379/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003380/// source code as part of a new template declaration.
3381///
3382/// \param Old The old template parameter list, typically found via
3383/// name lookup of the template declared with this template parameter
3384/// list.
3385///
3386/// \param Complain If true, this routine will produce a diagnostic if
3387/// the template parameter lists are not equivalent.
3388///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003389/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003390///
3391/// \param TemplateArgLoc If this source location is valid, then we
3392/// are actually checking the template parameter list of a template
3393/// argument (New) against the template parameter list of its
3394/// corresponding template template parameter (Old). We produce
3395/// slightly different diagnostics in this scenario.
3396///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003397/// \returns True if the template parameter lists are equal, false
3398/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003399bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003400Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3401 TemplateParameterList *Old,
3402 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003403 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003404 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003405 if (Old->size() != New->size()) {
3406 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003407 unsigned NextDiag = diag::err_template_param_list_different_arity;
3408 if (TemplateArgLoc.isValid()) {
3409 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3410 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003411 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003412 Diag(New->getTemplateLoc(), NextDiag)
3413 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003414 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003415 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003416 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003417 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003418 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3419 }
3420
3421 return false;
3422 }
3423
3424 for (TemplateParameterList::iterator OldParm = Old->begin(),
3425 OldParmEnd = Old->end(), NewParm = New->begin();
3426 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3427 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003428 if (Complain) {
3429 unsigned NextDiag = diag::err_template_param_different_kind;
3430 if (TemplateArgLoc.isValid()) {
3431 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3432 NextDiag = diag::note_template_param_different_kind;
3433 }
3434 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003435 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003436 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003437 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003438 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003439 return false;
3440 }
3441
Douglas Gregor2e87ca22010-06-04 08:34:32 +00003442 if (TemplateTypeParmDecl *OldTTP
3443 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3444 // Template type parameters are equivalent if either both are template
3445 // type parameter packs or neither are (since we know we're at the same
3446 // index).
3447 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3448 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3449 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3450 // allow one to match a template parameter pack in the template
3451 // parameter list of a template template parameter to one or more
3452 // template parameters in the template parameter list of the
3453 // corresponding template template argument.
3454 if (Complain) {
3455 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3456 if (TemplateArgLoc.isValid()) {
3457 Diag(TemplateArgLoc,
3458 diag::err_template_arg_template_params_mismatch);
3459 NextDiag = diag::note_template_parameter_pack_non_pack;
3460 }
3461 Diag(NewTTP->getLocation(), NextDiag)
3462 << 0 << NewTTP->isParameterPack();
3463 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3464 << 0 << OldTTP->isParameterPack();
3465 }
3466 return false;
3467 }
Mike Stump11289f42009-09-09 15:08:12 +00003468 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003469 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3470 // The types of non-type template parameters must agree.
3471 NonTypeTemplateParmDecl *NewNTTP
3472 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003473
3474 // If we are matching a template template argument to a template
3475 // template parameter and one of the non-type template parameter types
3476 // is dependent, then we must wait until template instantiation time
3477 // to actually compare the arguments.
3478 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3479 (OldNTTP->getType()->isDependentType() ||
3480 NewNTTP->getType()->isDependentType()))
3481 continue;
3482
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003483 if (Context.getCanonicalType(OldNTTP->getType()) !=
3484 Context.getCanonicalType(NewNTTP->getType())) {
3485 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003486 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3487 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003488 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003489 diag::err_template_arg_template_params_mismatch);
3490 NextDiag = diag::note_template_nontype_parm_different_type;
3491 }
3492 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003493 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003494 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003495 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003496 diag::note_template_nontype_parm_prev_declaration)
3497 << OldNTTP->getType();
3498 }
3499 return false;
3500 }
3501 } else {
3502 // The template parameter lists of template template
3503 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003504 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003505 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003506 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003507 = cast<TemplateTemplateParmDecl>(*OldParm);
3508 TemplateTemplateParmDecl *NewTTP
3509 = cast<TemplateTemplateParmDecl>(*NewParm);
3510 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3511 OldTTP->getTemplateParameters(),
3512 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003513 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003514 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003515 return false;
3516 }
3517 }
3518
3519 return true;
3520}
3521
3522/// \brief Check whether a template can be declared within this scope.
3523///
3524/// If the template declaration is valid in this scope, returns
3525/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003526bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003527Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003528 // Find the nearest enclosing declaration scope.
3529 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3530 (S->getFlags() & Scope::TemplateParamScope) != 0)
3531 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003532
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003533 // C++ [temp]p2:
3534 // A template-declaration can appear only as a namespace scope or
3535 // class scope declaration.
3536 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003537 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3538 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003539 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003540 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003541
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003542 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003543 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003544
3545 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3546 return false;
3547
Mike Stump11289f42009-09-09 15:08:12 +00003548 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003549 diag::err_template_outside_namespace_or_class_scope)
3550 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003551}
Douglas Gregor67a65642009-02-17 23:15:12 +00003552
Douglas Gregor54888652009-10-07 00:13:32 +00003553/// \brief Determine what kind of template specialization the given declaration
3554/// is.
3555static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3556 if (!D)
3557 return TSK_Undeclared;
3558
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003559 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3560 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003561 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3562 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003563 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3564 return Var->getTemplateSpecializationKind();
3565
Douglas Gregor54888652009-10-07 00:13:32 +00003566 return TSK_Undeclared;
3567}
3568
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003569/// \brief Check whether a specialization is well-formed in the current
3570/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003571///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003572/// This routine determines whether a template specialization can be declared
3573/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003574///
3575/// \param S the semantic analysis object for which this check is being
3576/// performed.
3577///
3578/// \param Specialized the entity being specialized or instantiated, which
3579/// may be a kind of template (class template, function template, etc.) or
3580/// a member of a class template (member function, static data member,
3581/// member class).
3582///
3583/// \param PrevDecl the previous declaration of this entity, if any.
3584///
3585/// \param Loc the location of the explicit specialization or instantiation of
3586/// this entity.
3587///
3588/// \param IsPartialSpecialization whether this is a partial specialization of
3589/// a class template.
3590///
Douglas Gregor54888652009-10-07 00:13:32 +00003591/// \returns true if there was an error that we cannot recover from, false
3592/// otherwise.
3593static bool CheckTemplateSpecializationScope(Sema &S,
3594 NamedDecl *Specialized,
3595 NamedDecl *PrevDecl,
3596 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003597 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003598 // Keep these "kind" numbers in sync with the %select statements in the
3599 // various diagnostics emitted by this routine.
3600 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003601 bool isTemplateSpecialization = false;
3602 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003603 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003604 isTemplateSpecialization = true;
3605 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003606 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003607 isTemplateSpecialization = true;
3608 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003609 EntityKind = 3;
3610 else if (isa<VarDecl>(Specialized))
3611 EntityKind = 4;
3612 else if (isa<RecordDecl>(Specialized))
3613 EntityKind = 5;
3614 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003615 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3616 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003617 return true;
3618 }
3619
Douglas Gregorf47b9112009-02-25 22:02:03 +00003620 // C++ [temp.expl.spec]p2:
3621 // An explicit specialization shall be declared in the namespace
3622 // of which the template is a member, or, for member templates, in
3623 // the namespace of which the enclosing class or enclosing class
3624 // template is a member. An explicit specialization of a member
3625 // function, member class or static data member of a class
3626 // template shall be declared in the namespace of which the class
3627 // template is a member. Such a declaration may also be a
3628 // definition. If the declaration is not a definition, the
3629 // specialization may be defined later in the name- space in which
3630 // the explicit specialization was declared, or in a namespace
3631 // that encloses the one in which the explicit specialization was
3632 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00003633 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00003634 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003635 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003636 return true;
3637 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003638
Douglas Gregor40fb7442009-10-07 17:30:37 +00003639 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3640 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003641 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003642 return true;
3643 }
3644
Douglas Gregore4b05162009-10-07 17:21:34 +00003645 // C++ [temp.class.spec]p6:
3646 // A class template partial specialization may be declared or redeclared
3647 // in any namespace scope in which its definition may be defined (14.5.1
3648 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003649 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003650 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003651 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003652 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003653 if ((!PrevDecl ||
3654 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3655 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregorb1aab432010-09-12 05:08:28 +00003656 // C++ [temp.exp.spec]p2:
3657 // An explicit specialization shall be declared in the namespace of which
3658 // the template is a member, or, for member templates, in the namespace
3659 // of which the enclosing class or enclosing class template is a member.
3660 // An explicit specialization of a member function, member class or
3661 // static data member of a class template shall be declared in the
3662 // namespace of which the class template is a member.
3663 //
3664 // C++0x [temp.expl.spec]p2:
3665 // An explicit specialization shall be declared in a namespace enclosing
3666 // the specialized template.
3667 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
3668 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
Douglas Gregor8ce63152010-09-12 05:24:55 +00003669 bool IsCPlusPlus0xExtension
3670 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003671 if (isa<TranslationUnitDecl>(SpecializedContext))
Douglas Gregor8ce63152010-09-12 05:24:55 +00003672 S.Diag(Loc, IsCPlusPlus0xExtension
3673 ? diag::ext_template_spec_decl_out_of_scope_global
3674 : diag::err_template_spec_decl_out_of_scope_global)
3675 << EntityKind << Specialized;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003676 else if (isa<NamespaceDecl>(SpecializedContext))
Douglas Gregor8ce63152010-09-12 05:24:55 +00003677 S.Diag(Loc, IsCPlusPlus0xExtension
3678 ? diag::ext_template_spec_decl_out_of_scope
3679 : diag::err_template_spec_decl_out_of_scope)
3680 << EntityKind << Specialized
3681 << cast<NamedDecl>(SpecializedContext);
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003682
3683 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3684 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003685 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003686 }
Douglas Gregor54888652009-10-07 00:13:32 +00003687
3688 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003689 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003690 // Note that HandleDeclarator() performs this check for explicit
3691 // specializations of function templates, static data members, and member
3692 // functions, so we skip the check here for those kinds of entities.
3693 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003694 // Should we refactor that check, so that it occurs later?
3695 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003696 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3697 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003698 if (isa<TranslationUnitDecl>(SpecializedContext))
3699 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3700 << EntityKind << Specialized;
3701 else if (isa<NamespaceDecl>(SpecializedContext))
3702 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3703 << EntityKind << Specialized
3704 << cast<NamedDecl>(SpecializedContext);
3705
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003706 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003707 }
Douglas Gregor54888652009-10-07 00:13:32 +00003708
3709 // FIXME: check for specialization-after-instantiation errors and such.
3710
Douglas Gregorf47b9112009-02-25 22:02:03 +00003711 return false;
3712}
Douglas Gregor54888652009-10-07 00:13:32 +00003713
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003714/// \brief Check the non-type template arguments of a class template
3715/// partial specialization according to C++ [temp.class.spec]p9.
3716///
Douglas Gregor09a30232009-06-12 22:08:06 +00003717/// \param TemplateParams the template parameters of the primary class
3718/// template.
3719///
3720/// \param TemplateArg the template arguments of the class template
3721/// partial specialization.
3722///
3723/// \param MirrorsPrimaryTemplate will be set true if the class
3724/// template partial specialization arguments are identical to the
3725/// implicit template arguments of the primary template. This is not
3726/// necessarily an error (C++0x), and it is left to the caller to diagnose
3727/// this condition when it is an error.
3728///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003729/// \returns true if there was an error, false otherwise.
3730bool Sema::CheckClassTemplatePartialSpecializationArgs(
3731 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003732 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003733 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003734 // FIXME: the interface to this function will have to change to
3735 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003736 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003737
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003738 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003739
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003740 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003741 // Determine whether the template argument list of the partial
3742 // specialization is identical to the implicit argument list of
3743 // the primary template. The caller may need to diagnostic this as
3744 // an error per C++ [temp.class.spec]p9b3.
3745 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003746 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003747 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3748 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003749 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003750 MirrorsPrimaryTemplate = false;
3751 } else if (TemplateTemplateParmDecl *TTP
3752 = dyn_cast<TemplateTemplateParmDecl>(
3753 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003754 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003755 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003756 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003757 if (!ArgDecl ||
3758 ArgDecl->getIndex() != TTP->getIndex() ||
3759 ArgDecl->getDepth() != TTP->getDepth())
3760 MirrorsPrimaryTemplate = false;
3761 }
3762 }
3763
Mike Stump11289f42009-09-09 15:08:12 +00003764 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003765 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003766 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003767 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003768 }
3769
Anders Carlsson40c1d492009-06-13 18:20:51 +00003770 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003771 if (!ArgExpr) {
3772 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003773 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003774 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003775
3776 // C++ [temp.class.spec]p8:
3777 // A non-type argument is non-specialized if it is the name of a
3778 // non-type parameter. All other non-type arguments are
3779 // specialized.
3780 //
3781 // Below, we check the two conditions that only apply to
3782 // specialized non-type arguments, so skip any non-specialized
3783 // arguments.
3784 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003785 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003786 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003787 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003788 (Param->getIndex() != NTTP->getIndex() ||
3789 Param->getDepth() != NTTP->getDepth()))
3790 MirrorsPrimaryTemplate = false;
3791
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003792 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003793 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003794
3795 // C++ [temp.class.spec]p9:
3796 // Within the argument list of a class template partial
3797 // specialization, the following restrictions apply:
3798 // -- A partially specialized non-type argument expression
3799 // shall not involve a template parameter of the partial
3800 // specialization except when the argument expression is a
3801 // simple identifier.
3802 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003803 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003804 diag::err_dependent_non_type_arg_in_partial_spec)
3805 << ArgExpr->getSourceRange();
3806 return true;
3807 }
3808
3809 // -- The type of a template parameter corresponding to a
3810 // specialized non-type argument shall not be dependent on a
3811 // parameter of the specialization.
3812 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003813 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003814 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3815 << Param->getType()
3816 << ArgExpr->getSourceRange();
3817 Diag(Param->getLocation(), diag::note_template_param_here);
3818 return true;
3819 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003820
3821 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003822 }
3823
3824 return false;
3825}
3826
Douglas Gregorc854c662010-02-26 06:03:23 +00003827/// \brief Retrieve the previous declaration of the given declaration.
3828static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3829 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3830 return VD->getPreviousDeclaration();
3831 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3832 return FD->getPreviousDeclaration();
3833 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3834 return TD->getPreviousDeclaration();
3835 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3836 return TD->getPreviousDeclaration();
3837 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3838 return FTD->getPreviousDeclaration();
3839 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3840 return CTD->getPreviousDeclaration();
3841 return 0;
3842}
3843
John McCall48871652010-08-21 09:40:31 +00003844DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003845Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3846 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003847 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003848 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003849 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003850 SourceLocation TemplateNameLoc,
3851 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003852 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003853 SourceLocation RAngleLoc,
3854 AttributeList *Attr,
3855 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003856 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003857
Douglas Gregor67a65642009-02-17 23:15:12 +00003858 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003859 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003860 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003861 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3862
3863 if (!ClassTemplate) {
3864 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3865 << (Name.getAsTemplateDecl() &&
3866 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3867 return true;
3868 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003869
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003870 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003871 bool isPartialSpecialization = false;
3872
Douglas Gregorf47b9112009-02-25 22:02:03 +00003873 // Check the validity of the template headers that introduce this
3874 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003875 // FIXME: We probably shouldn't complain about these headers for
3876 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003877 bool Invalid = false;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003878 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003879 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3880 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003881 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003882 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003883 isExplicitSpecialization,
3884 Invalid);
3885 if (Invalid)
3886 return true;
3887
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003888 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3889 if (TemplateParams)
3890 --NumMatchedTemplateParamLists;
3891
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003892 if (TemplateParams && TemplateParams->size() > 0) {
3893 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003894
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003895 // C++ [temp.class.spec]p10:
3896 // The template parameter list of a specialization shall not
3897 // contain default template argument values.
3898 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3899 Decl *Param = TemplateParams->getParam(I);
3900 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3901 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003902 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003903 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003904 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003905 }
3906 } else if (NonTypeTemplateParmDecl *NTTP
3907 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3908 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003909 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003910 diag::err_default_arg_in_partial_spec)
3911 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003912 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003913 }
3914 } else {
3915 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003916 if (TTP->hasDefaultArgument()) {
3917 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003918 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003919 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003920 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00003921 }
3922 }
3923 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003924 } else if (TemplateParams) {
3925 if (TUK == TUK_Friend)
3926 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003927 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003928 SourceRange(TemplateParams->getTemplateLoc(),
3929 TemplateParams->getRAngleLoc()))
3930 << SourceRange(LAngleLoc, RAngleLoc);
3931 else
3932 isExplicitSpecialization = true;
3933 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003934 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003935 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003936 isExplicitSpecialization = true;
3937 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003938
Douglas Gregor67a65642009-02-17 23:15:12 +00003939 // Check that the specialization uses the same tag kind as the
3940 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003941 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3942 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00003943 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003944 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003945 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003946 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003947 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003948 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003949 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003950 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003951 diag::note_previous_use);
3952 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3953 }
3954
Douglas Gregorc40290e2009-03-09 23:48:35 +00003955 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003956 TemplateArgumentListInfo TemplateArgs;
3957 TemplateArgs.setLAngleLoc(LAngleLoc);
3958 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003959 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003960
Douglas Gregor67a65642009-02-17 23:15:12 +00003961 // Check that the template argument list is well-formed for this
3962 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003963 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3964 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003965 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3966 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003967 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003968
Mike Stump11289f42009-09-09 15:08:12 +00003969 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003970 ClassTemplate->getTemplateParameters()->size()) &&
3971 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003972
Douglas Gregor2373c592009-05-31 09:31:02 +00003973 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003974 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00003975 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003976 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003977 if (CheckClassTemplatePartialSpecializationArgs(
3978 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003979 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003980 return true;
3981
Douglas Gregor09a30232009-06-12 22:08:06 +00003982 if (MirrorsPrimaryTemplate) {
3983 // C++ [temp.class.spec]p9b3:
3984 //
Mike Stump11289f42009-09-09 15:08:12 +00003985 // -- The argument list of the specialization shall not be identical
3986 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003987 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003988 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003989 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003990 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003991 ClassTemplate->getIdentifier(),
3992 TemplateNameLoc,
3993 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003994 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003995 AS_none);
3996 }
3997
Douglas Gregor2208a292009-09-26 20:57:03 +00003998 // FIXME: Diagnose friend partial specializations
3999
Douglas Gregor92354b62010-02-09 00:37:32 +00004000 if (!Name.isDependent() &&
4001 !TemplateSpecializationType::anyDependentTemplateArguments(
4002 TemplateArgs.getArgumentArray(),
4003 TemplateArgs.size())) {
4004 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4005 << ClassTemplate->getDeclName();
4006 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00004007 }
4008 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004009
Douglas Gregor67a65642009-02-17 23:15:12 +00004010 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00004011 ClassTemplateSpecializationDecl *PrevDecl = 0;
4012
4013 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004014 // FIXME: Template parameter list matters, too
Douglas Gregor2373c592009-05-31 09:31:02 +00004015 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004016 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
4017 Converted.flatSize(),
4018 InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00004019 else
4020 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004021 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4022 Converted.flatSize(), InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00004023
4024 ClassTemplateSpecializationDecl *Specialization = 0;
4025
Douglas Gregorf47b9112009-02-25 22:02:03 +00004026 // Check whether we can declare a class template specialization in
4027 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00004028 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00004029 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004030 TemplateNameLoc,
4031 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00004032 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004033
Douglas Gregor15301382009-07-30 17:40:51 +00004034 // The canonical type
4035 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00004036 if (PrevDecl &&
4037 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00004038 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00004039 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00004040 // arguments was referenced but not declared, or we're only
4041 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00004042 // declaration node as our own, updating its source location to
4043 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00004044 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00004045 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00004046 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00004047 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00004048 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00004049 // Build the canonical type that describes the converted template
4050 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00004051 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4052 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00004053 Converted.getFlatArguments(),
4054 Converted.flatSize());
4055
Douglas Gregor2373c592009-05-31 09:31:02 +00004056 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00004057 ClassTemplatePartialSpecializationDecl *PrevPartial
4058 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00004059 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004060 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump11289f42009-09-09 15:08:12 +00004061 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00004062 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00004063 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00004064 TemplateNameLoc,
4065 TemplateParams,
4066 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004067 Converted,
John McCall6b51f282009-11-23 01:53:49 +00004068 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00004069 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00004070 PrevPartial,
4071 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00004072 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00004073 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00004074 Partial->setTemplateParameterListsInfo(Context,
4075 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004076 (TemplateParameterList**) TemplateParameterLists.release());
4077 }
Douglas Gregor2373c592009-05-31 09:31:02 +00004078
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004079 if (!PrevPartial)
4080 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00004081 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00004082
Douglas Gregor21610382009-10-29 00:04:11 +00004083 // If we are providing an explicit specialization of a member class
4084 // template specialization, make a note of that.
4085 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4086 PrevPartial->setMemberSpecialization();
4087
Douglas Gregor91772d12009-06-13 00:26:55 +00004088 // Check that all of the template parameters of the class template
4089 // partial specialization are deducible from the template
4090 // arguments. If not, this class template partial specialization
4091 // will never be used.
4092 llvm::SmallVector<bool, 8> DeducibleParams;
4093 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004094 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00004095 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004096 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00004097 unsigned NumNonDeducible = 0;
4098 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
4099 if (!DeducibleParams[I])
4100 ++NumNonDeducible;
4101
4102 if (NumNonDeducible) {
4103 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
4104 << (NumNonDeducible > 1)
4105 << SourceRange(TemplateNameLoc, RAngleLoc);
4106 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4107 if (!DeducibleParams[I]) {
4108 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
4109 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00004110 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00004111 diag::note_partial_spec_unused_parameter)
4112 << Param->getDeclName();
4113 else
Mike Stump11289f42009-09-09 15:08:12 +00004114 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00004115 diag::note_partial_spec_unused_parameter)
Benjamin Kramere8394df2010-08-11 14:47:12 +00004116 << "<anonymous>";
Douglas Gregor91772d12009-06-13 00:26:55 +00004117 }
4118 }
4119 }
Douglas Gregor67a65642009-02-17 23:15:12 +00004120 } else {
4121 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00004122 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00004123 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004124 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00004125 ClassTemplate->getDeclContext(),
4126 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004127 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004128 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00004129 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004130 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00004131 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00004132 Specialization->setTemplateParameterListsInfo(Context,
4133 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004134 (TemplateParameterList**) TemplateParameterLists.release());
4135 }
Douglas Gregor67a65642009-02-17 23:15:12 +00004136
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004137 if (!PrevDecl)
4138 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00004139
4140 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00004141 }
4142
Douglas Gregor06db9f52009-10-12 20:18:28 +00004143 // C++ [temp.expl.spec]p6:
4144 // If a template, a member template or the member of a class template is
4145 // explicitly specialized then that specialization shall be declared
4146 // before the first use of that specialization that would cause an implicit
4147 // instantiation to take place, in every translation unit in which such a
4148 // use occurs; no diagnostic is required.
4149 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00004150 bool Okay = false;
4151 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4152 // Is there any previous explicit specialization declaration?
4153 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4154 Okay = true;
4155 break;
4156 }
4157 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00004158
Douglas Gregorc854c662010-02-26 06:03:23 +00004159 if (!Okay) {
4160 SourceRange Range(TemplateNameLoc, RAngleLoc);
4161 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4162 << Context.getTypeDeclType(Specialization) << Range;
4163
4164 Diag(PrevDecl->getPointOfInstantiation(),
4165 diag::note_instantiation_required_here)
4166 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00004167 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00004168 return true;
4169 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00004170 }
4171
Douglas Gregor2208a292009-09-26 20:57:03 +00004172 // If this is not a friend, note that this is an explicit specialization.
4173 if (TUK != TUK_Friend)
4174 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00004175
4176 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00004177 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004178 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00004179 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004180 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00004181 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00004182 Diag(Def->getLocation(), diag::note_previous_definition);
4183 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00004184 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00004185 }
4186 }
4187
Douglas Gregord56a91e2009-02-26 22:19:44 +00004188 // Build the fully-sugared type for this class template
4189 // specialization as the user wrote in the specialization
4190 // itself. This means that we'll pretty-print the type retrieved
4191 // from the specialization's declaration the way that the user
4192 // actually wrote the specialization, rather than formatting the
4193 // name based on the "canonical" representation used to store the
4194 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004195 TypeSourceInfo *WrittenTy
4196 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4197 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004198 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00004199 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregord890b732010-07-06 18:33:12 +00004200 if (TemplateParams)
4201 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnara8075c852010-06-12 07:44:57 +00004202 }
Douglas Gregorc40290e2009-03-09 23:48:35 +00004203 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00004204
Douglas Gregor1e249f82009-02-25 22:18:32 +00004205 // C++ [temp.expl.spec]p9:
4206 // A template explicit specialization is in the scope of the
4207 // namespace in which the template was defined.
4208 //
4209 // We actually implement this paragraph where we set the semantic
4210 // context (in the creation of the ClassTemplateSpecializationDecl),
4211 // but we also maintain the lexical context where the actual
4212 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00004213 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00004214
Douglas Gregor67a65642009-02-17 23:15:12 +00004215 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00004216 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00004217 Specialization->startDefinition();
4218
Douglas Gregor2208a292009-09-26 20:57:03 +00004219 if (TUK == TUK_Friend) {
4220 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4221 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00004222 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00004223 /*FIXME:*/KWLoc);
4224 Friend->setAccess(AS_public);
4225 CurContext->addDecl(Friend);
4226 } else {
4227 // Add the specialization into its lexical context, so that it can
4228 // be seen when iterating through the list of declarations in that
4229 // context. However, specializations are not found by name lookup.
4230 CurContext->addDecl(Specialization);
4231 }
John McCall48871652010-08-21 09:40:31 +00004232 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00004233}
Douglas Gregor333489b2009-03-27 23:10:48 +00004234
John McCall48871652010-08-21 09:40:31 +00004235Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004236 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004237 Declarator &D) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004238 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4239}
4240
John McCall48871652010-08-21 09:40:31 +00004241Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004242 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004243 Declarator &D) {
Douglas Gregor17a7c122009-06-24 00:54:41 +00004244 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4245 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4246 "Not a function declarator!");
4247 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00004248
Douglas Gregor17a7c122009-06-24 00:54:41 +00004249 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004250 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004251 }
Mike Stump11289f42009-09-09 15:08:12 +00004252
Douglas Gregor17a7c122009-06-24 00:54:41 +00004253 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004254
John McCall48871652010-08-21 09:40:31 +00004255 Decl *DP = HandleDeclarator(ParentScope, D,
4256 move(TemplateParameterLists),
4257 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004258 if (FunctionTemplateDecl *FunctionTemplate
John McCall48871652010-08-21 09:40:31 +00004259 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump11289f42009-09-09 15:08:12 +00004260 return ActOnStartOfFunctionDef(FnBodyScope,
John McCall48871652010-08-21 09:40:31 +00004261 FunctionTemplate->getTemplatedDecl());
4262 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4263 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4264 return 0;
Douglas Gregor17a7c122009-06-24 00:54:41 +00004265}
4266
John McCall4f7ced62010-02-11 01:33:53 +00004267/// \brief Strips various properties off an implicit instantiation
4268/// that has just been explicitly specialized.
4269static void StripImplicitInstantiation(NamedDecl *D) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004270 D->dropAttrs();
John McCall4f7ced62010-02-11 01:33:53 +00004271
4272 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4273 FD->setInlineSpecified(false);
4274 }
4275}
4276
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004277/// \brief Diagnose cases where we have an explicit template specialization
4278/// before/after an explicit template instantiation, producing diagnostics
4279/// for those cases where they are required and determining whether the
4280/// new specialization/instantiation will have any effect.
4281///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004282/// \param NewLoc the location of the new explicit specialization or
4283/// instantiation.
4284///
4285/// \param NewTSK the kind of the new explicit specialization or instantiation.
4286///
4287/// \param PrevDecl the previous declaration of the entity.
4288///
4289/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4290///
4291/// \param PrevPointOfInstantiation if valid, indicates where the previus
4292/// declaration was instantiated (either implicitly or explicitly).
4293///
Abramo Bagnara8075c852010-06-12 07:44:57 +00004294/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004295/// specialization or instantiation has no effect and should be ignored.
4296///
4297/// \returns true if there was an error that should prevent the introduction of
4298/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004299bool
4300Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4301 TemplateSpecializationKind NewTSK,
4302 NamedDecl *PrevDecl,
4303 TemplateSpecializationKind PrevTSK,
4304 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004305 bool &HasNoEffect) {
4306 HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004307
4308 switch (NewTSK) {
4309 case TSK_Undeclared:
4310 case TSK_ImplicitInstantiation:
4311 assert(false && "Don't check implicit instantiations here");
4312 return false;
4313
4314 case TSK_ExplicitSpecialization:
4315 switch (PrevTSK) {
4316 case TSK_Undeclared:
4317 case TSK_ExplicitSpecialization:
4318 // Okay, we're just specializing something that is either already
4319 // explicitly specialized or has merely been mentioned without any
4320 // instantiation.
4321 return false;
4322
4323 case TSK_ImplicitInstantiation:
4324 if (PrevPointOfInstantiation.isInvalid()) {
4325 // The declaration itself has not actually been instantiated, so it is
4326 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004327 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004328 return false;
4329 }
4330 // Fall through
4331
4332 case TSK_ExplicitInstantiationDeclaration:
4333 case TSK_ExplicitInstantiationDefinition:
4334 assert((PrevTSK == TSK_ImplicitInstantiation ||
4335 PrevPointOfInstantiation.isValid()) &&
4336 "Explicit instantiation without point of instantiation?");
4337
4338 // C++ [temp.expl.spec]p6:
4339 // If a template, a member template or the member of a class template
4340 // is explicitly specialized then that specialization shall be declared
4341 // before the first use of that specialization that would cause an
4342 // implicit instantiation to take place, in every translation unit in
4343 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004344 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4345 // Is there any previous explicit specialization declaration?
4346 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4347 return false;
4348 }
4349
Douglas Gregor1d957a32009-10-27 18:42:08 +00004350 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004351 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004352 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004353 << (PrevTSK != TSK_ImplicitInstantiation);
4354
4355 return true;
4356 }
4357 break;
4358
4359 case TSK_ExplicitInstantiationDeclaration:
4360 switch (PrevTSK) {
4361 case TSK_ExplicitInstantiationDeclaration:
4362 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00004363 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004364 return false;
4365
4366 case TSK_Undeclared:
4367 case TSK_ImplicitInstantiation:
4368 // We're explicitly instantiating something that may have already been
4369 // implicitly instantiated; that's fine.
4370 return false;
4371
4372 case TSK_ExplicitSpecialization:
4373 // C++0x [temp.explicit]p4:
4374 // For a given set of template parameters, if an explicit instantiation
4375 // of a template appears after a declaration of an explicit
4376 // specialization for that template, the explicit instantiation has no
4377 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00004378 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004379 return false;
4380
4381 case TSK_ExplicitInstantiationDefinition:
4382 // C++0x [temp.explicit]p10:
4383 // If an entity is the subject of both an explicit instantiation
4384 // declaration and an explicit instantiation definition in the same
4385 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004386 Diag(NewLoc,
4387 diag::err_explicit_instantiation_declaration_after_definition);
4388 Diag(PrevPointOfInstantiation,
4389 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004390 assert(PrevPointOfInstantiation.isValid() &&
4391 "Explicit instantiation without point of instantiation?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00004392 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004393 return false;
4394 }
4395 break;
4396
4397 case TSK_ExplicitInstantiationDefinition:
4398 switch (PrevTSK) {
4399 case TSK_Undeclared:
4400 case TSK_ImplicitInstantiation:
4401 // We're explicitly instantiating something that may have already been
4402 // implicitly instantiated; that's fine.
4403 return false;
4404
4405 case TSK_ExplicitSpecialization:
4406 // C++ DR 259, C++0x [temp.explicit]p4:
4407 // For a given set of template parameters, if an explicit
4408 // instantiation of a template appears after a declaration of
4409 // an explicit specialization for that template, the explicit
4410 // instantiation has no effect.
4411 //
4412 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004413 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004414 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004415 if (!getLangOptions().CPlusPlus0x) {
4416 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004417 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004418 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004419 diag::note_previous_template_specialization);
4420 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004421 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004422 return false;
4423
4424 case TSK_ExplicitInstantiationDeclaration:
4425 // We're explicity instantiating a definition for something for which we
4426 // were previously asked to suppress instantiations. That's fine.
4427 return false;
4428
4429 case TSK_ExplicitInstantiationDefinition:
4430 // C++0x [temp.spec]p5:
4431 // For a given template and a given set of template-arguments,
4432 // - an explicit instantiation definition shall appear at most once
4433 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004434 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004435 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004436 Diag(PrevPointOfInstantiation,
4437 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004438 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004439 return false;
4440 }
4441 break;
4442 }
4443
4444 assert(false && "Missing specialization/instantiation case?");
4445
4446 return false;
4447}
4448
John McCallb9c78482010-04-08 09:05:18 +00004449/// \brief Perform semantic analysis for the given dependent function
4450/// template specialization. The only possible way to get a dependent
4451/// function template specialization is with a friend declaration,
4452/// like so:
4453///
4454/// template <class T> void foo(T);
4455/// template <class T> class A {
4456/// friend void foo<>(T);
4457/// };
4458///
4459/// There really isn't any useful analysis we can do here, so we
4460/// just store the information.
4461bool
4462Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4463 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4464 LookupResult &Previous) {
4465 // Remove anything from Previous that isn't a function template in
4466 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00004467 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00004468 LookupResult::Filter F = Previous.makeFilter();
4469 while (F.hasNext()) {
4470 NamedDecl *D = F.next()->getUnderlyingDecl();
4471 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00004472 !FDLookupContext->InEnclosingNamespaceSetOf(
4473 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00004474 F.erase();
4475 }
4476 F.done();
4477
4478 // Should this be diagnosed here?
4479 if (Previous.empty()) return true;
4480
4481 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4482 ExplicitTemplateArgs);
4483 return false;
4484}
4485
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004486/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004487/// specialization.
4488///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004489/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004490/// explicit function template specialization. On successful completion,
4491/// the function declaration \p FD will become a function template
4492/// specialization.
4493///
4494/// \param FD the function declaration, which will be updated to become a
4495/// function template specialization.
4496///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004497/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4498/// if any. Note that this may be valid info even when 0 arguments are
4499/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4500/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004501///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004502/// \param PrevDecl the set of declarations that may be specialized by
4503/// this function specialization.
4504bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004505Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004506 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004507 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004508 // The set of function template specializations that could match this
4509 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004510 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004511
Sebastian Redl50c68252010-08-31 00:36:30 +00004512 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00004513 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4514 I != E; ++I) {
4515 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4516 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004517 // Only consider templates found within the same semantic lookup scope as
4518 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00004519 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4520 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004521 continue;
4522
4523 // C++ [temp.expl.spec]p11:
4524 // A trailing template-argument can be left unspecified in the
4525 // template-id naming an explicit function template specialization
4526 // provided it can be deduced from the function argument type.
4527 // Perform template argument deduction to determine whether we may be
4528 // specializing this template.
4529 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004530 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004531 FunctionDecl *Specialization = 0;
4532 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004533 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004534 FD->getType(),
4535 Specialization,
4536 Info)) {
4537 // FIXME: Template argument deduction failed; record why it failed, so
4538 // that we can provide nifty diagnostics.
4539 (void)TDK;
4540 continue;
4541 }
4542
4543 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004544 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004545 }
4546 }
4547
Douglas Gregor5de279c2009-09-26 03:41:46 +00004548 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004549 UnresolvedSetIterator Result
4550 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4551 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004552 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004553 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004554 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004555 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004556 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004557 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004558 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004559
4560 // Ignore access information; it doesn't figure into redeclaration checking.
4561 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004562 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004563
4564 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004565 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004566
4567 // If this is a friend declaration, then we're not really declaring
4568 // an explicit specialization.
4569 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004570
Douglas Gregor54888652009-10-07 00:13:32 +00004571 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004572 if (!isFriend &&
4573 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004574 Specialization->getPrimaryTemplate(),
4575 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004576 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004577 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004578
4579 // C++ [temp.expl.spec]p6:
4580 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004581 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004582 // before the first use of that specialization that would cause an implicit
4583 // instantiation to take place, in every translation unit in which such a
4584 // use occurs; no diagnostic is required.
4585 FunctionTemplateSpecializationInfo *SpecInfo
4586 = Specialization->getTemplateSpecializationInfo();
4587 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004588
Abramo Bagnara8075c852010-06-12 07:44:57 +00004589 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00004590 if (!isFriend &&
4591 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004592 TSK_ExplicitSpecialization,
4593 Specialization,
4594 SpecInfo->getTemplateSpecializationKind(),
4595 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004596 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004597 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004598
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004599 // Mark the prior declaration as an explicit specialization, so that later
4600 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004601 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00004602 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004603 MarkUnusedFileScopedDecl(Specialization);
4604 }
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004605
4606 // Turn the given function declaration into a function template
4607 // specialization, with the template arguments from the previous
4608 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004609 // Take copies of (semantic and syntactic) template argument lists.
4610 const TemplateArgumentList* TemplArgs = new (Context)
4611 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4612 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4613 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004614 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004615 TemplArgs, /*InsertPos=*/0,
4616 SpecInfo->getTemplateSpecializationKind(),
4617 TemplArgsAsWritten);
4618
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004619 // The "previous declaration" for this function template specialization is
4620 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004621 Previous.clear();
4622 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004623 return false;
4624}
4625
Douglas Gregor86d142a2009-10-08 07:24:58 +00004626/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004627/// specialization.
4628///
4629/// This routine performs all of the semantic analysis required for an
4630/// explicit member function specialization. On successful completion,
4631/// the function declaration \p FD will become a member function
4632/// specialization.
4633///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004634/// \param Member the member declaration, which will be updated to become a
4635/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004636///
John McCall1f82f242009-11-18 22:49:29 +00004637/// \param Previous the set of declarations, one of which may be specialized
4638/// by this function specialization; the set will be modified to contain the
4639/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004640bool
John McCall1f82f242009-11-18 22:49:29 +00004641Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004642 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004643
Douglas Gregor86d142a2009-10-08 07:24:58 +00004644 // Try to find the member we are instantiating.
4645 NamedDecl *Instantiation = 0;
4646 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004647 MemberSpecializationInfo *MSInfo = 0;
4648
John McCall1f82f242009-11-18 22:49:29 +00004649 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004650 // Nowhere to look anyway.
4651 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004652 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4653 I != E; ++I) {
4654 NamedDecl *D = (*I)->getUnderlyingDecl();
4655 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004656 if (Context.hasSameType(Function->getType(), Method->getType())) {
4657 Instantiation = Method;
4658 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004659 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004660 break;
4661 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004662 }
4663 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004664 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004665 VarDecl *PrevVar;
4666 if (Previous.isSingleResult() &&
4667 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004668 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004669 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004670 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004671 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004672 }
4673 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004674 CXXRecordDecl *PrevRecord;
4675 if (Previous.isSingleResult() &&
4676 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4677 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004678 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004679 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004680 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004681 }
4682
4683 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004684 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004685 // specializations are always out-of-line, the caller will complain about
4686 // this mismatch later.
4687 return false;
4688 }
John McCalle820e5e2010-04-13 20:37:33 +00004689
4690 // If this is a friend, just bail out here before we start turning
4691 // things into explicit specializations.
4692 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4693 // Preserve instantiation information.
4694 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4695 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4696 cast<CXXMethodDecl>(InstantiatedFrom),
4697 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4698 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4699 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4700 cast<CXXRecordDecl>(InstantiatedFrom),
4701 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4702 }
4703
4704 Previous.clear();
4705 Previous.addDecl(Instantiation);
4706 return false;
4707 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004708
Douglas Gregor86d142a2009-10-08 07:24:58 +00004709 // Make sure that this is a specialization of a member.
4710 if (!InstantiatedFrom) {
4711 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4712 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004713 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4714 return true;
4715 }
4716
Douglas Gregor06db9f52009-10-12 20:18:28 +00004717 // C++ [temp.expl.spec]p6:
4718 // If a template, a member template or the member of a class template is
4719 // explicitly specialized then that spe- cialization shall be declared
4720 // before the first use of that specialization that would cause an implicit
4721 // instantiation to take place, in every translation unit in which such a
4722 // use occurs; no diagnostic is required.
4723 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004724
Abramo Bagnara8075c852010-06-12 07:44:57 +00004725 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00004726 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4727 TSK_ExplicitSpecialization,
4728 Instantiation,
4729 MSInfo->getTemplateSpecializationKind(),
4730 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004731 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004732 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004733
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004734 // Check the scope of this explicit specialization.
4735 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004736 InstantiatedFrom,
4737 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004738 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004739 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004740
Douglas Gregor86d142a2009-10-08 07:24:58 +00004741 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004742 // the original declaration to note that it is an explicit specialization
4743 // (if it was previously an implicit instantiation). This latter step
4744 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004745 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004746 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4747 if (InstantiationFunction->getTemplateSpecializationKind() ==
4748 TSK_ImplicitInstantiation) {
4749 InstantiationFunction->setTemplateSpecializationKind(
4750 TSK_ExplicitSpecialization);
4751 InstantiationFunction->setLocation(Member->getLocation());
4752 }
4753
Douglas Gregor86d142a2009-10-08 07:24:58 +00004754 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4755 cast<CXXMethodDecl>(InstantiatedFrom),
4756 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004757 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004758 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004759 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4760 if (InstantiationVar->getTemplateSpecializationKind() ==
4761 TSK_ImplicitInstantiation) {
4762 InstantiationVar->setTemplateSpecializationKind(
4763 TSK_ExplicitSpecialization);
4764 InstantiationVar->setLocation(Member->getLocation());
4765 }
4766
Douglas Gregor86d142a2009-10-08 07:24:58 +00004767 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4768 cast<VarDecl>(InstantiatedFrom),
4769 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004770 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004771 } else {
4772 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004773 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4774 if (InstantiationClass->getTemplateSpecializationKind() ==
4775 TSK_ImplicitInstantiation) {
4776 InstantiationClass->setTemplateSpecializationKind(
4777 TSK_ExplicitSpecialization);
4778 InstantiationClass->setLocation(Member->getLocation());
4779 }
4780
Douglas Gregor86d142a2009-10-08 07:24:58 +00004781 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004782 cast<CXXRecordDecl>(InstantiatedFrom),
4783 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004784 }
4785
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004786 // Save the caller the trouble of having to figure out which declaration
4787 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004788 Previous.clear();
4789 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004790 return false;
4791}
4792
Douglas Gregore47f5a72009-10-14 23:41:34 +00004793/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004794///
4795/// \returns true if a serious error occurs, false otherwise.
4796static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00004797 SourceLocation InstLoc,
4798 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00004799 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
4800 DeclContext *CurContext = S.CurContext->getRedeclContext();
Douglas Gregore47f5a72009-10-14 23:41:34 +00004801
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004802 if (CurContext->isRecord()) {
4803 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4804 << D;
4805 return true;
4806 }
4807
Douglas Gregore47f5a72009-10-14 23:41:34 +00004808 // C++0x [temp.explicit]p2:
4809 // An explicit instantiation shall appear in an enclosing namespace of its
4810 // template.
4811 //
4812 // This is DR275, which we do not retroactively apply to C++98/03.
4813 if (S.getLangOptions().CPlusPlus0x &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004814 !CurContext->Encloses(OrigContext)) {
4815 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004816 S.Diag(InstLoc,
4817 S.getLangOptions().CPlusPlus0x?
4818 diag::err_explicit_instantiation_out_of_scope
4819 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004820 << D << NS;
4821 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004822 S.Diag(InstLoc,
4823 S.getLangOptions().CPlusPlus0x?
4824 diag::err_explicit_instantiation_must_be_global
4825 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004826 << D;
4827 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004828 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004829 }
Sebastian Redl50c68252010-08-31 00:36:30 +00004830
Douglas Gregore47f5a72009-10-14 23:41:34 +00004831 // C++0x [temp.explicit]p2:
4832 // If the name declared in the explicit instantiation is an unqualified
4833 // name, the explicit instantiation shall appear in the namespace where
4834 // its template is declared or, if that namespace is inline (7.3.1), any
4835 // namespace from its enclosing namespace set.
4836 if (WasQualifiedName)
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004837 return false;
Sebastian Redl50c68252010-08-31 00:36:30 +00004838
4839 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004840 return false;
Sebastian Redl50c68252010-08-31 00:36:30 +00004841
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004842 S.Diag(InstLoc,
4843 S.getLangOptions().CPlusPlus0x?
4844 diag::err_explicit_instantiation_unqualified_wrong_namespace
4845 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Sebastian Redl50c68252010-08-31 00:36:30 +00004846 << D << OrigContext;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004847 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004848 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004849}
4850
4851/// \brief Determine whether the given scope specifier has a template-id in it.
4852static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4853 if (!SS.isSet())
4854 return false;
4855
4856 // C++0x [temp.explicit]p2:
4857 // If the explicit instantiation is for a member function, a member class
4858 // or a static data member of a class template specialization, the name of
4859 // the class template specialization in the qualified-id for the member
4860 // name shall be a simple-template-id.
4861 //
4862 // C++98 has the same restriction, just worded differently.
4863 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4864 NNS; NNS = NNS->getPrefix())
4865 if (Type *T = NNS->getAsType())
4866 if (isa<TemplateSpecializationType>(T))
4867 return true;
4868
4869 return false;
4870}
4871
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004872// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00004873DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004874Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004875 SourceLocation ExternLoc,
4876 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004877 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004878 SourceLocation KWLoc,
4879 const CXXScopeSpec &SS,
4880 TemplateTy TemplateD,
4881 SourceLocation TemplateNameLoc,
4882 SourceLocation LAngleLoc,
4883 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004884 SourceLocation RAngleLoc,
4885 AttributeList *Attr) {
4886 // Find the class template we're specializing
4887 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004888 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004889 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4890
4891 // Check that the specialization uses the same tag kind as the
4892 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004893 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4894 assert(Kind != TTK_Enum &&
4895 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004896 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004897 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004898 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004899 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004900 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004901 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004902 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004903 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004904 diag::note_previous_use);
4905 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4906 }
4907
Douglas Gregore47f5a72009-10-14 23:41:34 +00004908 // C++0x [temp.explicit]p2:
4909 // There are two forms of explicit instantiation: an explicit instantiation
4910 // definition and an explicit instantiation declaration. An explicit
4911 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004912 TemplateSpecializationKind TSK
4913 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4914 : TSK_ExplicitInstantiationDeclaration;
4915
Douglas Gregora1f49972009-05-13 00:25:59 +00004916 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004917 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004918 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004919
4920 // Check that the template argument list is well-formed for this
4921 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004922 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4923 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004924 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4925 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004926 return true;
4927
Mike Stump11289f42009-09-09 15:08:12 +00004928 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004929 ClassTemplate->getTemplateParameters()->size()) &&
4930 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004931
Douglas Gregora1f49972009-05-13 00:25:59 +00004932 // Find the class template specialization declaration that
4933 // corresponds to these arguments.
Douglas Gregora1f49972009-05-13 00:25:59 +00004934 void *InsertPos = 0;
4935 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004936 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4937 Converted.flatSize(), InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004938
Abramo Bagnara8075c852010-06-12 07:44:57 +00004939 TemplateSpecializationKind PrevDecl_TSK
4940 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4941
Douglas Gregor54888652009-10-07 00:13:32 +00004942 // C++0x [temp.explicit]p2:
4943 // [...] An explicit instantiation shall appear in an enclosing
4944 // namespace of its template. [...]
4945 //
4946 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004947 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4948 SS.isSet()))
4949 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004950
Douglas Gregora1f49972009-05-13 00:25:59 +00004951 ClassTemplateSpecializationDecl *Specialization = 0;
4952
Douglas Gregor0681a352009-11-25 06:01:46 +00004953 bool ReusedDecl = false;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004954 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004955 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00004956 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004957 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004958 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004959 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00004960 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00004961
Abramo Bagnara8075c852010-06-12 07:44:57 +00004962 // Even though HasNoEffect == true means that this explicit instantiation
4963 // has no effect on semantics, we go on to put its syntax in the AST.
4964
4965 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4966 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004967 // Since the only prior class template specialization with these
4968 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00004969 // declaration node as our own, updating the source location
4970 // for the template name to reflect our new declaration.
4971 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004972 Specialization = PrevDecl;
4973 Specialization->setLocation(TemplateNameLoc);
4974 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004975 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004976 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004977 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004978
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004979 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004980 // Create a new class template specialization declaration node for
4981 // this explicit specialization.
4982 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004983 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00004984 ClassTemplate->getDeclContext(),
4985 TemplateNameLoc,
4986 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004987 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004988 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004989
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004990 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00004991 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004992 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004993 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004994 }
4995
4996 // Build the fully-sugared type for this explicit instantiation as
4997 // the user wrote in the explicit instantiation itself. This means
4998 // that we'll pretty-print the type retrieved from the
4999 // specialization's declaration the way that the user actually wrote
5000 // the explicit instantiation, rather than formatting the name based
5001 // on the "canonical" representation used to store the template
5002 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00005003 TypeSourceInfo *WrittenTy
5004 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5005 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00005006 Context.getTypeDeclType(Specialization));
5007 Specialization->setTypeAsWritten(WrittenTy);
5008 TemplateArgsIn.release();
5009
Abramo Bagnara8075c852010-06-12 07:44:57 +00005010 // Set source locations for keywords.
5011 Specialization->setExternLoc(ExternLoc);
5012 Specialization->setTemplateKeywordLoc(TemplateLoc);
5013
5014 // Add the explicit instantiation into its lexical context. However,
5015 // since explicit instantiations are never found by name lookup, we
5016 // just put it into the declaration context directly.
5017 Specialization->setLexicalDeclContext(CurContext);
5018 CurContext->addDecl(Specialization);
5019
5020 // Syntax is now OK, so return if it has no other effect on semantics.
5021 if (HasNoEffect) {
5022 // Set the template specialization kind.
5023 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00005024 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00005025 }
Douglas Gregora1f49972009-05-13 00:25:59 +00005026
5027 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00005028 // A definition of a class template or class member template
5029 // shall be in scope at the point of the explicit instantiation of
5030 // the class template or class member template.
5031 //
5032 // This check comes when we actually try to perform the
5033 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00005034 ClassTemplateSpecializationDecl *Def
5035 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005036 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00005037 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00005038 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00005039 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00005040 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00005041 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5042 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00005043
Douglas Gregor1d957a32009-10-27 18:42:08 +00005044 // Instantiate the members of this class template specialization.
5045 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005046 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00005047 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00005048 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5049
5050 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5051 // TSK_ExplicitInstantiationDefinition
5052 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5053 TSK == TSK_ExplicitInstantiationDefinition)
5054 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00005055
Douglas Gregor12e49d32009-10-15 22:53:21 +00005056 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00005057 }
Douglas Gregora1f49972009-05-13 00:25:59 +00005058
Abramo Bagnara8075c852010-06-12 07:44:57 +00005059 // Set the template specialization kind.
5060 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00005061 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00005062}
5063
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005064// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00005065DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00005066Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00005067 SourceLocation ExternLoc,
5068 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005069 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005070 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005071 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005072 IdentifierInfo *Name,
5073 SourceLocation NameLoc,
5074 AttributeList *Attr) {
5075
Douglas Gregord6ab8742009-05-28 23:31:59 +00005076 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00005077 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00005078 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00005079 KWLoc, SS, Name, NameLoc, Attr, AS_none,
5080 MultiTemplateParamsArg(*this, 0, 0),
Douglas Gregor0bf31402010-10-08 23:50:27 +00005081 Owned, IsDependent, false,
5082 TypeResult());
John McCall7f41d982009-09-11 04:59:25 +00005083 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
5084
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005085 if (!TagD)
5086 return true;
5087
John McCall48871652010-08-21 09:40:31 +00005088 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005089 if (Tag->isEnum()) {
5090 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
5091 << Context.getTypeDeclType(Tag);
5092 return true;
5093 }
5094
Douglas Gregorb8006faf2009-05-27 17:30:49 +00005095 if (Tag->isInvalidDecl())
5096 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005097
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005098 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
5099 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
5100 if (!Pattern) {
5101 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
5102 << Context.getTypeDeclType(Record);
5103 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
5104 return true;
5105 }
5106
Douglas Gregore47f5a72009-10-14 23:41:34 +00005107 // C++0x [temp.explicit]p2:
5108 // If the explicit instantiation is for a class or member class, the
5109 // elaborated-type-specifier in the declaration shall include a
5110 // simple-template-id.
5111 //
5112 // C++98 has the same restriction, just worded differently.
5113 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00005114 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005115 << Record << SS.getRange();
5116
5117 // C++0x [temp.explicit]p2:
5118 // There are two forms of explicit instantiation: an explicit instantiation
5119 // definition and an explicit instantiation declaration. An explicit
5120 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00005121 TemplateSpecializationKind TSK
5122 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5123 : TSK_ExplicitInstantiationDeclaration;
5124
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005125 // C++0x [temp.explicit]p2:
5126 // [...] An explicit instantiation shall appear in an enclosing
5127 // namespace of its template. [...]
5128 //
5129 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00005130 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005131
5132 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00005133 CXXRecordDecl *PrevDecl
5134 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005135 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00005136 PrevDecl = Record;
5137 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005138 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00005139 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005140 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00005141 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005142 PrevDecl,
5143 MSInfo->getTemplateSpecializationKind(),
5144 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005145 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005146 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005147 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005148 return TagD;
5149 }
5150
Douglas Gregor12e49d32009-10-15 22:53:21 +00005151 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005152 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00005153 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00005154 // C++ [temp.explicit]p3:
5155 // A definition of a member class of a class template shall be in scope
5156 // at the point of an explicit instantiation of the member class.
5157 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005158 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00005159 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00005160 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
5161 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00005162 Diag(Pattern->getLocation(), diag::note_forward_declaration)
5163 << Pattern;
5164 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005165 } else {
5166 if (InstantiateClass(NameLoc, Record, Def,
5167 getTemplateInstantiationArgs(Record),
5168 TSK))
5169 return true;
5170
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005171 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00005172 if (!RecordDef)
5173 return true;
5174 }
5175 }
5176
5177 // Instantiate all of the members of the class.
5178 InstantiateClassMembers(NameLoc, RecordDef,
5179 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005180
Douglas Gregor88d292c2010-05-13 16:44:06 +00005181 if (TSK == TSK_ExplicitInstantiationDefinition)
5182 MarkVTableUsed(NameLoc, RecordDef, true);
5183
Mike Stump87c57ac2009-05-16 07:39:55 +00005184 // FIXME: We don't have any representation for explicit instantiations of
5185 // member classes. Such a representation is not needed for compilation, but it
5186 // should be available for clients that want to see all of the declarations in
5187 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005188 return TagD;
5189}
5190
John McCallfaf5fb42010-08-26 23:41:50 +00005191DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
5192 SourceLocation ExternLoc,
5193 SourceLocation TemplateLoc,
5194 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005195 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005196 // TODO: check if/when DNInfo should replace Name.
5197 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5198 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00005199 if (!Name) {
5200 if (!D.isInvalidType())
5201 Diag(D.getDeclSpec().getSourceRange().getBegin(),
5202 diag::err_explicit_instantiation_requires_name)
5203 << D.getDeclSpec().getSourceRange()
5204 << D.getSourceRange();
5205
5206 return true;
5207 }
5208
5209 // The scope passed in may not be a decl scope. Zip up the scope tree until
5210 // we find one that is.
5211 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5212 (S->getFlags() & Scope::TemplateParamScope) != 0)
5213 S = S->getParent();
5214
5215 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00005216 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5217 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00005218 if (R.isNull())
5219 return true;
5220
5221 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5222 // Cannot explicitly instantiate a typedef.
5223 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5224 << Name;
5225 return true;
5226 }
5227
Douglas Gregor3c74d412009-10-14 20:14:33 +00005228 // C++0x [temp.explicit]p1:
5229 // [...] An explicit instantiation of a function template shall not use the
5230 // inline or constexpr specifiers.
5231 // Presumably, this also applies to member functions of class templates as
5232 // well.
5233 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5234 Diag(D.getDeclSpec().getInlineSpecLoc(),
5235 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00005236 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00005237
5238 // FIXME: check for constexpr specifier.
5239
Douglas Gregore47f5a72009-10-14 23:41:34 +00005240 // C++0x [temp.explicit]p2:
5241 // There are two forms of explicit instantiation: an explicit instantiation
5242 // definition and an explicit instantiation declaration. An explicit
5243 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00005244 TemplateSpecializationKind TSK
5245 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5246 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005247
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005248 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005249 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00005250
5251 if (!R->isFunctionType()) {
5252 // C++ [temp.explicit]p1:
5253 // A [...] static data member of a class template can be explicitly
5254 // instantiated from the member definition associated with its class
5255 // template.
John McCall27b18f82009-11-17 02:14:36 +00005256 if (Previous.isAmbiguous())
5257 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00005258
John McCall67c00872009-12-02 08:25:40 +00005259 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005260 if (!Prev || !Prev->isStaticDataMember()) {
5261 // We expect to see a data data member here.
5262 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5263 << Name;
5264 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5265 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005266 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005267 return true;
5268 }
5269
5270 if (!Prev->getInstantiatedFromStaticDataMember()) {
5271 // FIXME: Check for explicit specialization?
5272 Diag(D.getIdentifierLoc(),
5273 diag::err_explicit_instantiation_data_member_not_instantiated)
5274 << Prev;
5275 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5276 // FIXME: Can we provide a note showing where this was declared?
5277 return true;
5278 }
5279
Douglas Gregore47f5a72009-10-14 23:41:34 +00005280 // C++0x [temp.explicit]p2:
5281 // If the explicit instantiation is for a member function, a member class
5282 // or a static data member of a class template specialization, the name of
5283 // the class template specialization in the qualified-id for the member
5284 // name shall be a simple-template-id.
5285 //
5286 // C++98 has the same restriction, just worded differently.
5287 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5288 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005289 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005290 << Prev << D.getCXXScopeSpec().getRange();
5291
5292 // Check the scope of this explicit instantiation.
5293 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5294
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005295 // Verify that it is okay to explicitly instantiate here.
5296 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5297 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00005298 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005299 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005300 MSInfo->getTemplateSpecializationKind(),
5301 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005302 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005303 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005304 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005305 return (Decl*) 0;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005306
Douglas Gregor450f00842009-09-25 18:43:00 +00005307 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005308 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005309 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005310 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregor450f00842009-09-25 18:43:00 +00005311
5312 // FIXME: Create an ExplicitInstantiation node?
John McCall48871652010-08-21 09:40:31 +00005313 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005314 }
5315
Douglas Gregor0e876e02009-09-25 23:53:26 +00005316 // If the declarator is a template-id, translate the parser's template
5317 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005318 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005319 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005320 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5321 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005322 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5323 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005324 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5325 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005326 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005327 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005328 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005329 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005330 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005331
Douglas Gregor450f00842009-09-25 18:43:00 +00005332 // C++ [temp.explicit]p1:
5333 // A [...] function [...] can be explicitly instantiated from its template.
5334 // A member function [...] of a class template can be explicitly
5335 // instantiated from the member definition associated with its class
5336 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005337 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005338 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5339 P != PEnd; ++P) {
5340 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005341 if (!HasExplicitTemplateArgs) {
5342 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5343 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5344 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005345
John McCall58cc69d2010-01-27 01:50:18 +00005346 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005347 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5348 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005349 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005350 }
5351 }
5352
5353 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5354 if (!FunTmpl)
5355 continue;
5356
John McCallbc077cf2010-02-08 23:07:23 +00005357 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005358 FunctionDecl *Specialization = 0;
5359 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005360 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005361 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005362 R, Specialization, Info)) {
5363 // FIXME: Keep track of almost-matches?
5364 (void)TDK;
5365 continue;
5366 }
5367
John McCall58cc69d2010-01-27 01:50:18 +00005368 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005369 }
5370
5371 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005372 UnresolvedSetIterator Result
5373 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005374 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005375 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5376 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5377 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005378
John McCall58cc69d2010-01-27 01:50:18 +00005379 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005380 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005381
5382 // Ignore access control bits, we don't need them for redeclaration checking.
5383 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005384
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005385 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005386 Diag(D.getIdentifierLoc(),
5387 diag::err_explicit_instantiation_member_function_not_instantiated)
5388 << Specialization
5389 << (Specialization->getTemplateSpecializationKind() ==
5390 TSK_ExplicitSpecialization);
5391 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5392 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005393 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005394
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005395 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005396 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5397 PrevDecl = Specialization;
5398
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005399 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005400 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005401 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005402 PrevDecl,
5403 PrevDecl->getTemplateSpecializationKind(),
5404 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005405 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005406 return true;
5407
5408 // FIXME: We may still want to build some representation of this
5409 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00005410 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005411 return (Decl*) 0;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005412 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005413
5414 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005415
5416 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005417 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005418
Douglas Gregore47f5a72009-10-14 23:41:34 +00005419 // C++0x [temp.explicit]p2:
5420 // If the explicit instantiation is for a member function, a member class
5421 // or a static data member of a class template specialization, the name of
5422 // the class template specialization in the qualified-id for the member
5423 // name shall be a simple-template-id.
5424 //
5425 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005426 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005427 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005428 D.getCXXScopeSpec().isSet() &&
5429 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5430 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005431 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005432 << Specialization << D.getCXXScopeSpec().getRange();
5433
5434 CheckExplicitInstantiationScope(*this,
5435 FunTmpl? (NamedDecl *)FunTmpl
5436 : Specialization->getInstantiatedFromMemberFunction(),
5437 D.getIdentifierLoc(),
5438 D.getCXXScopeSpec().isSet());
5439
Douglas Gregor450f00842009-09-25 18:43:00 +00005440 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCall48871652010-08-21 09:40:31 +00005441 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005442}
5443
John McCallfaf5fb42010-08-26 23:41:50 +00005444TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005445Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5446 const CXXScopeSpec &SS, IdentifierInfo *Name,
5447 SourceLocation TagLoc, SourceLocation NameLoc) {
5448 // This has to hold, because SS is expected to be defined.
5449 assert(Name && "Expected a name in a dependent tag");
5450
5451 NestedNameSpecifier *NNS
5452 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5453 if (!NNS)
5454 return true;
5455
Abramo Bagnara6150c882010-05-11 21:36:43 +00005456 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005457
Douglas Gregorba41d012010-04-24 16:38:41 +00005458 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5459 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005460 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005461 return true;
5462 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005463
5464 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallba7bf592010-08-24 05:47:05 +00005465 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCall7f41d982009-09-11 04:59:25 +00005466}
5467
John McCallfaf5fb42010-08-26 23:41:50 +00005468TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005469Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5470 const CXXScopeSpec &SS, const IdentifierInfo &II,
5471 SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005472 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005473 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5474 if (!NNS)
5475 return true;
5476
Douglas Gregorf7d77712010-06-16 22:31:08 +00005477 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5478 !getLangOptions().CPlusPlus0x)
5479 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5480 << FixItHint::CreateRemoval(TypenameLoc);
5481
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005482 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005483 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005484 if (T.isNull())
5485 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005486
5487 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5488 if (isa<DependentNameType>(T)) {
5489 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005490 TL.setKeywordLoc(TypenameLoc);
5491 TL.setQualifierRange(SS.getRange());
5492 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005493 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005494 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005495 TL.setKeywordLoc(TypenameLoc);
5496 TL.setQualifierRange(SS.getRange());
5497 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005498 }
5499
John McCallba7bf592010-08-24 05:47:05 +00005500 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00005501}
5502
John McCallfaf5fb42010-08-26 23:41:50 +00005503TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005504Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5505 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallba7bf592010-08-24 05:47:05 +00005506 ParsedType Ty) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00005507 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5508 !getLangOptions().CPlusPlus0x)
5509 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5510 << FixItHint::CreateRemoval(TypenameLoc);
5511
John McCallf7bcc812010-05-28 23:32:21 +00005512 TypeSourceInfo *InnerTSI = 0;
5513 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCallf7bcc812010-05-28 23:32:21 +00005514
5515 assert(isa<TemplateSpecializationType>(T) &&
5516 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005517
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005518 if (computeDeclContext(SS, false)) {
5519 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005520 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005521 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005522
5523 // Push the inner type, preserving its source locations if possible.
5524 TypeLocBuilder Builder;
5525 if (InnerTSI)
5526 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5527 else
5528 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5529
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005530 /* Note: NNS already embedded in template specialization type T. */
5531 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCallf7bcc812010-05-28 23:32:21 +00005532 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5533 TL.setKeywordLoc(TypenameLoc);
5534 TL.setQualifierRange(SS.getRange());
5535
5536 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallba7bf592010-08-24 05:47:05 +00005537 return CreateParsedType(T, TSI);
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005538 }
Mike Stump11289f42009-09-09 15:08:12 +00005539
John McCallc392f372010-06-11 00:33:02 +00005540 // TODO: it's really silly that we make a template specialization
5541 // type earlier only to drop it again here.
5542 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5543 DependentTemplateName *DTN =
5544 TST->getTemplateName().getAsDependentTemplateName();
5545 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005546 assert(DTN->getQualifier()
5547 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5548 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5549 DTN->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00005550 DTN->getIdentifier(),
5551 TST->getNumArgs(),
5552 TST->getArgs());
John McCall99b2fe52010-04-29 23:50:39 +00005553 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCallc392f372010-06-11 00:33:02 +00005554 DependentTemplateSpecializationTypeLoc TL =
5555 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5556 if (InnerTSI) {
5557 TemplateSpecializationTypeLoc TSTL =
5558 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5559 TL.setLAngleLoc(TSTL.getLAngleLoc());
5560 TL.setRAngleLoc(TSTL.getRAngleLoc());
5561 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5562 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5563 } else {
5564 TL.initializeLocal(SourceLocation());
5565 }
John McCallf7bcc812010-05-28 23:32:21 +00005566 TL.setKeywordLoc(TypenameLoc);
5567 TL.setQualifierRange(SS.getRange());
John McCallba7bf592010-08-24 05:47:05 +00005568 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00005569}
5570
Douglas Gregor333489b2009-03-27 23:10:48 +00005571/// \brief Build the type that describes a C++ typename specifier,
5572/// e.g., "typename T::type".
5573QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005574Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5575 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005576 SourceLocation KeywordLoc, SourceRange NNSRange,
5577 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005578 CXXScopeSpec SS;
5579 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005580 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005581
John McCall0b66eb32010-05-01 00:40:08 +00005582 DeclContext *Ctx = computeDeclContext(SS);
5583 if (!Ctx) {
5584 // If the nested-name-specifier is dependent and couldn't be
5585 // resolved to a type, build a typename type.
5586 assert(NNS->isDependent());
5587 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005588 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005589
John McCall0b66eb32010-05-01 00:40:08 +00005590 // If the nested-name-specifier refers to the current instantiation,
5591 // the "typename" keyword itself is superfluous. In C++03, the
5592 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5593 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00005594 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005595
John McCall0b66eb32010-05-01 00:40:08 +00005596 if (RequireCompleteDeclContext(SS, Ctx))
5597 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005598
5599 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005600 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005601 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005602 unsigned DiagID = 0;
5603 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005604 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005605 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005606 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005607 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005608
5609 case LookupResult::NotFoundInCurrentInstantiation:
5610 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005611 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005612
5613 case LookupResult::Found:
Douglas Gregorf7d77712010-06-16 22:31:08 +00005614 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005615 // We found a type. Build an ElaboratedType, since the
5616 // typename-specifier was just sugar.
5617 return Context.getElaboratedType(ETK_Typename, NNS,
5618 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005619 }
5620
5621 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005622 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005623 break;
5624
John McCalle61f2ba2009-11-18 02:36:19 +00005625 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005626 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005627 return QualType();
5628
Douglas Gregor333489b2009-03-27 23:10:48 +00005629 case LookupResult::FoundOverloaded:
5630 DiagID = diag::err_typename_nested_not_type;
5631 Referenced = *Result.begin();
5632 break;
5633
John McCall6538c932009-10-10 05:48:19 +00005634 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005635 return QualType();
5636 }
5637
5638 // If we get here, it's because name lookup did not find a
5639 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005640 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5641 IILoc);
5642 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005643 if (Referenced)
5644 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5645 << Name;
5646 return QualType();
5647}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005648
5649namespace {
5650 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005651 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005652 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005653 SourceLocation Loc;
5654 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005655
Douglas Gregor15acfb92009-08-06 16:20:37 +00005656 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005657 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5658
Mike Stump11289f42009-09-09 15:08:12 +00005659 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005660 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005661 DeclarationName Entity)
5662 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005663 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005664
5665 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005666 /// transformed.
5667 ///
5668 /// For the purposes of type reconstruction, a type has already been
5669 /// transformed if it is NULL or if it is not dependent.
5670 bool AlreadyTransformed(QualType T) {
5671 return T.isNull() || !T->isDependentType();
5672 }
Mike Stump11289f42009-09-09 15:08:12 +00005673
5674 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005675 /// rebuilt.
5676 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005677
Douglas Gregor15acfb92009-08-06 16:20:37 +00005678 /// \brief Returns the name of the entity whose type is being rebuilt.
5679 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005680
Douglas Gregoref6ab412009-10-27 06:26:26 +00005681 /// \brief Sets the "base" location and entity when that
5682 /// information is known based on another transformation.
5683 void setBase(SourceLocation Loc, DeclarationName Entity) {
5684 this->Loc = Loc;
5685 this->Entity = Entity;
5686 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00005687 };
5688}
5689
Douglas Gregor15acfb92009-08-06 16:20:37 +00005690/// \brief Rebuilds a type within the context of the current instantiation.
5691///
Mike Stump11289f42009-09-09 15:08:12 +00005692/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005693/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005694/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005695/// partial specialization thereof). This routine will rebuild that type now
5696/// that we have entered the declarator's scope, which may produce different
5697/// canonical types, e.g.,
5698///
5699/// \code
5700/// template<typename T>
5701/// struct X {
5702/// typedef T* pointer;
5703/// pointer data();
5704/// };
5705///
5706/// template<typename T>
5707/// typename X<T>::pointer X<T>::data() { ... }
5708/// \endcode
5709///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005710/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005711/// since we do not know that we can look into X<T> when we parsed the type.
5712/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005713/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005714/// as the canonical type of T*, allowing the return types of the out-of-line
5715/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005716TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5717 SourceLocation Loc,
5718 DeclarationName Name) {
5719 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005720 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005721
Douglas Gregor15acfb92009-08-06 16:20:37 +00005722 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5723 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005724}
Douglas Gregorbe999392009-09-15 16:23:51 +00005725
John McCalldadc5752010-08-24 06:29:42 +00005726ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00005727 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5728 DeclarationName());
5729 return Rebuilder.TransformExpr(E);
5730}
5731
John McCall99b2fe52010-04-29 23:50:39 +00005732bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5733 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005734
5735 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5736 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5737 DeclarationName());
5738 NestedNameSpecifier *Rebuilt =
5739 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005740 if (!Rebuilt) return true;
5741
5742 SS.setScopeRep(Rebuilt);
5743 return false;
John McCall2408e322010-04-27 00:57:59 +00005744}
5745
Douglas Gregorbe999392009-09-15 16:23:51 +00005746/// \brief Produces a formatted string that describes the binding of
5747/// template parameters to template arguments.
5748std::string
5749Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5750 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005751 // FIXME: For variadic templates, we'll need to get the structured list.
5752 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5753 Args.flat_size());
5754}
5755
5756std::string
5757Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5758 const TemplateArgument *Args,
5759 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005760 std::string Result;
5761
Douglas Gregore62e6a02009-11-11 19:13:48 +00005762 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005763 return Result;
5764
5765 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005766 if (I >= NumArgs)
5767 break;
5768
Douglas Gregorbe999392009-09-15 16:23:51 +00005769 if (I == 0)
5770 Result += "[with ";
5771 else
5772 Result += ", ";
5773
5774 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5775 Result += Id->getName();
5776 } else {
5777 Result += '$';
5778 Result += llvm::utostr(I);
5779 }
5780
5781 Result += " = ";
5782
5783 switch (Args[I].getKind()) {
5784 case TemplateArgument::Null:
5785 Result += "<no value>";
5786 break;
5787
5788 case TemplateArgument::Type: {
5789 std::string TypeStr;
5790 Args[I].getAsType().getAsStringInternal(TypeStr,
5791 Context.PrintingPolicy);
5792 Result += TypeStr;
5793 break;
5794 }
5795
5796 case TemplateArgument::Declaration: {
5797 bool Unnamed = true;
5798 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5799 if (ND->getDeclName()) {
5800 Unnamed = false;
5801 Result += ND->getNameAsString();
5802 }
5803 }
5804
5805 if (Unnamed) {
5806 Result += "<anonymous>";
5807 }
5808 break;
5809 }
5810
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005811 case TemplateArgument::Template: {
5812 std::string Str;
5813 llvm::raw_string_ostream OS(Str);
5814 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5815 Result += OS.str();
5816 break;
5817 }
5818
Douglas Gregorbe999392009-09-15 16:23:51 +00005819 case TemplateArgument::Integral: {
5820 Result += Args[I].getAsIntegral()->toString(10);
5821 break;
5822 }
5823
5824 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005825 // FIXME: This is non-optimal, since we're regurgitating the
5826 // expression we were given.
5827 std::string Str;
5828 {
5829 llvm::raw_string_ostream OS(Str);
5830 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5831 Context.PrintingPolicy);
5832 }
5833 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005834 break;
5835 }
5836
5837 case TemplateArgument::Pack:
5838 // FIXME: Format template argument packs
5839 Result += "<template argument pack>";
5840 break;
5841 }
5842 }
5843
5844 Result += ']';
5845 return Result;
5846}