blob: f85c3f00709e64172271f88c650f1f59a9f2d9fe [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 }
Fariborz Jahanian26d1e2b2010-10-13 16:19:16 +00002557 return false;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00002558}
2559
2560
Douglas Gregord32e0282009-02-09 23:23:08 +00002561/// \brief Check a template argument against its corresponding
2562/// template type parameter.
2563///
2564/// This routine implements the semantics of C++ [temp.arg.type]. It
2565/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002566bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002567 TypeSourceInfo *ArgInfo) {
2568 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002569 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00002570 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00002571
2572 if (Arg->isVariablyModifiedType()) {
2573 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002574 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002575 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002576 }
2577
Douglas Gregor7731d3f2010-10-13 00:27:52 +00002578 // C++03 [temp.arg.type]p2:
2579 // A local type, a type with no linkage, an unnamed type or a type
2580 // compounded from any of these types shall not be used as a
2581 // template-argument for a template type-parameter.
2582 //
2583 // C++0x allows these, and even in C++03 we allow them as an extension with
2584 // a warning.
Douglas Gregor52051cb2010-10-13 18:05:20 +00002585 if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00002586 UnnamedLocalNoLinkageFinder Finder(*this, SR);
2587 (void)Finder.Visit(Context.getCanonicalType(Arg));
2588 }
2589
Douglas Gregord32e0282009-02-09 23:23:08 +00002590 return false;
2591}
2592
Douglas Gregorccb07762009-02-11 19:52:55 +00002593/// \brief Checks whether the given template argument is the address
2594/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002595static bool
2596CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2597 NonTypeTemplateParmDecl *Param,
2598 QualType ParamType,
2599 Expr *ArgIn,
2600 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002601 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002602 Expr *Arg = ArgIn;
2603 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002604
2605 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002606 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002607 Arg = Cast->getSubExpr();
2608
2609 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002610 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002611 // A template-argument for a non-type, non-template
2612 // template-parameter shall be one of: [...]
2613 //
2614 // -- the address of an object or function with external
2615 // linkage, including function templates and function
2616 // template-ids but excluding non-static class members,
2617 // expressed as & id-expression where the & is optional if
2618 // the name refers to a function or array, or if the
2619 // corresponding template-parameter is a reference; or
2620 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002621
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002622 // In C++98/03 mode, give an extension warning on any extra parentheses.
2623 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2624 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002625 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002626 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002627 S.Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002628 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002629 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002630 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002631 }
2632
2633 Arg = Parens->getSubExpr();
2634 }
2635
Douglas Gregorb242683d2010-04-01 18:32:35 +00002636 bool AddressTaken = false;
2637 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002638 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00002639 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002640 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002641 AddressTaken = true;
2642 AddrOpLoc = UnOp->getOperatorLoc();
2643 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002644 } else
2645 DRE = dyn_cast<DeclRefExpr>(Arg);
2646
Douglas Gregorb242683d2010-04-01 18:32:35 +00002647 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002648 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2649 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002650 S.Diag(Param->getLocation(), diag::note_template_param_here);
2651 return true;
2652 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002653
2654 // Stop checking the precise nature of the argument if it is value dependent,
2655 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002656 if (Arg->isValueDependent()) {
2657 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002658 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002659 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002660
Douglas Gregorb242683d2010-04-01 18:32:35 +00002661 if (!isa<ValueDecl>(DRE->getDecl())) {
2662 S.Diag(Arg->getSourceRange().getBegin(),
2663 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002664 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002665 S.Diag(Param->getLocation(), diag::note_template_param_here);
2666 return true;
2667 }
2668
2669 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002670
2671 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002672 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2673 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002674 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002675 S.Diag(Param->getLocation(), diag::note_template_param_here);
2676 return true;
2677 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002678
2679 // Cannot refer to non-static member functions
2680 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002681 if (!Method->isStatic()) {
2682 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002683 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002684 S.Diag(Param->getLocation(), diag::note_template_param_here);
2685 return true;
2686 }
Mike Stump11289f42009-09-09 15:08:12 +00002687
Douglas Gregorccb07762009-02-11 19:52:55 +00002688 // Functions must have external linkage.
2689 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002690 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002691 S.Diag(Arg->getSourceRange().getBegin(),
2692 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002693 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002694 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002695 << true;
2696 return true;
2697 }
2698
2699 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002700 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002701
Douglas Gregorb242683d2010-04-01 18:32:35 +00002702 // If the template parameter has pointer type, the function decays.
2703 if (ParamType->isPointerType() && !AddressTaken)
2704 ArgType = S.Context.getPointerType(Func->getType());
2705 else if (AddressTaken && ParamType->isReferenceType()) {
2706 // If we originally had an address-of operator, but the
2707 // parameter has reference type, complain and (if things look
2708 // like they will work) drop the address-of operator.
2709 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2710 ParamType.getNonReferenceType())) {
2711 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2712 << ParamType;
2713 S.Diag(Param->getLocation(), diag::note_template_param_here);
2714 return true;
2715 }
2716
2717 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2718 << ParamType
2719 << FixItHint::CreateRemoval(AddrOpLoc);
2720 S.Diag(Param->getLocation(), diag::note_template_param_here);
2721
2722 ArgType = Func->getType();
2723 }
2724 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002725 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002726 S.Diag(Arg->getSourceRange().getBegin(),
2727 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002728 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002729 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002730 << true;
2731 return true;
2732 }
2733
Douglas Gregorb242683d2010-04-01 18:32:35 +00002734 // A value of reference type is not an object.
2735 if (Var->getType()->isReferenceType()) {
2736 S.Diag(Arg->getSourceRange().getBegin(),
2737 diag::err_template_arg_reference_var)
2738 << Var->getType() << Arg->getSourceRange();
2739 S.Diag(Param->getLocation(), diag::note_template_param_here);
2740 return true;
2741 }
2742
Douglas Gregorccb07762009-02-11 19:52:55 +00002743 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002744 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002745
2746 // If the template parameter has pointer type, we must have taken
2747 // the address of this object.
2748 if (ParamType->isReferenceType()) {
2749 if (AddressTaken) {
2750 // If we originally had an address-of operator, but the
2751 // parameter has reference type, complain and (if things look
2752 // like they will work) drop the address-of operator.
2753 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2754 ParamType.getNonReferenceType())) {
2755 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2756 << ParamType;
2757 S.Diag(Param->getLocation(), diag::note_template_param_here);
2758 return true;
2759 }
2760
2761 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2762 << ParamType
2763 << FixItHint::CreateRemoval(AddrOpLoc);
2764 S.Diag(Param->getLocation(), diag::note_template_param_here);
2765
2766 ArgType = Var->getType();
2767 }
2768 } else if (!AddressTaken && ParamType->isPointerType()) {
2769 if (Var->getType()->isArrayType()) {
2770 // Array-to-pointer decay.
2771 ArgType = S.Context.getArrayDecayedType(Var->getType());
2772 } else {
2773 // If the template parameter has pointer type but the address of
2774 // this object was not taken, complain and (possibly) recover by
2775 // taking the address of the entity.
2776 ArgType = S.Context.getPointerType(Var->getType());
2777 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2778 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2779 << ParamType;
2780 S.Diag(Param->getLocation(), diag::note_template_param_here);
2781 return true;
2782 }
2783
2784 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2785 << ParamType
2786 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2787
2788 S.Diag(Param->getLocation(), diag::note_template_param_here);
2789 }
2790 }
2791 } else {
2792 // We found something else, but we don't know specifically what it is.
2793 S.Diag(Arg->getSourceRange().getBegin(),
2794 diag::err_template_arg_not_object_or_func)
2795 << Arg->getSourceRange();
2796 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2797 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002798 }
Mike Stump11289f42009-09-09 15:08:12 +00002799
Douglas Gregorb242683d2010-04-01 18:32:35 +00002800 if (ParamType->isPointerType() &&
2801 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2802 S.IsQualificationConversion(ArgType, ParamType)) {
2803 // For pointer-to-object types, qualification conversions are
2804 // permitted.
2805 } else {
2806 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2807 if (!ParamRef->getPointeeType()->isFunctionType()) {
2808 // C++ [temp.arg.nontype]p5b3:
2809 // For a non-type template-parameter of type reference to
2810 // object, no conversions apply. The type referred to by the
2811 // reference may be more cv-qualified than the (otherwise
2812 // identical) type of the template- argument. The
2813 // template-parameter is bound directly to the
2814 // template-argument, which shall be an lvalue.
2815
2816 // FIXME: Other qualifiers?
2817 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2818 unsigned ArgQuals = ArgType.getCVRQualifiers();
2819
2820 if ((ParamQuals | ArgQuals) != ParamQuals) {
2821 S.Diag(Arg->getSourceRange().getBegin(),
2822 diag::err_template_arg_ref_bind_ignores_quals)
2823 << ParamType << Arg->getType()
2824 << Arg->getSourceRange();
2825 S.Diag(Param->getLocation(), diag::note_template_param_here);
2826 return true;
2827 }
2828 }
2829 }
2830
2831 // At this point, the template argument refers to an object or
2832 // function with external linkage. We now need to check whether the
2833 // argument and parameter types are compatible.
2834 if (!S.Context.hasSameUnqualifiedType(ArgType,
2835 ParamType.getNonReferenceType())) {
2836 // We can't perform this conversion or binding.
2837 if (ParamType->isReferenceType())
2838 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2839 << ParamType << Arg->getType() << Arg->getSourceRange();
2840 else
2841 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2842 << Arg->getType() << ParamType << Arg->getSourceRange();
2843 S.Diag(Param->getLocation(), diag::note_template_param_here);
2844 return true;
2845 }
2846 }
2847
2848 // Create the template argument.
2849 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002850 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002851 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002852}
2853
2854/// \brief Checks whether the given template argument is a pointer to
2855/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002856bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2857 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002858 bool Invalid = false;
2859
2860 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002861 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002862 Arg = Cast->getSubExpr();
2863
2864 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002865 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002866 // A template-argument for a non-type, non-template
2867 // template-parameter shall be one of: [...]
2868 //
2869 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002870 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002871
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002872 // In C++98/03 mode, give an extension warning on any extra parentheses.
2873 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2874 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002875 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002876 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00002877 Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002878 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002879 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002880 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002881 }
2882
2883 Arg = Parens->getSubExpr();
2884 }
2885
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002886 // A pointer-to-member constant written &Class::member.
2887 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00002888 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002889 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2890 if (DRE && !DRE->getQualifier())
2891 DRE = 0;
2892 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002893 }
2894 // A constant of pointer-to-member type.
2895 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2896 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2897 if (VD->getType()->isMemberPointerType()) {
2898 if (isa<NonTypeTemplateParmDecl>(VD) ||
2899 (isa<VarDecl>(VD) &&
2900 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2901 if (Arg->isTypeDependent() || Arg->isValueDependent())
2902 Converted = TemplateArgument(Arg->Retain());
2903 else
2904 Converted = TemplateArgument(VD->getCanonicalDecl());
2905 return Invalid;
2906 }
2907 }
2908 }
2909
2910 DRE = 0;
2911 }
2912
Douglas Gregorccb07762009-02-11 19:52:55 +00002913 if (!DRE)
2914 return Diag(Arg->getSourceRange().getBegin(),
2915 diag::err_template_arg_not_pointer_to_member_form)
2916 << Arg->getSourceRange();
2917
2918 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2919 assert((isa<FieldDecl>(DRE->getDecl()) ||
2920 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2921 "Only non-static member pointers can make it here");
2922
2923 // Okay: this is the address of a non-static member, and therefore
2924 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002925 if (Arg->isTypeDependent() || Arg->isValueDependent())
2926 Converted = TemplateArgument(Arg->Retain());
2927 else
2928 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002929 return Invalid;
2930 }
2931
2932 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002933 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002934 diag::err_template_arg_not_pointer_to_member_form)
2935 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002936 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002937 diag::note_template_arg_refers_here);
2938 return true;
2939}
2940
Douglas Gregord32e0282009-02-09 23:23:08 +00002941/// \brief Check a template argument against its corresponding
2942/// non-type template parameter.
2943///
Douglas Gregor463421d2009-03-03 04:44:36 +00002944/// This routine implements the semantics of C++ [temp.arg.nontype].
2945/// It returns true if an error occurred, and false otherwise. \p
2946/// InstantiatedParamType is the type of the non-type template
2947/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002948///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002949/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002950bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002951 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002952 TemplateArgument &Converted,
2953 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002954 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2955
Douglas Gregor86560402009-02-10 23:36:10 +00002956 // If either the parameter has a dependent type or the argument is
2957 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002958 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2959 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002960 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002961 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002962 }
Douglas Gregor86560402009-02-10 23:36:10 +00002963
2964 // C++ [temp.arg.nontype]p5:
2965 // The following conversions are performed on each expression used
2966 // as a non-type template-argument. If a non-type
2967 // template-argument cannot be converted to the type of the
2968 // corresponding template-parameter then the program is
2969 // ill-formed.
2970 //
2971 // -- for a non-type template-parameter of integral or
2972 // enumeration type, integral promotions (4.5) and integral
2973 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002974 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002975 QualType ArgType = Arg->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +00002976 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002977 // C++ [temp.arg.nontype]p1:
2978 // A template-argument for a non-type, non-template
2979 // template-parameter shall be one of:
2980 //
2981 // -- an integral constant-expression of integral or enumeration
2982 // type; or
2983 // -- the name of a non-type template-parameter; or
2984 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002985 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00002986 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002987 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002988 diag::err_template_arg_not_integral_or_enumeral)
2989 << ArgType << Arg->getSourceRange();
2990 Diag(Param->getLocation(), diag::note_template_param_here);
2991 return true;
2992 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002993 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002994 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2995 << ArgType << Arg->getSourceRange();
2996 return true;
2997 }
2998
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002999 // From here on out, all we care about are the unqualified forms
3000 // of the parameter and argument types.
3001 ParamType = ParamType.getUnqualifiedType();
3002 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00003003
3004 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00003005 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00003006 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003007 } else if (CTAK == CTAK_Deduced) {
3008 // C++ [temp.deduct.type]p17:
3009 // If, in the declaration of a function template with a non-type
3010 // template-parameter, the non-type template- parameter is used
3011 // in an expression in the function parameter-list and, if the
3012 // corresponding template-argument is deduced, the
3013 // template-argument type shall match the type of the
3014 // template-parameter exactly, except that a template-argument
3015 // deduced from an array bound may be of any integral type.
3016 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3017 << ArgType << ParamType;
3018 Diag(Param->getLocation(), diag::note_template_param_here);
3019 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00003020 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3021 !ParamType->isEnumeralType()) {
3022 // This is an integral promotion or conversion.
John McCalle3027922010-08-25 11:45:40 +00003023 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00003024 } else {
3025 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003026 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00003027 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003028 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00003029 Diag(Param->getLocation(), diag::note_template_param_here);
3030 return true;
3031 }
3032
Douglas Gregor52aba872009-03-14 00:20:21 +00003033 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00003034 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003035 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00003036
3037 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00003038 llvm::APSInt OldValue = Value;
3039
3040 // Coerce the template argument's value to the value it will have
3041 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00003042 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00003043 if (Value.getBitWidth() != AllowedBits)
3044 Value.extOrTrunc(AllowedBits);
3045 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00003046
3047 // Complain if an unsigned parameter received a negative value.
3048 if (IntegerType->isUnsignedIntegerType()
3049 && (OldValue.isSigned() && OldValue.isNegative())) {
3050 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3051 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3052 << Arg->getSourceRange();
3053 Diag(Param->getLocation(), diag::note_template_param_here);
3054 }
3055
3056 // Complain if we overflowed the template parameter's type.
3057 unsigned RequiredBits;
3058 if (IntegerType->isUnsignedIntegerType())
3059 RequiredBits = OldValue.getActiveBits();
3060 else if (OldValue.isUnsigned())
3061 RequiredBits = OldValue.getActiveBits() + 1;
3062 else
3063 RequiredBits = OldValue.getMinSignedBits();
3064 if (RequiredBits > AllowedBits) {
3065 Diag(Arg->getSourceRange().getBegin(),
3066 diag::warn_template_arg_too_large)
3067 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3068 << Arg->getSourceRange();
3069 Diag(Param->getLocation(), diag::note_template_param_here);
3070 }
Douglas Gregor52aba872009-03-14 00:20:21 +00003071 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003072
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003073 // Add the value of this argument to the list of converted
3074 // arguments. We use the bitwidth and signedness of the template
3075 // parameter.
3076 if (Arg->isValueDependent()) {
3077 // The argument is value-dependent. Create a new
3078 // TemplateArgument with the converted expression.
3079 Converted = TemplateArgument(Arg);
3080 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003081 }
3082
John McCall0ad16662009-10-29 08:12:44 +00003083 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00003084 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003085 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00003086 return false;
3087 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003088
John McCall16df1e52010-03-30 21:47:33 +00003089 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3090
Douglas Gregorb242683d2010-04-01 18:32:35 +00003091 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3092 // from a template argument of type std::nullptr_t to a non-type
3093 // template parameter of type pointer to object, pointer to
3094 // function, or pointer-to-member, respectively.
3095 if (ArgType->isNullPtrType() &&
3096 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
3097 Converted = TemplateArgument((NamedDecl *)0);
3098 return false;
3099 }
3100
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003101 // Handle pointer-to-function, reference-to-function, and
3102 // pointer-to-member-function all in (roughly) the same way.
3103 if (// -- For a non-type template-parameter of type pointer to
3104 // function, only the function-to-pointer conversion (4.3) is
3105 // applied. If the template-argument represents a set of
3106 // overloaded functions (or a pointer to such), the matching
3107 // function is selected from the set (13.4).
3108 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003109 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003110 // -- For a non-type template-parameter of type reference to
3111 // function, no conversions apply. If the template-argument
3112 // represents a set of overloaded functions, the matching
3113 // function is selected from the set (13.4).
3114 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003115 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003116 // -- For a non-type template-parameter of type pointer to
3117 // member function, no conversions apply. If the
3118 // template-argument represents a set of overloaded member
3119 // functions, the matching member function is selected from
3120 // the set (13.4).
3121 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003122 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003123 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003124
Douglas Gregor064fdb22010-04-14 23:11:21 +00003125 if (Arg->getType() == Context.OverloadTy) {
3126 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
3127 true,
3128 FoundResult)) {
3129 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3130 return true;
3131
3132 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3133 ArgType = Arg->getType();
3134 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00003135 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003136 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00003137
Douglas Gregorb242683d2010-04-01 18:32:35 +00003138 if (!ParamType->isMemberPointerType())
3139 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3140 ParamType,
3141 Arg, Converted);
3142
3143 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCalle3027922010-08-25 11:45:40 +00003144 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb242683d2010-04-01 18:32:35 +00003145 } else if (!Context.hasSameUnqualifiedType(ArgType,
3146 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003147 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003148 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003149 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003150 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003151 Diag(Param->getLocation(), diag::note_template_param_here);
3152 return true;
3153 }
Mike Stump11289f42009-09-09 15:08:12 +00003154
Douglas Gregorb242683d2010-04-01 18:32:35 +00003155 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003156 }
3157
Chris Lattner696197c2009-02-20 21:37:53 +00003158 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003159 // -- for a non-type template-parameter of type pointer to
3160 // object, qualification conversions (4.4) and the
3161 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00003162 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00003163 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003164 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00003165
Douglas Gregorb242683d2010-04-01 18:32:35 +00003166 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3167 ParamType,
3168 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00003169 }
Mike Stump11289f42009-09-09 15:08:12 +00003170
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003171 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003172 // -- For a non-type template-parameter of type reference to
3173 // object, no conversions apply. The type referred to by the
3174 // reference may be more cv-qualified than the (otherwise
3175 // identical) type of the template-argument. The
3176 // template-parameter is bound directly to the
3177 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00003178 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003179 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00003180
Douglas Gregor064fdb22010-04-14 23:11:21 +00003181 if (Arg->getType() == Context.OverloadTy) {
3182 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
3183 ParamRefType->getPointeeType(),
3184 true,
3185 FoundResult)) {
3186 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3187 return true;
3188
3189 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3190 ArgType = Arg->getType();
3191 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00003192 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003193 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00003194
Douglas Gregorb242683d2010-04-01 18:32:35 +00003195 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3196 ParamType,
3197 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003198 }
Douglas Gregor0e558532009-02-11 16:16:59 +00003199
3200 // -- For a non-type template-parameter of type pointer to data
3201 // member, qualification conversions (4.4) are applied.
3202 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3203
Douglas Gregor1515f762009-02-11 18:22:40 +00003204 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00003205 // Types match exactly: nothing more to do here.
3206 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCalle3027922010-08-25 11:45:40 +00003207 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor0e558532009-02-11 16:16:59 +00003208 } else {
3209 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003210 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00003211 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003212 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00003213 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003214 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00003215 }
3216
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00003217 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00003218}
3219
3220/// \brief Check a template argument against its corresponding
3221/// template template parameter.
3222///
3223/// This routine implements the semantics of C++ [temp.arg.template].
3224/// It returns true if an error occurred, and false otherwise.
3225bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003226 const TemplateArgumentLoc &Arg) {
3227 TemplateName Name = Arg.getArgument().getAsTemplate();
3228 TemplateDecl *Template = Name.getAsTemplateDecl();
3229 if (!Template) {
3230 // Any dependent template name is fine.
3231 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3232 return false;
3233 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003234
3235 // C++ [temp.arg.template]p1:
3236 // A template-argument for a template template-parameter shall be
3237 // the name of a class template, expressed as id-expression. Only
3238 // primary class templates are considered when matching the
3239 // template template argument with the corresponding parameter;
3240 // partial specializations are not considered even if their
3241 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003242 //
3243 // Note that we also allow template template parameters here, which
3244 // will happen when we are dealing with, e.g., class template
3245 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003246 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003247 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003248 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003249 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003250 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003251 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003252 << Template;
3253 }
3254
3255 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3256 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003257 true,
3258 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003259 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003260}
3261
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003262/// \brief Given a non-type template argument that refers to a
3263/// declaration and the type of its corresponding non-type template
3264/// parameter, produce an expression that properly refers to that
3265/// declaration.
John McCalldadc5752010-08-24 06:29:42 +00003266ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003267Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3268 QualType ParamType,
3269 SourceLocation Loc) {
3270 assert(Arg.getKind() == TemplateArgument::Declaration &&
3271 "Only declaration template arguments permitted here");
3272 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3273
3274 if (VD->getDeclContext()->isRecord() &&
3275 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3276 // If the value is a class member, we might have a pointer-to-member.
3277 // Determine whether the non-type template template parameter is of
3278 // pointer-to-member type. If so, we need to build an appropriate
3279 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3280 // would refer to the member itself.
3281 if (ParamType->isMemberPointerType()) {
3282 QualType ClassType
3283 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3284 NestedNameSpecifier *Qualifier
John McCallb268a282010-08-23 23:25:46 +00003285 = NestedNameSpecifier::Create(Context, 0, false,
3286 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003287 CXXScopeSpec SS;
3288 SS.setScopeRep(Qualifier);
John McCalldadc5752010-08-24 06:29:42 +00003289 ExprResult RefExpr = BuildDeclRefExpr(VD,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003290 VD->getType().getNonReferenceType(),
3291 Loc,
3292 &SS);
3293 if (RefExpr.isInvalid())
3294 return ExprError();
3295
John McCalle3027922010-08-25 11:45:40 +00003296 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003297
3298 // We might need to perform a trailing qualification conversion, since
3299 // the element type on the parameter could be more qualified than the
3300 // element type in the expression we constructed.
3301 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3302 ParamType.getUnqualifiedType())) {
3303 Expr *RefE = RefExpr.takeAs<Expr>();
John McCalle3027922010-08-25 11:45:40 +00003304 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003305 RefExpr = Owned(RefE);
3306 }
3307
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003308 assert(!RefExpr.isInvalid() &&
3309 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003310 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003311 return move(RefExpr);
3312 }
3313 }
3314
3315 QualType T = VD->getType().getNonReferenceType();
3316 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003317 // When the non-type template parameter is a pointer, take the
3318 // address of the declaration.
John McCalldadc5752010-08-24 06:29:42 +00003319 ExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003320 if (RefExpr.isInvalid())
3321 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003322
3323 if (T->isFunctionType() || T->isArrayType()) {
3324 // Decay functions and arrays.
3325 Expr *RefE = (Expr *)RefExpr.get();
3326 DefaultFunctionArrayConversion(RefE);
3327 if (RefE != RefExpr.get()) {
3328 RefExpr.release();
3329 RefExpr = Owned(RefE);
3330 }
3331
3332 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003333 }
3334
Douglas Gregorb242683d2010-04-01 18:32:35 +00003335 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00003336 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003337 }
3338
3339 // If the non-type template parameter has reference type, qualify the
3340 // resulting declaration reference with the extra qualifiers on the
3341 // type that the reference refers to.
3342 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3343 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3344
3345 return BuildDeclRefExpr(VD, T, Loc);
3346}
3347
3348/// \brief Construct a new expression that refers to the given
3349/// integral template argument with the given source-location
3350/// information.
3351///
3352/// This routine takes care of the mapping from an integral template
3353/// argument (which may have any integral type) to the appropriate
3354/// literal value.
John McCalldadc5752010-08-24 06:29:42 +00003355ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003356Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3357 SourceLocation Loc) {
3358 assert(Arg.getKind() == TemplateArgument::Integral &&
3359 "Operation is only value for integral template arguments");
3360 QualType T = Arg.getIntegralType();
3361 if (T->isCharType() || T->isWideCharType())
3362 return Owned(new (Context) CharacterLiteral(
3363 Arg.getAsIntegral()->getZExtValue(),
3364 T->isWideCharType(),
3365 T,
3366 Loc));
3367 if (T->isBooleanType())
3368 return Owned(new (Context) CXXBoolLiteralExpr(
3369 Arg.getAsIntegral()->getBoolValue(),
3370 T,
3371 Loc));
3372
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003373 return Owned(IntegerLiteral::Create(Context, *Arg.getAsIntegral(), T, Loc));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003374}
3375
3376
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003377/// \brief Determine whether the given template parameter lists are
3378/// equivalent.
3379///
Mike Stump11289f42009-09-09 15:08:12 +00003380/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003381/// source code as part of a new template declaration.
3382///
3383/// \param Old The old template parameter list, typically found via
3384/// name lookup of the template declared with this template parameter
3385/// list.
3386///
3387/// \param Complain If true, this routine will produce a diagnostic if
3388/// the template parameter lists are not equivalent.
3389///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003390/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003391///
3392/// \param TemplateArgLoc If this source location is valid, then we
3393/// are actually checking the template parameter list of a template
3394/// argument (New) against the template parameter list of its
3395/// corresponding template template parameter (Old). We produce
3396/// slightly different diagnostics in this scenario.
3397///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003398/// \returns True if the template parameter lists are equal, false
3399/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003400bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003401Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3402 TemplateParameterList *Old,
3403 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003404 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003405 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003406 if (Old->size() != New->size()) {
3407 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003408 unsigned NextDiag = diag::err_template_param_list_different_arity;
3409 if (TemplateArgLoc.isValid()) {
3410 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3411 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003412 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003413 Diag(New->getTemplateLoc(), NextDiag)
3414 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003415 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003416 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003417 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003418 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003419 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3420 }
3421
3422 return false;
3423 }
3424
3425 for (TemplateParameterList::iterator OldParm = Old->begin(),
3426 OldParmEnd = Old->end(), NewParm = New->begin();
3427 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3428 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003429 if (Complain) {
3430 unsigned NextDiag = diag::err_template_param_different_kind;
3431 if (TemplateArgLoc.isValid()) {
3432 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3433 NextDiag = diag::note_template_param_different_kind;
3434 }
3435 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003436 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003437 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003438 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003439 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003440 return false;
3441 }
3442
Douglas Gregor2e87ca22010-06-04 08:34:32 +00003443 if (TemplateTypeParmDecl *OldTTP
3444 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3445 // Template type parameters are equivalent if either both are template
3446 // type parameter packs or neither are (since we know we're at the same
3447 // index).
3448 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3449 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3450 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3451 // allow one to match a template parameter pack in the template
3452 // parameter list of a template template parameter to one or more
3453 // template parameters in the template parameter list of the
3454 // corresponding template template argument.
3455 if (Complain) {
3456 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3457 if (TemplateArgLoc.isValid()) {
3458 Diag(TemplateArgLoc,
3459 diag::err_template_arg_template_params_mismatch);
3460 NextDiag = diag::note_template_parameter_pack_non_pack;
3461 }
3462 Diag(NewTTP->getLocation(), NextDiag)
3463 << 0 << NewTTP->isParameterPack();
3464 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3465 << 0 << OldTTP->isParameterPack();
3466 }
3467 return false;
3468 }
Mike Stump11289f42009-09-09 15:08:12 +00003469 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003470 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3471 // The types of non-type template parameters must agree.
3472 NonTypeTemplateParmDecl *NewNTTP
3473 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003474
3475 // If we are matching a template template argument to a template
3476 // template parameter and one of the non-type template parameter types
3477 // is dependent, then we must wait until template instantiation time
3478 // to actually compare the arguments.
3479 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3480 (OldNTTP->getType()->isDependentType() ||
3481 NewNTTP->getType()->isDependentType()))
3482 continue;
3483
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003484 if (Context.getCanonicalType(OldNTTP->getType()) !=
3485 Context.getCanonicalType(NewNTTP->getType())) {
3486 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003487 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3488 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003489 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003490 diag::err_template_arg_template_params_mismatch);
3491 NextDiag = diag::note_template_nontype_parm_different_type;
3492 }
3493 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003494 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003495 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003496 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003497 diag::note_template_nontype_parm_prev_declaration)
3498 << OldNTTP->getType();
3499 }
3500 return false;
3501 }
3502 } else {
3503 // The template parameter lists of template template
3504 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003505 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003506 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003507 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003508 = cast<TemplateTemplateParmDecl>(*OldParm);
3509 TemplateTemplateParmDecl *NewTTP
3510 = cast<TemplateTemplateParmDecl>(*NewParm);
3511 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3512 OldTTP->getTemplateParameters(),
3513 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003514 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003515 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003516 return false;
3517 }
3518 }
3519
3520 return true;
3521}
3522
3523/// \brief Check whether a template can be declared within this scope.
3524///
3525/// If the template declaration is valid in this scope, returns
3526/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003527bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003528Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003529 // Find the nearest enclosing declaration scope.
3530 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3531 (S->getFlags() & Scope::TemplateParamScope) != 0)
3532 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003533
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003534 // C++ [temp]p2:
3535 // A template-declaration can appear only as a namespace scope or
3536 // class scope declaration.
3537 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003538 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3539 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003540 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003541 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003542
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003543 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003544 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003545
3546 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3547 return false;
3548
Mike Stump11289f42009-09-09 15:08:12 +00003549 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003550 diag::err_template_outside_namespace_or_class_scope)
3551 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003552}
Douglas Gregor67a65642009-02-17 23:15:12 +00003553
Douglas Gregor54888652009-10-07 00:13:32 +00003554/// \brief Determine what kind of template specialization the given declaration
3555/// is.
3556static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3557 if (!D)
3558 return TSK_Undeclared;
3559
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003560 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3561 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003562 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3563 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003564 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3565 return Var->getTemplateSpecializationKind();
3566
Douglas Gregor54888652009-10-07 00:13:32 +00003567 return TSK_Undeclared;
3568}
3569
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003570/// \brief Check whether a specialization is well-formed in the current
3571/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003572///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003573/// This routine determines whether a template specialization can be declared
3574/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003575///
3576/// \param S the semantic analysis object for which this check is being
3577/// performed.
3578///
3579/// \param Specialized the entity being specialized or instantiated, which
3580/// may be a kind of template (class template, function template, etc.) or
3581/// a member of a class template (member function, static data member,
3582/// member class).
3583///
3584/// \param PrevDecl the previous declaration of this entity, if any.
3585///
3586/// \param Loc the location of the explicit specialization or instantiation of
3587/// this entity.
3588///
3589/// \param IsPartialSpecialization whether this is a partial specialization of
3590/// a class template.
3591///
Douglas Gregor54888652009-10-07 00:13:32 +00003592/// \returns true if there was an error that we cannot recover from, false
3593/// otherwise.
3594static bool CheckTemplateSpecializationScope(Sema &S,
3595 NamedDecl *Specialized,
3596 NamedDecl *PrevDecl,
3597 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003598 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003599 // Keep these "kind" numbers in sync with the %select statements in the
3600 // various diagnostics emitted by this routine.
3601 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003602 bool isTemplateSpecialization = false;
3603 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003604 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003605 isTemplateSpecialization = true;
3606 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003607 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003608 isTemplateSpecialization = true;
3609 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003610 EntityKind = 3;
3611 else if (isa<VarDecl>(Specialized))
3612 EntityKind = 4;
3613 else if (isa<RecordDecl>(Specialized))
3614 EntityKind = 5;
3615 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003616 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3617 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003618 return true;
3619 }
3620
Douglas Gregorf47b9112009-02-25 22:02:03 +00003621 // C++ [temp.expl.spec]p2:
3622 // An explicit specialization shall be declared in the namespace
3623 // of which the template is a member, or, for member templates, in
3624 // the namespace of which the enclosing class or enclosing class
3625 // template is a member. An explicit specialization of a member
3626 // function, member class or static data member of a class
3627 // template shall be declared in the namespace of which the class
3628 // template is a member. Such a declaration may also be a
3629 // definition. If the declaration is not a definition, the
3630 // specialization may be defined later in the name- space in which
3631 // the explicit specialization was declared, or in a namespace
3632 // that encloses the one in which the explicit specialization was
3633 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00003634 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00003635 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003636 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003637 return true;
3638 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003639
Douglas Gregor40fb7442009-10-07 17:30:37 +00003640 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3641 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003642 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003643 return true;
3644 }
3645
Douglas Gregore4b05162009-10-07 17:21:34 +00003646 // C++ [temp.class.spec]p6:
3647 // A class template partial specialization may be declared or redeclared
3648 // in any namespace scope in which its definition may be defined (14.5.1
3649 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003650 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003651 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003652 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003653 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003654 if ((!PrevDecl ||
3655 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3656 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregorb1aab432010-09-12 05:08:28 +00003657 // C++ [temp.exp.spec]p2:
3658 // An explicit specialization shall be declared in the namespace of which
3659 // the template is a member, or, for member templates, in the namespace
3660 // of which the enclosing class or enclosing class template is a member.
3661 // An explicit specialization of a member function, member class or
3662 // static data member of a class template shall be declared in the
3663 // namespace of which the class template is a member.
3664 //
3665 // C++0x [temp.expl.spec]p2:
3666 // An explicit specialization shall be declared in a namespace enclosing
3667 // the specialized template.
3668 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
3669 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
Douglas Gregor8ce63152010-09-12 05:24:55 +00003670 bool IsCPlusPlus0xExtension
3671 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003672 if (isa<TranslationUnitDecl>(SpecializedContext))
Douglas Gregor8ce63152010-09-12 05:24:55 +00003673 S.Diag(Loc, IsCPlusPlus0xExtension
3674 ? diag::ext_template_spec_decl_out_of_scope_global
3675 : diag::err_template_spec_decl_out_of_scope_global)
3676 << EntityKind << Specialized;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003677 else if (isa<NamespaceDecl>(SpecializedContext))
Douglas Gregor8ce63152010-09-12 05:24:55 +00003678 S.Diag(Loc, IsCPlusPlus0xExtension
3679 ? diag::ext_template_spec_decl_out_of_scope
3680 : diag::err_template_spec_decl_out_of_scope)
3681 << EntityKind << Specialized
3682 << cast<NamedDecl>(SpecializedContext);
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003683
3684 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3685 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003686 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003687 }
Douglas Gregor54888652009-10-07 00:13:32 +00003688
3689 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003690 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003691 // Note that HandleDeclarator() performs this check for explicit
3692 // specializations of function templates, static data members, and member
3693 // functions, so we skip the check here for those kinds of entities.
3694 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003695 // Should we refactor that check, so that it occurs later?
3696 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003697 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3698 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003699 if (isa<TranslationUnitDecl>(SpecializedContext))
3700 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3701 << EntityKind << Specialized;
3702 else if (isa<NamespaceDecl>(SpecializedContext))
3703 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3704 << EntityKind << Specialized
3705 << cast<NamedDecl>(SpecializedContext);
3706
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003707 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003708 }
Douglas Gregor54888652009-10-07 00:13:32 +00003709
3710 // FIXME: check for specialization-after-instantiation errors and such.
3711
Douglas Gregorf47b9112009-02-25 22:02:03 +00003712 return false;
3713}
Douglas Gregor54888652009-10-07 00:13:32 +00003714
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003715/// \brief Check the non-type template arguments of a class template
3716/// partial specialization according to C++ [temp.class.spec]p9.
3717///
Douglas Gregor09a30232009-06-12 22:08:06 +00003718/// \param TemplateParams the template parameters of the primary class
3719/// template.
3720///
3721/// \param TemplateArg the template arguments of the class template
3722/// partial specialization.
3723///
3724/// \param MirrorsPrimaryTemplate will be set true if the class
3725/// template partial specialization arguments are identical to the
3726/// implicit template arguments of the primary template. This is not
3727/// necessarily an error (C++0x), and it is left to the caller to diagnose
3728/// this condition when it is an error.
3729///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003730/// \returns true if there was an error, false otherwise.
3731bool Sema::CheckClassTemplatePartialSpecializationArgs(
3732 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003733 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003734 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003735 // FIXME: the interface to this function will have to change to
3736 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003737 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003738
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003739 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003740
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003741 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003742 // Determine whether the template argument list of the partial
3743 // specialization is identical to the implicit argument list of
3744 // the primary template. The caller may need to diagnostic this as
3745 // an error per C++ [temp.class.spec]p9b3.
3746 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003747 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003748 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3749 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003750 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003751 MirrorsPrimaryTemplate = false;
3752 } else if (TemplateTemplateParmDecl *TTP
3753 = dyn_cast<TemplateTemplateParmDecl>(
3754 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003755 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003756 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003757 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003758 if (!ArgDecl ||
3759 ArgDecl->getIndex() != TTP->getIndex() ||
3760 ArgDecl->getDepth() != TTP->getDepth())
3761 MirrorsPrimaryTemplate = false;
3762 }
3763 }
3764
Mike Stump11289f42009-09-09 15:08:12 +00003765 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003766 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003767 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003768 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003769 }
3770
Anders Carlsson40c1d492009-06-13 18:20:51 +00003771 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003772 if (!ArgExpr) {
3773 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003774 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003775 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003776
3777 // C++ [temp.class.spec]p8:
3778 // A non-type argument is non-specialized if it is the name of a
3779 // non-type parameter. All other non-type arguments are
3780 // specialized.
3781 //
3782 // Below, we check the two conditions that only apply to
3783 // specialized non-type arguments, so skip any non-specialized
3784 // arguments.
3785 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003786 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003787 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003788 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003789 (Param->getIndex() != NTTP->getIndex() ||
3790 Param->getDepth() != NTTP->getDepth()))
3791 MirrorsPrimaryTemplate = false;
3792
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003793 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003794 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003795
3796 // C++ [temp.class.spec]p9:
3797 // Within the argument list of a class template partial
3798 // specialization, the following restrictions apply:
3799 // -- A partially specialized non-type argument expression
3800 // shall not involve a template parameter of the partial
3801 // specialization except when the argument expression is a
3802 // simple identifier.
3803 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003804 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003805 diag::err_dependent_non_type_arg_in_partial_spec)
3806 << ArgExpr->getSourceRange();
3807 return true;
3808 }
3809
3810 // -- The type of a template parameter corresponding to a
3811 // specialized non-type argument shall not be dependent on a
3812 // parameter of the specialization.
3813 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003814 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003815 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3816 << Param->getType()
3817 << ArgExpr->getSourceRange();
3818 Diag(Param->getLocation(), diag::note_template_param_here);
3819 return true;
3820 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003821
3822 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003823 }
3824
3825 return false;
3826}
3827
Douglas Gregorc854c662010-02-26 06:03:23 +00003828/// \brief Retrieve the previous declaration of the given declaration.
3829static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3830 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3831 return VD->getPreviousDeclaration();
3832 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3833 return FD->getPreviousDeclaration();
3834 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3835 return TD->getPreviousDeclaration();
3836 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3837 return TD->getPreviousDeclaration();
3838 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3839 return FTD->getPreviousDeclaration();
3840 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3841 return CTD->getPreviousDeclaration();
3842 return 0;
3843}
3844
John McCall48871652010-08-21 09:40:31 +00003845DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003846Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3847 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003848 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003849 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003850 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003851 SourceLocation TemplateNameLoc,
3852 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003853 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003854 SourceLocation RAngleLoc,
3855 AttributeList *Attr,
3856 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003857 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003858
Douglas Gregor67a65642009-02-17 23:15:12 +00003859 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003860 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003861 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003862 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3863
3864 if (!ClassTemplate) {
3865 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3866 << (Name.getAsTemplateDecl() &&
3867 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3868 return true;
3869 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003870
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003871 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003872 bool isPartialSpecialization = false;
3873
Douglas Gregorf47b9112009-02-25 22:02:03 +00003874 // Check the validity of the template headers that introduce this
3875 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003876 // FIXME: We probably shouldn't complain about these headers for
3877 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003878 bool Invalid = false;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003879 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003880 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3881 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003882 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003883 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003884 isExplicitSpecialization,
3885 Invalid);
3886 if (Invalid)
3887 return true;
3888
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003889 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3890 if (TemplateParams)
3891 --NumMatchedTemplateParamLists;
3892
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003893 if (TemplateParams && TemplateParams->size() > 0) {
3894 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003895
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003896 // C++ [temp.class.spec]p10:
3897 // The template parameter list of a specialization shall not
3898 // contain default template argument values.
3899 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3900 Decl *Param = TemplateParams->getParam(I);
3901 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3902 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003903 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003904 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003905 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003906 }
3907 } else if (NonTypeTemplateParmDecl *NTTP
3908 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3909 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003910 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003911 diag::err_default_arg_in_partial_spec)
3912 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003913 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003914 }
3915 } else {
3916 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003917 if (TTP->hasDefaultArgument()) {
3918 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003919 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003920 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003921 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00003922 }
3923 }
3924 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003925 } else if (TemplateParams) {
3926 if (TUK == TUK_Friend)
3927 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003928 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003929 SourceRange(TemplateParams->getTemplateLoc(),
3930 TemplateParams->getRAngleLoc()))
3931 << SourceRange(LAngleLoc, RAngleLoc);
3932 else
3933 isExplicitSpecialization = true;
3934 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003935 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003936 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003937 isExplicitSpecialization = true;
3938 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003939
Douglas Gregor67a65642009-02-17 23:15:12 +00003940 // Check that the specialization uses the same tag kind as the
3941 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003942 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3943 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00003944 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003945 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003946 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003947 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003948 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003949 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003950 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003951 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003952 diag::note_previous_use);
3953 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3954 }
3955
Douglas Gregorc40290e2009-03-09 23:48:35 +00003956 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003957 TemplateArgumentListInfo TemplateArgs;
3958 TemplateArgs.setLAngleLoc(LAngleLoc);
3959 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003960 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003961
Douglas Gregor67a65642009-02-17 23:15:12 +00003962 // Check that the template argument list is well-formed for this
3963 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003964 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3965 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003966 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3967 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003968 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003969
Mike Stump11289f42009-09-09 15:08:12 +00003970 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003971 ClassTemplate->getTemplateParameters()->size()) &&
3972 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003973
Douglas Gregor2373c592009-05-31 09:31:02 +00003974 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003975 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00003976 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003977 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003978 if (CheckClassTemplatePartialSpecializationArgs(
3979 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003980 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003981 return true;
3982
Douglas Gregor09a30232009-06-12 22:08:06 +00003983 if (MirrorsPrimaryTemplate) {
3984 // C++ [temp.class.spec]p9b3:
3985 //
Mike Stump11289f42009-09-09 15:08:12 +00003986 // -- The argument list of the specialization shall not be identical
3987 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003988 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003989 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003990 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003991 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003992 ClassTemplate->getIdentifier(),
3993 TemplateNameLoc,
3994 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003995 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003996 AS_none);
3997 }
3998
Douglas Gregor2208a292009-09-26 20:57:03 +00003999 // FIXME: Diagnose friend partial specializations
4000
Douglas Gregor92354b62010-02-09 00:37:32 +00004001 if (!Name.isDependent() &&
4002 !TemplateSpecializationType::anyDependentTemplateArguments(
4003 TemplateArgs.getArgumentArray(),
4004 TemplateArgs.size())) {
4005 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4006 << ClassTemplate->getDeclName();
4007 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00004008 }
4009 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004010
Douglas Gregor67a65642009-02-17 23:15:12 +00004011 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00004012 ClassTemplateSpecializationDecl *PrevDecl = 0;
4013
4014 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004015 // FIXME: Template parameter list matters, too
Douglas Gregor2373c592009-05-31 09:31:02 +00004016 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004017 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
4018 Converted.flatSize(),
4019 InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00004020 else
4021 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004022 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4023 Converted.flatSize(), InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00004024
4025 ClassTemplateSpecializationDecl *Specialization = 0;
4026
Douglas Gregorf47b9112009-02-25 22:02:03 +00004027 // Check whether we can declare a class template specialization in
4028 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00004029 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00004030 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004031 TemplateNameLoc,
4032 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00004033 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004034
Douglas Gregor15301382009-07-30 17:40:51 +00004035 // The canonical type
4036 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00004037 if (PrevDecl &&
4038 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00004039 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00004040 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00004041 // arguments was referenced but not declared, or we're only
4042 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00004043 // declaration node as our own, updating its source location to
4044 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00004045 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00004046 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00004047 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00004048 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00004049 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00004050 // Build the canonical type that describes the converted template
4051 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00004052 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4053 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00004054 Converted.getFlatArguments(),
4055 Converted.flatSize());
4056
Douglas Gregor2373c592009-05-31 09:31:02 +00004057 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00004058 ClassTemplatePartialSpecializationDecl *PrevPartial
4059 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00004060 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004061 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump11289f42009-09-09 15:08:12 +00004062 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00004063 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00004064 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00004065 TemplateNameLoc,
4066 TemplateParams,
4067 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004068 Converted,
John McCall6b51f282009-11-23 01:53:49 +00004069 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00004070 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00004071 PrevPartial,
4072 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00004073 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00004074 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00004075 Partial->setTemplateParameterListsInfo(Context,
4076 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004077 (TemplateParameterList**) TemplateParameterLists.release());
4078 }
Douglas Gregor2373c592009-05-31 09:31:02 +00004079
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004080 if (!PrevPartial)
4081 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00004082 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00004083
Douglas Gregor21610382009-10-29 00:04:11 +00004084 // If we are providing an explicit specialization of a member class
4085 // template specialization, make a note of that.
4086 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4087 PrevPartial->setMemberSpecialization();
4088
Douglas Gregor91772d12009-06-13 00:26:55 +00004089 // Check that all of the template parameters of the class template
4090 // partial specialization are deducible from the template
4091 // arguments. If not, this class template partial specialization
4092 // will never be used.
4093 llvm::SmallVector<bool, 8> DeducibleParams;
4094 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004095 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00004096 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004097 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00004098 unsigned NumNonDeducible = 0;
4099 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
4100 if (!DeducibleParams[I])
4101 ++NumNonDeducible;
4102
4103 if (NumNonDeducible) {
4104 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
4105 << (NumNonDeducible > 1)
4106 << SourceRange(TemplateNameLoc, RAngleLoc);
4107 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4108 if (!DeducibleParams[I]) {
4109 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
4110 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00004111 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00004112 diag::note_partial_spec_unused_parameter)
4113 << Param->getDeclName();
4114 else
Mike Stump11289f42009-09-09 15:08:12 +00004115 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00004116 diag::note_partial_spec_unused_parameter)
Benjamin Kramere8394df2010-08-11 14:47:12 +00004117 << "<anonymous>";
Douglas Gregor91772d12009-06-13 00:26:55 +00004118 }
4119 }
4120 }
Douglas Gregor67a65642009-02-17 23:15:12 +00004121 } else {
4122 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00004123 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00004124 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004125 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00004126 ClassTemplate->getDeclContext(),
4127 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004128 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004129 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00004130 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004131 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00004132 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00004133 Specialization->setTemplateParameterListsInfo(Context,
4134 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004135 (TemplateParameterList**) TemplateParameterLists.release());
4136 }
Douglas Gregor67a65642009-02-17 23:15:12 +00004137
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004138 if (!PrevDecl)
4139 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00004140
4141 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00004142 }
4143
Douglas Gregor06db9f52009-10-12 20:18:28 +00004144 // C++ [temp.expl.spec]p6:
4145 // If a template, a member template or the member of a class template is
4146 // explicitly specialized then that specialization shall be declared
4147 // before the first use of that specialization that would cause an implicit
4148 // instantiation to take place, in every translation unit in which such a
4149 // use occurs; no diagnostic is required.
4150 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00004151 bool Okay = false;
4152 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4153 // Is there any previous explicit specialization declaration?
4154 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4155 Okay = true;
4156 break;
4157 }
4158 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00004159
Douglas Gregorc854c662010-02-26 06:03:23 +00004160 if (!Okay) {
4161 SourceRange Range(TemplateNameLoc, RAngleLoc);
4162 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4163 << Context.getTypeDeclType(Specialization) << Range;
4164
4165 Diag(PrevDecl->getPointOfInstantiation(),
4166 diag::note_instantiation_required_here)
4167 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00004168 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00004169 return true;
4170 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00004171 }
4172
Douglas Gregor2208a292009-09-26 20:57:03 +00004173 // If this is not a friend, note that this is an explicit specialization.
4174 if (TUK != TUK_Friend)
4175 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00004176
4177 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00004178 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004179 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00004180 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004181 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00004182 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00004183 Diag(Def->getLocation(), diag::note_previous_definition);
4184 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00004185 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00004186 }
4187 }
4188
Douglas Gregord56a91e2009-02-26 22:19:44 +00004189 // Build the fully-sugared type for this class template
4190 // specialization as the user wrote in the specialization
4191 // itself. This means that we'll pretty-print the type retrieved
4192 // from the specialization's declaration the way that the user
4193 // actually wrote the specialization, rather than formatting the
4194 // name based on the "canonical" representation used to store the
4195 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004196 TypeSourceInfo *WrittenTy
4197 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4198 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004199 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00004200 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregord890b732010-07-06 18:33:12 +00004201 if (TemplateParams)
4202 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnara8075c852010-06-12 07:44:57 +00004203 }
Douglas Gregorc40290e2009-03-09 23:48:35 +00004204 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00004205
Douglas Gregor1e249f82009-02-25 22:18:32 +00004206 // C++ [temp.expl.spec]p9:
4207 // A template explicit specialization is in the scope of the
4208 // namespace in which the template was defined.
4209 //
4210 // We actually implement this paragraph where we set the semantic
4211 // context (in the creation of the ClassTemplateSpecializationDecl),
4212 // but we also maintain the lexical context where the actual
4213 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00004214 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00004215
Douglas Gregor67a65642009-02-17 23:15:12 +00004216 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00004217 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00004218 Specialization->startDefinition();
4219
Douglas Gregor2208a292009-09-26 20:57:03 +00004220 if (TUK == TUK_Friend) {
4221 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4222 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00004223 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00004224 /*FIXME:*/KWLoc);
4225 Friend->setAccess(AS_public);
4226 CurContext->addDecl(Friend);
4227 } else {
4228 // Add the specialization into its lexical context, so that it can
4229 // be seen when iterating through the list of declarations in that
4230 // context. However, specializations are not found by name lookup.
4231 CurContext->addDecl(Specialization);
4232 }
John McCall48871652010-08-21 09:40:31 +00004233 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00004234}
Douglas Gregor333489b2009-03-27 23:10:48 +00004235
John McCall48871652010-08-21 09:40:31 +00004236Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004237 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004238 Declarator &D) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004239 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4240}
4241
John McCall48871652010-08-21 09:40:31 +00004242Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004243 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004244 Declarator &D) {
Douglas Gregor17a7c122009-06-24 00:54:41 +00004245 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4246 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4247 "Not a function declarator!");
4248 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00004249
Douglas Gregor17a7c122009-06-24 00:54:41 +00004250 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004251 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004252 }
Mike Stump11289f42009-09-09 15:08:12 +00004253
Douglas Gregor17a7c122009-06-24 00:54:41 +00004254 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004255
John McCall48871652010-08-21 09:40:31 +00004256 Decl *DP = HandleDeclarator(ParentScope, D,
4257 move(TemplateParameterLists),
4258 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004259 if (FunctionTemplateDecl *FunctionTemplate
John McCall48871652010-08-21 09:40:31 +00004260 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump11289f42009-09-09 15:08:12 +00004261 return ActOnStartOfFunctionDef(FnBodyScope,
John McCall48871652010-08-21 09:40:31 +00004262 FunctionTemplate->getTemplatedDecl());
4263 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4264 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4265 return 0;
Douglas Gregor17a7c122009-06-24 00:54:41 +00004266}
4267
John McCall4f7ced62010-02-11 01:33:53 +00004268/// \brief Strips various properties off an implicit instantiation
4269/// that has just been explicitly specialized.
4270static void StripImplicitInstantiation(NamedDecl *D) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004271 D->dropAttrs();
John McCall4f7ced62010-02-11 01:33:53 +00004272
4273 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4274 FD->setInlineSpecified(false);
4275 }
4276}
4277
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004278/// \brief Diagnose cases where we have an explicit template specialization
4279/// before/after an explicit template instantiation, producing diagnostics
4280/// for those cases where they are required and determining whether the
4281/// new specialization/instantiation will have any effect.
4282///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004283/// \param NewLoc the location of the new explicit specialization or
4284/// instantiation.
4285///
4286/// \param NewTSK the kind of the new explicit specialization or instantiation.
4287///
4288/// \param PrevDecl the previous declaration of the entity.
4289///
4290/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4291///
4292/// \param PrevPointOfInstantiation if valid, indicates where the previus
4293/// declaration was instantiated (either implicitly or explicitly).
4294///
Abramo Bagnara8075c852010-06-12 07:44:57 +00004295/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004296/// specialization or instantiation has no effect and should be ignored.
4297///
4298/// \returns true if there was an error that should prevent the introduction of
4299/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004300bool
4301Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4302 TemplateSpecializationKind NewTSK,
4303 NamedDecl *PrevDecl,
4304 TemplateSpecializationKind PrevTSK,
4305 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004306 bool &HasNoEffect) {
4307 HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004308
4309 switch (NewTSK) {
4310 case TSK_Undeclared:
4311 case TSK_ImplicitInstantiation:
4312 assert(false && "Don't check implicit instantiations here");
4313 return false;
4314
4315 case TSK_ExplicitSpecialization:
4316 switch (PrevTSK) {
4317 case TSK_Undeclared:
4318 case TSK_ExplicitSpecialization:
4319 // Okay, we're just specializing something that is either already
4320 // explicitly specialized or has merely been mentioned without any
4321 // instantiation.
4322 return false;
4323
4324 case TSK_ImplicitInstantiation:
4325 if (PrevPointOfInstantiation.isInvalid()) {
4326 // The declaration itself has not actually been instantiated, so it is
4327 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004328 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004329 return false;
4330 }
4331 // Fall through
4332
4333 case TSK_ExplicitInstantiationDeclaration:
4334 case TSK_ExplicitInstantiationDefinition:
4335 assert((PrevTSK == TSK_ImplicitInstantiation ||
4336 PrevPointOfInstantiation.isValid()) &&
4337 "Explicit instantiation without point of instantiation?");
4338
4339 // C++ [temp.expl.spec]p6:
4340 // If a template, a member template or the member of a class template
4341 // is explicitly specialized then that specialization shall be declared
4342 // before the first use of that specialization that would cause an
4343 // implicit instantiation to take place, in every translation unit in
4344 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004345 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4346 // Is there any previous explicit specialization declaration?
4347 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4348 return false;
4349 }
4350
Douglas Gregor1d957a32009-10-27 18:42:08 +00004351 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004352 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004353 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004354 << (PrevTSK != TSK_ImplicitInstantiation);
4355
4356 return true;
4357 }
4358 break;
4359
4360 case TSK_ExplicitInstantiationDeclaration:
4361 switch (PrevTSK) {
4362 case TSK_ExplicitInstantiationDeclaration:
4363 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00004364 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004365 return false;
4366
4367 case TSK_Undeclared:
4368 case TSK_ImplicitInstantiation:
4369 // We're explicitly instantiating something that may have already been
4370 // implicitly instantiated; that's fine.
4371 return false;
4372
4373 case TSK_ExplicitSpecialization:
4374 // C++0x [temp.explicit]p4:
4375 // For a given set of template parameters, if an explicit instantiation
4376 // of a template appears after a declaration of an explicit
4377 // specialization for that template, the explicit instantiation has no
4378 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00004379 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004380 return false;
4381
4382 case TSK_ExplicitInstantiationDefinition:
4383 // C++0x [temp.explicit]p10:
4384 // If an entity is the subject of both an explicit instantiation
4385 // declaration and an explicit instantiation definition in the same
4386 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004387 Diag(NewLoc,
4388 diag::err_explicit_instantiation_declaration_after_definition);
4389 Diag(PrevPointOfInstantiation,
4390 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004391 assert(PrevPointOfInstantiation.isValid() &&
4392 "Explicit instantiation without point of instantiation?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00004393 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004394 return false;
4395 }
4396 break;
4397
4398 case TSK_ExplicitInstantiationDefinition:
4399 switch (PrevTSK) {
4400 case TSK_Undeclared:
4401 case TSK_ImplicitInstantiation:
4402 // We're explicitly instantiating something that may have already been
4403 // implicitly instantiated; that's fine.
4404 return false;
4405
4406 case TSK_ExplicitSpecialization:
4407 // C++ DR 259, C++0x [temp.explicit]p4:
4408 // For a given set of template parameters, if an explicit
4409 // instantiation of a template appears after a declaration of
4410 // an explicit specialization for that template, the explicit
4411 // instantiation has no effect.
4412 //
4413 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004414 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004415 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004416 if (!getLangOptions().CPlusPlus0x) {
4417 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004418 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004419 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004420 diag::note_previous_template_specialization);
4421 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004422 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004423 return false;
4424
4425 case TSK_ExplicitInstantiationDeclaration:
4426 // We're explicity instantiating a definition for something for which we
4427 // were previously asked to suppress instantiations. That's fine.
4428 return false;
4429
4430 case TSK_ExplicitInstantiationDefinition:
4431 // C++0x [temp.spec]p5:
4432 // For a given template and a given set of template-arguments,
4433 // - an explicit instantiation definition shall appear at most once
4434 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004435 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004436 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004437 Diag(PrevPointOfInstantiation,
4438 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004439 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004440 return false;
4441 }
4442 break;
4443 }
4444
4445 assert(false && "Missing specialization/instantiation case?");
4446
4447 return false;
4448}
4449
John McCallb9c78482010-04-08 09:05:18 +00004450/// \brief Perform semantic analysis for the given dependent function
4451/// template specialization. The only possible way to get a dependent
4452/// function template specialization is with a friend declaration,
4453/// like so:
4454///
4455/// template <class T> void foo(T);
4456/// template <class T> class A {
4457/// friend void foo<>(T);
4458/// };
4459///
4460/// There really isn't any useful analysis we can do here, so we
4461/// just store the information.
4462bool
4463Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4464 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4465 LookupResult &Previous) {
4466 // Remove anything from Previous that isn't a function template in
4467 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00004468 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00004469 LookupResult::Filter F = Previous.makeFilter();
4470 while (F.hasNext()) {
4471 NamedDecl *D = F.next()->getUnderlyingDecl();
4472 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00004473 !FDLookupContext->InEnclosingNamespaceSetOf(
4474 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00004475 F.erase();
4476 }
4477 F.done();
4478
4479 // Should this be diagnosed here?
4480 if (Previous.empty()) return true;
4481
4482 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4483 ExplicitTemplateArgs);
4484 return false;
4485}
4486
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004487/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004488/// specialization.
4489///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004490/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004491/// explicit function template specialization. On successful completion,
4492/// the function declaration \p FD will become a function template
4493/// specialization.
4494///
4495/// \param FD the function declaration, which will be updated to become a
4496/// function template specialization.
4497///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004498/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4499/// if any. Note that this may be valid info even when 0 arguments are
4500/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4501/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004502///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004503/// \param PrevDecl the set of declarations that may be specialized by
4504/// this function specialization.
4505bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004506Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004507 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004508 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004509 // The set of function template specializations that could match this
4510 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004511 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004512
Sebastian Redl50c68252010-08-31 00:36:30 +00004513 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00004514 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4515 I != E; ++I) {
4516 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4517 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004518 // Only consider templates found within the same semantic lookup scope as
4519 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00004520 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4521 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004522 continue;
4523
4524 // C++ [temp.expl.spec]p11:
4525 // A trailing template-argument can be left unspecified in the
4526 // template-id naming an explicit function template specialization
4527 // provided it can be deduced from the function argument type.
4528 // Perform template argument deduction to determine whether we may be
4529 // specializing this template.
4530 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004531 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004532 FunctionDecl *Specialization = 0;
4533 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004534 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004535 FD->getType(),
4536 Specialization,
4537 Info)) {
4538 // FIXME: Template argument deduction failed; record why it failed, so
4539 // that we can provide nifty diagnostics.
4540 (void)TDK;
4541 continue;
4542 }
4543
4544 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004545 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004546 }
4547 }
4548
Douglas Gregor5de279c2009-09-26 03:41:46 +00004549 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004550 UnresolvedSetIterator Result
4551 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4552 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004553 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004554 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004555 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004556 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004557 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004558 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004559 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004560
4561 // Ignore access information; it doesn't figure into redeclaration checking.
4562 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004563 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004564
4565 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004566 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004567
4568 // If this is a friend declaration, then we're not really declaring
4569 // an explicit specialization.
4570 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004571
Douglas Gregor54888652009-10-07 00:13:32 +00004572 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004573 if (!isFriend &&
4574 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004575 Specialization->getPrimaryTemplate(),
4576 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004577 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004578 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004579
4580 // C++ [temp.expl.spec]p6:
4581 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004582 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004583 // before the first use of that specialization that would cause an implicit
4584 // instantiation to take place, in every translation unit in which such a
4585 // use occurs; no diagnostic is required.
4586 FunctionTemplateSpecializationInfo *SpecInfo
4587 = Specialization->getTemplateSpecializationInfo();
4588 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004589
Abramo Bagnara8075c852010-06-12 07:44:57 +00004590 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00004591 if (!isFriend &&
4592 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004593 TSK_ExplicitSpecialization,
4594 Specialization,
4595 SpecInfo->getTemplateSpecializationKind(),
4596 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004597 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004598 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004599
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004600 // Mark the prior declaration as an explicit specialization, so that later
4601 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004602 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00004603 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004604 MarkUnusedFileScopedDecl(Specialization);
4605 }
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004606
4607 // Turn the given function declaration into a function template
4608 // specialization, with the template arguments from the previous
4609 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004610 // Take copies of (semantic and syntactic) template argument lists.
4611 const TemplateArgumentList* TemplArgs = new (Context)
4612 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4613 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4614 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004615 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004616 TemplArgs, /*InsertPos=*/0,
4617 SpecInfo->getTemplateSpecializationKind(),
4618 TemplArgsAsWritten);
4619
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004620 // The "previous declaration" for this function template specialization is
4621 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004622 Previous.clear();
4623 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004624 return false;
4625}
4626
Douglas Gregor86d142a2009-10-08 07:24:58 +00004627/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004628/// specialization.
4629///
4630/// This routine performs all of the semantic analysis required for an
4631/// explicit member function specialization. On successful completion,
4632/// the function declaration \p FD will become a member function
4633/// specialization.
4634///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004635/// \param Member the member declaration, which will be updated to become a
4636/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004637///
John McCall1f82f242009-11-18 22:49:29 +00004638/// \param Previous the set of declarations, one of which may be specialized
4639/// by this function specialization; the set will be modified to contain the
4640/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004641bool
John McCall1f82f242009-11-18 22:49:29 +00004642Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004643 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004644
Douglas Gregor86d142a2009-10-08 07:24:58 +00004645 // Try to find the member we are instantiating.
4646 NamedDecl *Instantiation = 0;
4647 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004648 MemberSpecializationInfo *MSInfo = 0;
4649
John McCall1f82f242009-11-18 22:49:29 +00004650 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004651 // Nowhere to look anyway.
4652 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004653 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4654 I != E; ++I) {
4655 NamedDecl *D = (*I)->getUnderlyingDecl();
4656 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004657 if (Context.hasSameType(Function->getType(), Method->getType())) {
4658 Instantiation = Method;
4659 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004660 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004661 break;
4662 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004663 }
4664 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004665 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004666 VarDecl *PrevVar;
4667 if (Previous.isSingleResult() &&
4668 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004669 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004670 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004671 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004672 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004673 }
4674 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004675 CXXRecordDecl *PrevRecord;
4676 if (Previous.isSingleResult() &&
4677 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4678 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004679 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004680 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004681 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004682 }
4683
4684 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004685 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004686 // specializations are always out-of-line, the caller will complain about
4687 // this mismatch later.
4688 return false;
4689 }
John McCalle820e5e2010-04-13 20:37:33 +00004690
4691 // If this is a friend, just bail out here before we start turning
4692 // things into explicit specializations.
4693 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4694 // Preserve instantiation information.
4695 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4696 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4697 cast<CXXMethodDecl>(InstantiatedFrom),
4698 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4699 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4700 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4701 cast<CXXRecordDecl>(InstantiatedFrom),
4702 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4703 }
4704
4705 Previous.clear();
4706 Previous.addDecl(Instantiation);
4707 return false;
4708 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004709
Douglas Gregor86d142a2009-10-08 07:24:58 +00004710 // Make sure that this is a specialization of a member.
4711 if (!InstantiatedFrom) {
4712 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4713 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004714 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4715 return true;
4716 }
4717
Douglas Gregor06db9f52009-10-12 20:18:28 +00004718 // C++ [temp.expl.spec]p6:
4719 // If a template, a member template or the member of a class template is
4720 // explicitly specialized then that spe- cialization shall be declared
4721 // before the first use of that specialization that would cause an implicit
4722 // instantiation to take place, in every translation unit in which such a
4723 // use occurs; no diagnostic is required.
4724 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004725
Abramo Bagnara8075c852010-06-12 07:44:57 +00004726 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00004727 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4728 TSK_ExplicitSpecialization,
4729 Instantiation,
4730 MSInfo->getTemplateSpecializationKind(),
4731 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004732 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004733 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004734
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004735 // Check the scope of this explicit specialization.
4736 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004737 InstantiatedFrom,
4738 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004739 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004740 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004741
Douglas Gregor86d142a2009-10-08 07:24:58 +00004742 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004743 // the original declaration to note that it is an explicit specialization
4744 // (if it was previously an implicit instantiation). This latter step
4745 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004746 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004747 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4748 if (InstantiationFunction->getTemplateSpecializationKind() ==
4749 TSK_ImplicitInstantiation) {
4750 InstantiationFunction->setTemplateSpecializationKind(
4751 TSK_ExplicitSpecialization);
4752 InstantiationFunction->setLocation(Member->getLocation());
4753 }
4754
Douglas Gregor86d142a2009-10-08 07:24:58 +00004755 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4756 cast<CXXMethodDecl>(InstantiatedFrom),
4757 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004758 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004759 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004760 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4761 if (InstantiationVar->getTemplateSpecializationKind() ==
4762 TSK_ImplicitInstantiation) {
4763 InstantiationVar->setTemplateSpecializationKind(
4764 TSK_ExplicitSpecialization);
4765 InstantiationVar->setLocation(Member->getLocation());
4766 }
4767
Douglas Gregor86d142a2009-10-08 07:24:58 +00004768 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4769 cast<VarDecl>(InstantiatedFrom),
4770 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004771 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004772 } else {
4773 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004774 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4775 if (InstantiationClass->getTemplateSpecializationKind() ==
4776 TSK_ImplicitInstantiation) {
4777 InstantiationClass->setTemplateSpecializationKind(
4778 TSK_ExplicitSpecialization);
4779 InstantiationClass->setLocation(Member->getLocation());
4780 }
4781
Douglas Gregor86d142a2009-10-08 07:24:58 +00004782 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004783 cast<CXXRecordDecl>(InstantiatedFrom),
4784 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004785 }
4786
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004787 // Save the caller the trouble of having to figure out which declaration
4788 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004789 Previous.clear();
4790 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004791 return false;
4792}
4793
Douglas Gregore47f5a72009-10-14 23:41:34 +00004794/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004795///
4796/// \returns true if a serious error occurs, false otherwise.
4797static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00004798 SourceLocation InstLoc,
4799 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00004800 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
4801 DeclContext *CurContext = S.CurContext->getRedeclContext();
Douglas Gregore47f5a72009-10-14 23:41:34 +00004802
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004803 if (CurContext->isRecord()) {
4804 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4805 << D;
4806 return true;
4807 }
4808
Douglas Gregore47f5a72009-10-14 23:41:34 +00004809 // C++0x [temp.explicit]p2:
4810 // An explicit instantiation shall appear in an enclosing namespace of its
4811 // template.
4812 //
4813 // This is DR275, which we do not retroactively apply to C++98/03.
4814 if (S.getLangOptions().CPlusPlus0x &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004815 !CurContext->Encloses(OrigContext)) {
4816 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004817 S.Diag(InstLoc,
4818 S.getLangOptions().CPlusPlus0x?
4819 diag::err_explicit_instantiation_out_of_scope
4820 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004821 << D << NS;
4822 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004823 S.Diag(InstLoc,
4824 S.getLangOptions().CPlusPlus0x?
4825 diag::err_explicit_instantiation_must_be_global
4826 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004827 << D;
4828 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004829 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004830 }
Sebastian Redl50c68252010-08-31 00:36:30 +00004831
Douglas Gregore47f5a72009-10-14 23:41:34 +00004832 // C++0x [temp.explicit]p2:
4833 // If the name declared in the explicit instantiation is an unqualified
4834 // name, the explicit instantiation shall appear in the namespace where
4835 // its template is declared or, if that namespace is inline (7.3.1), any
4836 // namespace from its enclosing namespace set.
4837 if (WasQualifiedName)
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004838 return false;
Sebastian Redl50c68252010-08-31 00:36:30 +00004839
4840 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004841 return false;
Sebastian Redl50c68252010-08-31 00:36:30 +00004842
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004843 S.Diag(InstLoc,
4844 S.getLangOptions().CPlusPlus0x?
4845 diag::err_explicit_instantiation_unqualified_wrong_namespace
4846 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Sebastian Redl50c68252010-08-31 00:36:30 +00004847 << D << OrigContext;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004848 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004849 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004850}
4851
4852/// \brief Determine whether the given scope specifier has a template-id in it.
4853static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4854 if (!SS.isSet())
4855 return false;
4856
4857 // C++0x [temp.explicit]p2:
4858 // If the explicit instantiation is for a member function, a member class
4859 // or a static data member of a class template specialization, the name of
4860 // the class template specialization in the qualified-id for the member
4861 // name shall be a simple-template-id.
4862 //
4863 // C++98 has the same restriction, just worded differently.
4864 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4865 NNS; NNS = NNS->getPrefix())
4866 if (Type *T = NNS->getAsType())
4867 if (isa<TemplateSpecializationType>(T))
4868 return true;
4869
4870 return false;
4871}
4872
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004873// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00004874DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004875Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004876 SourceLocation ExternLoc,
4877 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004878 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004879 SourceLocation KWLoc,
4880 const CXXScopeSpec &SS,
4881 TemplateTy TemplateD,
4882 SourceLocation TemplateNameLoc,
4883 SourceLocation LAngleLoc,
4884 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004885 SourceLocation RAngleLoc,
4886 AttributeList *Attr) {
4887 // Find the class template we're specializing
4888 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004889 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004890 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4891
4892 // Check that the specialization uses the same tag kind as the
4893 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004894 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4895 assert(Kind != TTK_Enum &&
4896 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004897 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004898 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004899 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004900 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004901 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004902 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004903 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004904 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004905 diag::note_previous_use);
4906 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4907 }
4908
Douglas Gregore47f5a72009-10-14 23:41:34 +00004909 // C++0x [temp.explicit]p2:
4910 // There are two forms of explicit instantiation: an explicit instantiation
4911 // definition and an explicit instantiation declaration. An explicit
4912 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004913 TemplateSpecializationKind TSK
4914 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4915 : TSK_ExplicitInstantiationDeclaration;
4916
Douglas Gregora1f49972009-05-13 00:25:59 +00004917 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004918 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004919 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004920
4921 // Check that the template argument list is well-formed for this
4922 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004923 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4924 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004925 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4926 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004927 return true;
4928
Mike Stump11289f42009-09-09 15:08:12 +00004929 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004930 ClassTemplate->getTemplateParameters()->size()) &&
4931 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004932
Douglas Gregora1f49972009-05-13 00:25:59 +00004933 // Find the class template specialization declaration that
4934 // corresponds to these arguments.
Douglas Gregora1f49972009-05-13 00:25:59 +00004935 void *InsertPos = 0;
4936 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004937 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4938 Converted.flatSize(), InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004939
Abramo Bagnara8075c852010-06-12 07:44:57 +00004940 TemplateSpecializationKind PrevDecl_TSK
4941 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4942
Douglas Gregor54888652009-10-07 00:13:32 +00004943 // C++0x [temp.explicit]p2:
4944 // [...] An explicit instantiation shall appear in an enclosing
4945 // namespace of its template. [...]
4946 //
4947 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004948 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4949 SS.isSet()))
4950 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004951
Douglas Gregora1f49972009-05-13 00:25:59 +00004952 ClassTemplateSpecializationDecl *Specialization = 0;
4953
Douglas Gregor0681a352009-11-25 06:01:46 +00004954 bool ReusedDecl = false;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004955 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004956 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00004957 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004958 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004959 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004960 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00004961 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00004962
Abramo Bagnara8075c852010-06-12 07:44:57 +00004963 // Even though HasNoEffect == true means that this explicit instantiation
4964 // has no effect on semantics, we go on to put its syntax in the AST.
4965
4966 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4967 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004968 // Since the only prior class template specialization with these
4969 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00004970 // declaration node as our own, updating the source location
4971 // for the template name to reflect our new declaration.
4972 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004973 Specialization = PrevDecl;
4974 Specialization->setLocation(TemplateNameLoc);
4975 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004976 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004977 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004978 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004979
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004980 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004981 // Create a new class template specialization declaration node for
4982 // this explicit specialization.
4983 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004984 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00004985 ClassTemplate->getDeclContext(),
4986 TemplateNameLoc,
4987 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004988 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004989 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004990
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004991 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00004992 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004993 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004994 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004995 }
4996
4997 // Build the fully-sugared type for this explicit instantiation as
4998 // the user wrote in the explicit instantiation itself. This means
4999 // that we'll pretty-print the type retrieved from the
5000 // specialization's declaration the way that the user actually wrote
5001 // the explicit instantiation, rather than formatting the name based
5002 // on the "canonical" representation used to store the template
5003 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00005004 TypeSourceInfo *WrittenTy
5005 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5006 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00005007 Context.getTypeDeclType(Specialization));
5008 Specialization->setTypeAsWritten(WrittenTy);
5009 TemplateArgsIn.release();
5010
Abramo Bagnara8075c852010-06-12 07:44:57 +00005011 // Set source locations for keywords.
5012 Specialization->setExternLoc(ExternLoc);
5013 Specialization->setTemplateKeywordLoc(TemplateLoc);
5014
5015 // Add the explicit instantiation into its lexical context. However,
5016 // since explicit instantiations are never found by name lookup, we
5017 // just put it into the declaration context directly.
5018 Specialization->setLexicalDeclContext(CurContext);
5019 CurContext->addDecl(Specialization);
5020
5021 // Syntax is now OK, so return if it has no other effect on semantics.
5022 if (HasNoEffect) {
5023 // Set the template specialization kind.
5024 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00005025 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00005026 }
Douglas Gregora1f49972009-05-13 00:25:59 +00005027
5028 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00005029 // A definition of a class template or class member template
5030 // shall be in scope at the point of the explicit instantiation of
5031 // the class template or class member template.
5032 //
5033 // This check comes when we actually try to perform the
5034 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00005035 ClassTemplateSpecializationDecl *Def
5036 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005037 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00005038 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00005039 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00005040 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00005041 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00005042 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5043 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00005044
Douglas Gregor1d957a32009-10-27 18:42:08 +00005045 // Instantiate the members of this class template specialization.
5046 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005047 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00005048 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00005049 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5050
5051 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5052 // TSK_ExplicitInstantiationDefinition
5053 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5054 TSK == TSK_ExplicitInstantiationDefinition)
5055 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00005056
Douglas Gregor12e49d32009-10-15 22:53:21 +00005057 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00005058 }
Douglas Gregora1f49972009-05-13 00:25:59 +00005059
Abramo Bagnara8075c852010-06-12 07:44:57 +00005060 // Set the template specialization kind.
5061 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00005062 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00005063}
5064
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005065// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00005066DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00005067Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00005068 SourceLocation ExternLoc,
5069 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005070 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005071 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005072 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005073 IdentifierInfo *Name,
5074 SourceLocation NameLoc,
5075 AttributeList *Attr) {
5076
Douglas Gregord6ab8742009-05-28 23:31:59 +00005077 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00005078 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00005079 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00005080 KWLoc, SS, Name, NameLoc, Attr, AS_none,
5081 MultiTemplateParamsArg(*this, 0, 0),
Douglas Gregor0bf31402010-10-08 23:50:27 +00005082 Owned, IsDependent, false,
5083 TypeResult());
John McCall7f41d982009-09-11 04:59:25 +00005084 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
5085
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005086 if (!TagD)
5087 return true;
5088
John McCall48871652010-08-21 09:40:31 +00005089 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005090 if (Tag->isEnum()) {
5091 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
5092 << Context.getTypeDeclType(Tag);
5093 return true;
5094 }
5095
Douglas Gregorb8006faf2009-05-27 17:30:49 +00005096 if (Tag->isInvalidDecl())
5097 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005098
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005099 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
5100 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
5101 if (!Pattern) {
5102 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
5103 << Context.getTypeDeclType(Record);
5104 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
5105 return true;
5106 }
5107
Douglas Gregore47f5a72009-10-14 23:41:34 +00005108 // C++0x [temp.explicit]p2:
5109 // If the explicit instantiation is for a class or member class, the
5110 // elaborated-type-specifier in the declaration shall include a
5111 // simple-template-id.
5112 //
5113 // C++98 has the same restriction, just worded differently.
5114 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00005115 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005116 << Record << SS.getRange();
5117
5118 // C++0x [temp.explicit]p2:
5119 // There are two forms of explicit instantiation: an explicit instantiation
5120 // definition and an explicit instantiation declaration. An explicit
5121 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00005122 TemplateSpecializationKind TSK
5123 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5124 : TSK_ExplicitInstantiationDeclaration;
5125
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005126 // C++0x [temp.explicit]p2:
5127 // [...] An explicit instantiation shall appear in an enclosing
5128 // namespace of its template. [...]
5129 //
5130 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00005131 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005132
5133 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00005134 CXXRecordDecl *PrevDecl
5135 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005136 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00005137 PrevDecl = Record;
5138 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005139 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00005140 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005141 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00005142 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005143 PrevDecl,
5144 MSInfo->getTemplateSpecializationKind(),
5145 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005146 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005147 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005148 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005149 return TagD;
5150 }
5151
Douglas Gregor12e49d32009-10-15 22:53:21 +00005152 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005153 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00005154 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00005155 // C++ [temp.explicit]p3:
5156 // A definition of a member class of a class template shall be in scope
5157 // at the point of an explicit instantiation of the member class.
5158 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005159 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00005160 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00005161 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
5162 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00005163 Diag(Pattern->getLocation(), diag::note_forward_declaration)
5164 << Pattern;
5165 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005166 } else {
5167 if (InstantiateClass(NameLoc, Record, Def,
5168 getTemplateInstantiationArgs(Record),
5169 TSK))
5170 return true;
5171
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005172 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00005173 if (!RecordDef)
5174 return true;
5175 }
5176 }
5177
5178 // Instantiate all of the members of the class.
5179 InstantiateClassMembers(NameLoc, RecordDef,
5180 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005181
Douglas Gregor88d292c2010-05-13 16:44:06 +00005182 if (TSK == TSK_ExplicitInstantiationDefinition)
5183 MarkVTableUsed(NameLoc, RecordDef, true);
5184
Mike Stump87c57ac2009-05-16 07:39:55 +00005185 // FIXME: We don't have any representation for explicit instantiations of
5186 // member classes. Such a representation is not needed for compilation, but it
5187 // should be available for clients that want to see all of the declarations in
5188 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005189 return TagD;
5190}
5191
John McCallfaf5fb42010-08-26 23:41:50 +00005192DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
5193 SourceLocation ExternLoc,
5194 SourceLocation TemplateLoc,
5195 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005196 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005197 // TODO: check if/when DNInfo should replace Name.
5198 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5199 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00005200 if (!Name) {
5201 if (!D.isInvalidType())
5202 Diag(D.getDeclSpec().getSourceRange().getBegin(),
5203 diag::err_explicit_instantiation_requires_name)
5204 << D.getDeclSpec().getSourceRange()
5205 << D.getSourceRange();
5206
5207 return true;
5208 }
5209
5210 // The scope passed in may not be a decl scope. Zip up the scope tree until
5211 // we find one that is.
5212 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5213 (S->getFlags() & Scope::TemplateParamScope) != 0)
5214 S = S->getParent();
5215
5216 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00005217 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5218 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00005219 if (R.isNull())
5220 return true;
5221
5222 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5223 // Cannot explicitly instantiate a typedef.
5224 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5225 << Name;
5226 return true;
5227 }
5228
Douglas Gregor3c74d412009-10-14 20:14:33 +00005229 // C++0x [temp.explicit]p1:
5230 // [...] An explicit instantiation of a function template shall not use the
5231 // inline or constexpr specifiers.
5232 // Presumably, this also applies to member functions of class templates as
5233 // well.
5234 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5235 Diag(D.getDeclSpec().getInlineSpecLoc(),
5236 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00005237 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00005238
5239 // FIXME: check for constexpr specifier.
5240
Douglas Gregore47f5a72009-10-14 23:41:34 +00005241 // C++0x [temp.explicit]p2:
5242 // There are two forms of explicit instantiation: an explicit instantiation
5243 // definition and an explicit instantiation declaration. An explicit
5244 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00005245 TemplateSpecializationKind TSK
5246 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5247 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005248
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005249 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005250 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00005251
5252 if (!R->isFunctionType()) {
5253 // C++ [temp.explicit]p1:
5254 // A [...] static data member of a class template can be explicitly
5255 // instantiated from the member definition associated with its class
5256 // template.
John McCall27b18f82009-11-17 02:14:36 +00005257 if (Previous.isAmbiguous())
5258 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00005259
John McCall67c00872009-12-02 08:25:40 +00005260 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005261 if (!Prev || !Prev->isStaticDataMember()) {
5262 // We expect to see a data data member here.
5263 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5264 << Name;
5265 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5266 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005267 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005268 return true;
5269 }
5270
5271 if (!Prev->getInstantiatedFromStaticDataMember()) {
5272 // FIXME: Check for explicit specialization?
5273 Diag(D.getIdentifierLoc(),
5274 diag::err_explicit_instantiation_data_member_not_instantiated)
5275 << Prev;
5276 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5277 // FIXME: Can we provide a note showing where this was declared?
5278 return true;
5279 }
5280
Douglas Gregore47f5a72009-10-14 23:41:34 +00005281 // C++0x [temp.explicit]p2:
5282 // If the explicit instantiation is for a member function, a member class
5283 // or a static data member of a class template specialization, the name of
5284 // the class template specialization in the qualified-id for the member
5285 // name shall be a simple-template-id.
5286 //
5287 // C++98 has the same restriction, just worded differently.
5288 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5289 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005290 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005291 << Prev << D.getCXXScopeSpec().getRange();
5292
5293 // Check the scope of this explicit instantiation.
5294 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5295
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005296 // Verify that it is okay to explicitly instantiate here.
5297 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5298 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00005299 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005300 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005301 MSInfo->getTemplateSpecializationKind(),
5302 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005303 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005304 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005305 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005306 return (Decl*) 0;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005307
Douglas Gregor450f00842009-09-25 18:43:00 +00005308 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005309 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005310 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005311 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregor450f00842009-09-25 18:43:00 +00005312
5313 // FIXME: Create an ExplicitInstantiation node?
John McCall48871652010-08-21 09:40:31 +00005314 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005315 }
5316
Douglas Gregor0e876e02009-09-25 23:53:26 +00005317 // If the declarator is a template-id, translate the parser's template
5318 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005319 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005320 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005321 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5322 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005323 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5324 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005325 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5326 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005327 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005328 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005329 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005330 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005331 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005332
Douglas Gregor450f00842009-09-25 18:43:00 +00005333 // C++ [temp.explicit]p1:
5334 // A [...] function [...] can be explicitly instantiated from its template.
5335 // A member function [...] of a class template can be explicitly
5336 // instantiated from the member definition associated with its class
5337 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005338 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005339 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5340 P != PEnd; ++P) {
5341 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005342 if (!HasExplicitTemplateArgs) {
5343 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5344 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5345 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005346
John McCall58cc69d2010-01-27 01:50:18 +00005347 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005348 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5349 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005350 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005351 }
5352 }
5353
5354 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5355 if (!FunTmpl)
5356 continue;
5357
John McCallbc077cf2010-02-08 23:07:23 +00005358 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005359 FunctionDecl *Specialization = 0;
5360 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005361 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005362 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005363 R, Specialization, Info)) {
5364 // FIXME: Keep track of almost-matches?
5365 (void)TDK;
5366 continue;
5367 }
5368
John McCall58cc69d2010-01-27 01:50:18 +00005369 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005370 }
5371
5372 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005373 UnresolvedSetIterator Result
5374 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005375 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005376 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5377 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5378 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005379
John McCall58cc69d2010-01-27 01:50:18 +00005380 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005381 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005382
5383 // Ignore access control bits, we don't need them for redeclaration checking.
5384 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005385
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005386 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005387 Diag(D.getIdentifierLoc(),
5388 diag::err_explicit_instantiation_member_function_not_instantiated)
5389 << Specialization
5390 << (Specialization->getTemplateSpecializationKind() ==
5391 TSK_ExplicitSpecialization);
5392 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5393 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005394 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005395
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005396 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005397 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5398 PrevDecl = Specialization;
5399
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005400 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005401 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005402 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005403 PrevDecl,
5404 PrevDecl->getTemplateSpecializationKind(),
5405 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005406 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005407 return true;
5408
5409 // FIXME: We may still want to build some representation of this
5410 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00005411 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005412 return (Decl*) 0;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005413 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005414
5415 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005416
5417 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005418 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005419
Douglas Gregore47f5a72009-10-14 23:41:34 +00005420 // C++0x [temp.explicit]p2:
5421 // If the explicit instantiation is for a member function, a member class
5422 // or a static data member of a class template specialization, the name of
5423 // the class template specialization in the qualified-id for the member
5424 // name shall be a simple-template-id.
5425 //
5426 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005427 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005428 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005429 D.getCXXScopeSpec().isSet() &&
5430 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5431 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005432 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005433 << Specialization << D.getCXXScopeSpec().getRange();
5434
5435 CheckExplicitInstantiationScope(*this,
5436 FunTmpl? (NamedDecl *)FunTmpl
5437 : Specialization->getInstantiatedFromMemberFunction(),
5438 D.getIdentifierLoc(),
5439 D.getCXXScopeSpec().isSet());
5440
Douglas Gregor450f00842009-09-25 18:43:00 +00005441 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCall48871652010-08-21 09:40:31 +00005442 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005443}
5444
John McCallfaf5fb42010-08-26 23:41:50 +00005445TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005446Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5447 const CXXScopeSpec &SS, IdentifierInfo *Name,
5448 SourceLocation TagLoc, SourceLocation NameLoc) {
5449 // This has to hold, because SS is expected to be defined.
5450 assert(Name && "Expected a name in a dependent tag");
5451
5452 NestedNameSpecifier *NNS
5453 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5454 if (!NNS)
5455 return true;
5456
Abramo Bagnara6150c882010-05-11 21:36:43 +00005457 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005458
Douglas Gregorba41d012010-04-24 16:38:41 +00005459 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5460 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005461 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005462 return true;
5463 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005464
5465 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallba7bf592010-08-24 05:47:05 +00005466 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCall7f41d982009-09-11 04:59:25 +00005467}
5468
John McCallfaf5fb42010-08-26 23:41:50 +00005469TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005470Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5471 const CXXScopeSpec &SS, const IdentifierInfo &II,
5472 SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005473 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005474 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5475 if (!NNS)
5476 return true;
5477
Douglas Gregorf7d77712010-06-16 22:31:08 +00005478 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5479 !getLangOptions().CPlusPlus0x)
5480 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5481 << FixItHint::CreateRemoval(TypenameLoc);
5482
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005483 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005484 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005485 if (T.isNull())
5486 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005487
5488 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5489 if (isa<DependentNameType>(T)) {
5490 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005491 TL.setKeywordLoc(TypenameLoc);
5492 TL.setQualifierRange(SS.getRange());
5493 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005494 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005495 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005496 TL.setKeywordLoc(TypenameLoc);
5497 TL.setQualifierRange(SS.getRange());
5498 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005499 }
5500
John McCallba7bf592010-08-24 05:47:05 +00005501 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00005502}
5503
John McCallfaf5fb42010-08-26 23:41:50 +00005504TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005505Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5506 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallba7bf592010-08-24 05:47:05 +00005507 ParsedType Ty) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00005508 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5509 !getLangOptions().CPlusPlus0x)
5510 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5511 << FixItHint::CreateRemoval(TypenameLoc);
5512
John McCallf7bcc812010-05-28 23:32:21 +00005513 TypeSourceInfo *InnerTSI = 0;
5514 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCallf7bcc812010-05-28 23:32:21 +00005515
5516 assert(isa<TemplateSpecializationType>(T) &&
5517 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005518
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005519 if (computeDeclContext(SS, false)) {
5520 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005521 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005522 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005523
5524 // Push the inner type, preserving its source locations if possible.
5525 TypeLocBuilder Builder;
5526 if (InnerTSI)
5527 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5528 else
5529 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5530
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005531 /* Note: NNS already embedded in template specialization type T. */
5532 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCallf7bcc812010-05-28 23:32:21 +00005533 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5534 TL.setKeywordLoc(TypenameLoc);
5535 TL.setQualifierRange(SS.getRange());
5536
5537 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallba7bf592010-08-24 05:47:05 +00005538 return CreateParsedType(T, TSI);
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005539 }
Mike Stump11289f42009-09-09 15:08:12 +00005540
John McCallc392f372010-06-11 00:33:02 +00005541 // TODO: it's really silly that we make a template specialization
5542 // type earlier only to drop it again here.
5543 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5544 DependentTemplateName *DTN =
5545 TST->getTemplateName().getAsDependentTemplateName();
5546 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005547 assert(DTN->getQualifier()
5548 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5549 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5550 DTN->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00005551 DTN->getIdentifier(),
5552 TST->getNumArgs(),
5553 TST->getArgs());
John McCall99b2fe52010-04-29 23:50:39 +00005554 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCallc392f372010-06-11 00:33:02 +00005555 DependentTemplateSpecializationTypeLoc TL =
5556 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5557 if (InnerTSI) {
5558 TemplateSpecializationTypeLoc TSTL =
5559 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5560 TL.setLAngleLoc(TSTL.getLAngleLoc());
5561 TL.setRAngleLoc(TSTL.getRAngleLoc());
5562 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5563 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5564 } else {
5565 TL.initializeLocal(SourceLocation());
5566 }
John McCallf7bcc812010-05-28 23:32:21 +00005567 TL.setKeywordLoc(TypenameLoc);
5568 TL.setQualifierRange(SS.getRange());
John McCallba7bf592010-08-24 05:47:05 +00005569 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00005570}
5571
Douglas Gregor333489b2009-03-27 23:10:48 +00005572/// \brief Build the type that describes a C++ typename specifier,
5573/// e.g., "typename T::type".
5574QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005575Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5576 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005577 SourceLocation KeywordLoc, SourceRange NNSRange,
5578 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005579 CXXScopeSpec SS;
5580 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005581 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005582
John McCall0b66eb32010-05-01 00:40:08 +00005583 DeclContext *Ctx = computeDeclContext(SS);
5584 if (!Ctx) {
5585 // If the nested-name-specifier is dependent and couldn't be
5586 // resolved to a type, build a typename type.
5587 assert(NNS->isDependent());
5588 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005589 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005590
John McCall0b66eb32010-05-01 00:40:08 +00005591 // If the nested-name-specifier refers to the current instantiation,
5592 // the "typename" keyword itself is superfluous. In C++03, the
5593 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5594 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00005595 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005596
John McCall0b66eb32010-05-01 00:40:08 +00005597 if (RequireCompleteDeclContext(SS, Ctx))
5598 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005599
5600 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005601 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005602 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005603 unsigned DiagID = 0;
5604 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005605 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005606 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005607 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005608 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005609
5610 case LookupResult::NotFoundInCurrentInstantiation:
5611 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005612 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005613
5614 case LookupResult::Found:
Douglas Gregorf7d77712010-06-16 22:31:08 +00005615 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005616 // We found a type. Build an ElaboratedType, since the
5617 // typename-specifier was just sugar.
5618 return Context.getElaboratedType(ETK_Typename, NNS,
5619 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005620 }
5621
5622 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005623 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005624 break;
5625
John McCalle61f2ba2009-11-18 02:36:19 +00005626 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005627 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005628 return QualType();
5629
Douglas Gregor333489b2009-03-27 23:10:48 +00005630 case LookupResult::FoundOverloaded:
5631 DiagID = diag::err_typename_nested_not_type;
5632 Referenced = *Result.begin();
5633 break;
5634
John McCall6538c932009-10-10 05:48:19 +00005635 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005636 return QualType();
5637 }
5638
5639 // If we get here, it's because name lookup did not find a
5640 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005641 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5642 IILoc);
5643 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005644 if (Referenced)
5645 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5646 << Name;
5647 return QualType();
5648}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005649
5650namespace {
5651 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005652 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005653 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005654 SourceLocation Loc;
5655 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005656
Douglas Gregor15acfb92009-08-06 16:20:37 +00005657 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005658 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5659
Mike Stump11289f42009-09-09 15:08:12 +00005660 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005661 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005662 DeclarationName Entity)
5663 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005664 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005665
5666 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005667 /// transformed.
5668 ///
5669 /// For the purposes of type reconstruction, a type has already been
5670 /// transformed if it is NULL or if it is not dependent.
5671 bool AlreadyTransformed(QualType T) {
5672 return T.isNull() || !T->isDependentType();
5673 }
Mike Stump11289f42009-09-09 15:08:12 +00005674
5675 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005676 /// rebuilt.
5677 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005678
Douglas Gregor15acfb92009-08-06 16:20:37 +00005679 /// \brief Returns the name of the entity whose type is being rebuilt.
5680 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005681
Douglas Gregoref6ab412009-10-27 06:26:26 +00005682 /// \brief Sets the "base" location and entity when that
5683 /// information is known based on another transformation.
5684 void setBase(SourceLocation Loc, DeclarationName Entity) {
5685 this->Loc = Loc;
5686 this->Entity = Entity;
5687 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00005688 };
5689}
5690
Douglas Gregor15acfb92009-08-06 16:20:37 +00005691/// \brief Rebuilds a type within the context of the current instantiation.
5692///
Mike Stump11289f42009-09-09 15:08:12 +00005693/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005694/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005695/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005696/// partial specialization thereof). This routine will rebuild that type now
5697/// that we have entered the declarator's scope, which may produce different
5698/// canonical types, e.g.,
5699///
5700/// \code
5701/// template<typename T>
5702/// struct X {
5703/// typedef T* pointer;
5704/// pointer data();
5705/// };
5706///
5707/// template<typename T>
5708/// typename X<T>::pointer X<T>::data() { ... }
5709/// \endcode
5710///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005711/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005712/// since we do not know that we can look into X<T> when we parsed the type.
5713/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005714/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005715/// as the canonical type of T*, allowing the return types of the out-of-line
5716/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005717TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5718 SourceLocation Loc,
5719 DeclarationName Name) {
5720 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005721 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005722
Douglas Gregor15acfb92009-08-06 16:20:37 +00005723 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5724 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005725}
Douglas Gregorbe999392009-09-15 16:23:51 +00005726
John McCalldadc5752010-08-24 06:29:42 +00005727ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00005728 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5729 DeclarationName());
5730 return Rebuilder.TransformExpr(E);
5731}
5732
John McCall99b2fe52010-04-29 23:50:39 +00005733bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5734 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005735
5736 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5737 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5738 DeclarationName());
5739 NestedNameSpecifier *Rebuilt =
5740 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005741 if (!Rebuilt) return true;
5742
5743 SS.setScopeRep(Rebuilt);
5744 return false;
John McCall2408e322010-04-27 00:57:59 +00005745}
5746
Douglas Gregorbe999392009-09-15 16:23:51 +00005747/// \brief Produces a formatted string that describes the binding of
5748/// template parameters to template arguments.
5749std::string
5750Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5751 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005752 // FIXME: For variadic templates, we'll need to get the structured list.
5753 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5754 Args.flat_size());
5755}
5756
5757std::string
5758Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5759 const TemplateArgument *Args,
5760 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005761 std::string Result;
5762
Douglas Gregore62e6a02009-11-11 19:13:48 +00005763 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005764 return Result;
5765
5766 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005767 if (I >= NumArgs)
5768 break;
5769
Douglas Gregorbe999392009-09-15 16:23:51 +00005770 if (I == 0)
5771 Result += "[with ";
5772 else
5773 Result += ", ";
5774
5775 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5776 Result += Id->getName();
5777 } else {
5778 Result += '$';
5779 Result += llvm::utostr(I);
5780 }
5781
5782 Result += " = ";
5783
5784 switch (Args[I].getKind()) {
5785 case TemplateArgument::Null:
5786 Result += "<no value>";
5787 break;
5788
5789 case TemplateArgument::Type: {
5790 std::string TypeStr;
5791 Args[I].getAsType().getAsStringInternal(TypeStr,
5792 Context.PrintingPolicy);
5793 Result += TypeStr;
5794 break;
5795 }
5796
5797 case TemplateArgument::Declaration: {
5798 bool Unnamed = true;
5799 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5800 if (ND->getDeclName()) {
5801 Unnamed = false;
5802 Result += ND->getNameAsString();
5803 }
5804 }
5805
5806 if (Unnamed) {
5807 Result += "<anonymous>";
5808 }
5809 break;
5810 }
5811
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005812 case TemplateArgument::Template: {
5813 std::string Str;
5814 llvm::raw_string_ostream OS(Str);
5815 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5816 Result += OS.str();
5817 break;
5818 }
5819
Douglas Gregorbe999392009-09-15 16:23:51 +00005820 case TemplateArgument::Integral: {
5821 Result += Args[I].getAsIntegral()->toString(10);
5822 break;
5823 }
5824
5825 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005826 // FIXME: This is non-optimal, since we're regurgitating the
5827 // expression we were given.
5828 std::string Str;
5829 {
5830 llvm::raw_string_ostream OS(Str);
5831 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5832 Context.PrintingPolicy);
5833 }
5834 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005835 break;
5836 }
5837
5838 case TemplateArgument::Pack:
5839 // FIXME: Format template argument packs
5840 Result += "<template argument pack>";
5841 break;
5842 }
5843 }
5844
5845 Result += ']';
5846 return Result;
5847}