blob: 95b2223658cd52c17e3d30c3a185a6893145a822 [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor72c3f312008-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 Gregor99ebf652009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000011
John McCall2d887082010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Lookup.h"
John McCall5f1e0942010-08-24 08:50:51 +000014#include "clang/Sema/Scope.h"
John McCall7cd088e2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000016#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000017#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000019#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000020#include "clang/AST/ExprCXX.h"
John McCall92b7f702010-03-11 07:50:04 +000021#include "clang/AST/DeclFriend.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000022#include "clang/AST/DeclTemplate.h"
John McCall4e2cbb22010-10-20 05:44:58 +000023#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor5f3aeb62010-10-13 00:27:52 +000024#include "clang/AST/TypeVisitor.h"
John McCall19510852010-08-20 18:27:03 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000027#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000029#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000030using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000031using namespace sema;
Douglas Gregor72c3f312008-12-05 18:15:24 +000032
Douglas Gregor2dd078a2009-09-02 22:59:36 +000033/// \brief Determine whether the declaration found is acceptable as the name
34/// of a template and, if so, return that template declaration. Otherwise,
35/// returns NULL.
John McCallad00b772010-06-16 08:42:20 +000036static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
37 NamedDecl *Orig) {
38 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000039
Douglas Gregor2dd078a2009-09-02 22:59:36 +000040 if (isa<TemplateDecl>(D))
John McCallad00b772010-06-16 08:42:20 +000041 return Orig;
Mike Stump1eb44332009-09-09 15:08:12 +000042
Douglas Gregor2dd078a2009-09-02 22:59:36 +000043 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
44 // C++ [temp.local]p1:
45 // Like normal (non-template) classes, class templates have an
46 // injected-class-name (Clause 9). The injected-class-name
47 // can be used with or without a template-argument-list. When
48 // it is used without a template-argument-list, it is
49 // equivalent to the injected-class-name followed by the
50 // template-parameters of the class template enclosed in
51 // <>. When it is used with a template-argument-list, it
52 // refers to the specified class template specialization,
53 // which could be the current specialization or another
54 // specialization.
55 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000056 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000057 if (Record->getDescribedClassTemplate())
58 return Record->getDescribedClassTemplate();
59
60 if (ClassTemplateSpecializationDecl *Spec
61 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
62 return Spec->getSpecializedTemplate();
63 }
Mike Stump1eb44332009-09-09 15:08:12 +000064
Douglas Gregor2dd078a2009-09-02 22:59:36 +000065 return 0;
66 }
Mike Stump1eb44332009-09-09 15:08:12 +000067
Douglas Gregor2dd078a2009-09-02 22:59:36 +000068 return 0;
69}
70
John McCallf7a1a742009-11-24 19:00:30 +000071static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor01e56ae2010-04-12 20:54:26 +000072 // The set of class templates we've already seen.
73 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCallf7a1a742009-11-24 19:00:30 +000074 LookupResult::Filter filter = R.makeFilter();
75 while (filter.hasNext()) {
76 NamedDecl *Orig = filter.next();
John McCallad00b772010-06-16 08:42:20 +000077 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
John McCallf7a1a742009-11-24 19:00:30 +000078 if (!Repl)
79 filter.erase();
Douglas Gregor01e56ae2010-04-12 20:54:26 +000080 else if (Repl != Orig) {
81
82 // C++ [temp.local]p3:
83 // A lookup that finds an injected-class-name (10.2) can result in an
84 // ambiguity in certain cases (for example, if it is found in more than
85 // one base class). If all of the injected-class-names that are found
86 // refer to specializations of the same class template, and if the name
87 // is followed by a template-argument-list, the reference refers to the
88 // class template itself and not a specialization thereof, and is not
89 // ambiguous.
90 //
91 // FIXME: Will we eventually have to do the same for alias templates?
92 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
93 if (!ClassTemplates.insert(ClassTmpl)) {
94 filter.erase();
95 continue;
96 }
John McCall8ba66912010-08-13 07:02:08 +000097
98 // FIXME: we promote access to public here as a workaround to
99 // the fact that LookupResult doesn't let us remember that we
100 // found this template through a particular injected class name,
101 // which means we end up doing nasty things to the invariants.
102 // Pretending that access is public is *much* safer.
103 filter.replace(Repl, AS_public);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000104 }
John McCallf7a1a742009-11-24 19:00:30 +0000105 }
106 filter.done();
107}
108
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000109TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000110 CXXScopeSpec &SS,
Abramo Bagnara7c153532010-08-06 12:11:11 +0000111 bool hasTemplateKeyword,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000112 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +0000113 ParsedType ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000114 bool EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000115 TemplateTy &TemplateResult,
116 bool &MemberOfUnknownSpecialization) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000117 assert(getLangOptions().CPlusPlus && "No template names in C!");
118
Douglas Gregor014e88d2009-11-03 23:16:33 +0000119 DeclarationName TName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000120 MemberOfUnknownSpecialization = false;
Douglas Gregor014e88d2009-11-03 23:16:33 +0000121
122 switch (Name.getKind()) {
123 case UnqualifiedId::IK_Identifier:
124 TName = DeclarationName(Name.Identifier);
125 break;
126
127 case UnqualifiedId::IK_OperatorFunctionId:
128 TName = Context.DeclarationNames.getCXXOperatorName(
129 Name.OperatorFunctionId.Operator);
130 break;
131
Sean Hunte6252d12009-11-28 08:58:14 +0000132 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +0000133 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
134 break;
Sean Hunte6252d12009-11-28 08:58:14 +0000135
Douglas Gregor014e88d2009-11-03 23:16:33 +0000136 default:
137 return TNK_Non_template;
138 }
Mike Stump1eb44332009-09-09 15:08:12 +0000139
John McCallb3d87482010-08-24 05:47:05 +0000140 QualType ObjectType = ObjectTypePtr.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Douglas Gregorbfea2392009-12-31 08:11:17 +0000142 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
143 LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000144 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
145 MemberOfUnknownSpecialization);
John McCall67d22fb2010-08-28 20:17:00 +0000146 if (R.empty()) return TNK_Non_template;
147 if (R.isAmbiguous()) {
148 // Suppress diagnostics; we'll redo this lookup later.
John McCallb8592062010-08-13 02:23:42 +0000149 R.suppressDiagnostics();
John McCall67d22fb2010-08-28 20:17:00 +0000150
151 // FIXME: we might have ambiguous templates, in which case we
152 // should at least parse them properly!
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000153 return TNK_Non_template;
John McCallb8592062010-08-13 02:23:42 +0000154 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000155
John McCall0bd6feb2009-12-02 08:04:21 +0000156 TemplateName Template;
157 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000158
John McCall0bd6feb2009-12-02 08:04:21 +0000159 unsigned ResultCount = R.end() - R.begin();
160 if (ResultCount > 1) {
161 // We assume that we'll preserve the qualifier from a function
162 // template name in other ways.
163 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
164 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000165
166 // We'll do this lookup again later.
167 R.suppressDiagnostics();
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000168 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000169 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
170
171 if (SS.isSet() && !SS.isInvalid()) {
172 NestedNameSpecifier *Qualifier
173 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c153532010-08-06 12:11:11 +0000174 Template = Context.getQualifiedTemplateName(Qualifier,
175 hasTemplateKeyword, TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000176 } else {
177 Template = TemplateName(TD);
178 }
179
John McCallb8592062010-08-13 02:23:42 +0000180 if (isa<FunctionTemplateDecl>(TD)) {
John McCall0bd6feb2009-12-02 08:04:21 +0000181 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000182
183 // We'll do this lookup again later.
184 R.suppressDiagnostics();
185 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000186 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
187 TemplateKind = TNK_Type_template;
188 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000189 }
Mike Stump1eb44332009-09-09 15:08:12 +0000190
John McCall0bd6feb2009-12-02 08:04:21 +0000191 TemplateResult = TemplateTy::make(Template);
192 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000193}
194
Douglas Gregor84d0a192010-01-12 21:28:44 +0000195bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
196 SourceLocation IILoc,
197 Scope *S,
198 const CXXScopeSpec *SS,
199 TemplateTy &SuggestedTemplate,
200 TemplateNameKind &SuggestedKind) {
201 // We can't recover unless there's a dependent scope specifier preceding the
202 // template name.
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000203 // FIXME: Typo correction?
Douglas Gregor84d0a192010-01-12 21:28:44 +0000204 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
205 computeDeclContext(*SS))
206 return false;
207
208 // The code is missing a 'template' keyword prior to the dependent template
209 // name.
210 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
211 Diag(IILoc, diag::err_template_kw_missing)
212 << Qualifier << II.getName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000213 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor84d0a192010-01-12 21:28:44 +0000214 SuggestedTemplate
215 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
216 SuggestedKind = TNK_Dependent_template_name;
217 return true;
218}
219
John McCallf7a1a742009-11-24 19:00:30 +0000220void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000221 Scope *S, CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +0000222 QualType ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000223 bool EnteringContext,
224 bool &MemberOfUnknownSpecialization) {
John McCallf7a1a742009-11-24 19:00:30 +0000225 // Determine where to perform name lookup
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000226 MemberOfUnknownSpecialization = false;
John McCallf7a1a742009-11-24 19:00:30 +0000227 DeclContext *LookupCtx = 0;
228 bool isDependent = false;
229 if (!ObjectType.isNull()) {
230 // This nested-name-specifier occurs in a member access expression, e.g.,
231 // x->B::f, and we are looking into the type of the object.
232 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
233 LookupCtx = computeDeclContext(ObjectType);
234 isDependent = ObjectType->isDependentType();
235 assert((isDependent || !ObjectType->isIncompleteType()) &&
236 "Caller should have completed object type");
237 } else if (SS.isSet()) {
238 // This nested-name-specifier occurs after another nested-name-specifier,
239 // so long into the context associated with the prior nested-name-specifier.
240 LookupCtx = computeDeclContext(SS, EnteringContext);
241 isDependent = isDependentScopeSpecifier(SS);
242
243 // The declaration context must be complete.
John McCall77bb1aa2010-05-01 00:40:08 +0000244 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCallf7a1a742009-11-24 19:00:30 +0000245 return;
246 }
247
248 bool ObjectTypeSearchedInScope = false;
249 if (LookupCtx) {
250 // Perform "qualified" name lookup into the declaration context we
251 // computed, which is either the type of the base of a member access
252 // expression or the declaration context associated with a prior
253 // nested-name-specifier.
254 LookupQualifiedName(Found, LookupCtx);
255
256 if (!ObjectType.isNull() && Found.empty()) {
257 // C++ [basic.lookup.classref]p1:
258 // In a class member access expression (5.2.5), if the . or -> token is
259 // immediately followed by an identifier followed by a <, the
260 // identifier must be looked up to determine whether the < is the
261 // beginning of a template argument list (14.2) or a less-than operator.
262 // The identifier is first looked up in the class of the object
263 // expression. If the identifier is not found, it is then looked up in
264 // the context of the entire postfix-expression and shall name a class
265 // or function template.
John McCallf7a1a742009-11-24 19:00:30 +0000266 if (S) LookupName(Found, S);
267 ObjectTypeSearchedInScope = true;
268 }
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000269 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregor2e933882010-01-12 17:06:20 +0000270 // We cannot look into a dependent object type or nested nme
271 // specifier.
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000272 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000273 return;
274 } else {
275 // Perform unqualified name lookup in the current scope.
276 LookupName(Found, S);
277 }
278
Douglas Gregor2e933882010-01-12 17:06:20 +0000279 if (Found.empty() && !isDependent) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000280 // If we did not find any names, attempt to correct any typos.
281 DeclarationName Name = Found.getLookupName();
Douglas Gregoraaf87162010-04-14 20:04:41 +0000282 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000283 false, CTC_CXXCasts)) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000284 FilterAcceptableTemplateNames(Context, Found);
John McCallad00b772010-06-16 08:42:20 +0000285 if (!Found.empty()) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000286 if (LookupCtx)
287 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
288 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000289 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000290 Found.getLookupName().getAsString());
291 else
292 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
293 << Name << Found.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000294 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000295 Found.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000296 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
297 Diag(Template->getLocation(), diag::note_previous_decl)
298 << Template->getDeclName();
John McCallad00b772010-06-16 08:42:20 +0000299 }
Douglas Gregorbfea2392009-12-31 08:11:17 +0000300 } else {
301 Found.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000302 Found.setLookupName(Name);
Douglas Gregorbfea2392009-12-31 08:11:17 +0000303 }
304 }
305
John McCallf7a1a742009-11-24 19:00:30 +0000306 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000307 if (Found.empty()) {
308 if (isDependent)
309 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000310 return;
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000311 }
John McCallf7a1a742009-11-24 19:00:30 +0000312
313 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
314 // C++ [basic.lookup.classref]p1:
315 // [...] If the lookup in the class of the object expression finds a
316 // template, the name is also looked up in the context of the entire
317 // postfix-expression and [...]
318 //
319 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
320 LookupOrdinaryName);
321 LookupName(FoundOuter, S);
322 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000323
John McCallf7a1a742009-11-24 19:00:30 +0000324 if (FoundOuter.empty()) {
325 // - if the name is not found, the name found in the class of the
326 // object expression is used, otherwise
327 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
328 // - if the name is found in the context of the entire
329 // postfix-expression and does not name a class template, the name
330 // found in the class of the object expression is used, otherwise
John McCallad00b772010-06-16 08:42:20 +0000331 } else if (!Found.isSuppressingDiagnostics()) {
John McCallf7a1a742009-11-24 19:00:30 +0000332 // - if the name found is a class template, it must refer to the same
333 // entity as the one found in the class of the object expression,
334 // otherwise the program is ill-formed.
335 if (!Found.isSingleResult() ||
336 Found.getFoundDecl()->getCanonicalDecl()
337 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
338 Diag(Found.getNameLoc(),
Jeffrey Yasskin21d07e42010-06-05 01:39:57 +0000339 diag::ext_nested_name_member_ref_lookup_ambiguous)
340 << Found.getLookupName()
341 << ObjectType;
John McCallf7a1a742009-11-24 19:00:30 +0000342 Diag(Found.getRepresentativeDecl()->getLocation(),
343 diag::note_ambig_member_ref_object_type)
344 << ObjectType;
345 Diag(FoundOuter.getFoundDecl()->getLocation(),
346 diag::note_ambig_member_ref_scope);
347
348 // Recover by taking the template that we found in the object
349 // expression's type.
350 }
351 }
352 }
353}
354
John McCall2f841ba2009-12-02 03:53:29 +0000355/// ActOnDependentIdExpression - Handle a dependent id-expression that
356/// was just parsed. This is only possible with an explicit scope
357/// specifier naming a dependent type.
John McCall60d7b3a2010-08-24 06:29:42 +0000358ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000359Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000360 const DeclarationNameInfo &NameInfo,
John McCall2f841ba2009-12-02 03:53:29 +0000361 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000362 const TemplateArgumentListInfo *TemplateArgs) {
363 NestedNameSpecifier *Qualifier
364 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallea1471e2010-05-20 01:18:31 +0000365
366 DeclContext *DC = getFunctionLevelDeclContext();
John McCallf7a1a742009-11-24 19:00:30 +0000367
John McCall2f841ba2009-12-02 03:53:29 +0000368 if (!isAddressOfOperand &&
John McCallea1471e2010-05-20 01:18:31 +0000369 isa<CXXMethodDecl>(DC) &&
370 cast<CXXMethodDecl>(DC)->isInstance()) {
371 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2f841ba2009-12-02 03:53:29 +0000372
John McCallf7a1a742009-11-24 19:00:30 +0000373 // Since the 'this' expression is synthesized, we don't need to
374 // perform the double-lookup check.
375 NamedDecl *FirstQualifierInScope = 0;
376
John McCallaa81e162009-12-01 22:10:20 +0000377 return Owned(CXXDependentScopeMemberExpr::Create(Context,
378 /*This*/ 0, ThisType,
379 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000380 /*Op*/ SourceLocation(),
381 Qualifier, SS.getRange(),
382 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +0000383 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000384 TemplateArgs));
385 }
386
Abramo Bagnara25777432010-08-11 22:01:17 +0000387 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +0000388}
389
John McCall60d7b3a2010-08-24 06:29:42 +0000390ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000391Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000392 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000393 const TemplateArgumentListInfo *TemplateArgs) {
394 return Owned(DependentScopeDeclRefExpr::Create(Context,
395 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
396 SS.getRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +0000397 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000398 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000399}
400
Douglas Gregor72c3f312008-12-05 18:15:24 +0000401/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
402/// that the template parameter 'PrevDecl' is being shadowed by a new
403/// declaration at location Loc. Returns true to indicate that this is
404/// an error, and false otherwise.
405bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000406 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000407
408 // Microsoft Visual C++ permits template parameters to be shadowed.
409 if (getLangOptions().Microsoft)
410 return false;
411
412 // C++ [temp.local]p4:
413 // A template-parameter shall not be redeclared within its
414 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000415 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000416 << cast<NamedDecl>(PrevDecl)->getDeclName();
417 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
418 return true;
419}
420
Douglas Gregor2943aed2009-03-03 04:44:36 +0000421/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000422/// the parameter D to reference the templated declaration and return a pointer
423/// to the template declaration. Otherwise, do nothing to D and return null.
John McCalld226f652010-08-21 09:40:31 +0000424TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
425 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
426 D = Temp->getTemplatedDecl();
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000427 return Temp;
428 }
429 return 0;
430}
431
Douglas Gregor788cd062009-11-11 01:00:40 +0000432static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
433 const ParsedTemplateArgument &Arg) {
434
435 switch (Arg.getKind()) {
436 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000437 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000438 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
439 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000440 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000441 return TemplateArgumentLoc(TemplateArgument(T), DI);
442 }
443
444 case ParsedTemplateArgument::NonType: {
445 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
446 return TemplateArgumentLoc(TemplateArgument(E), E);
447 }
448
449 case ParsedTemplateArgument::Template: {
John McCall2b5289b2010-08-23 07:28:44 +0000450 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor788cd062009-11-11 01:00:40 +0000451 return TemplateArgumentLoc(TemplateArgument(Template),
452 Arg.getScopeSpec().getRange(),
453 Arg.getLocation());
454 }
455 }
456
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000457 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000458 return TemplateArgumentLoc();
459}
460
461/// \brief Translates template arguments as provided by the parser
462/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000463void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
464 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000465 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000466 TemplateArgs.addArgument(translateTemplateArgument(*this,
467 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000468}
469
Douglas Gregor72c3f312008-12-05 18:15:24 +0000470/// ActOnTypeParameter - Called when a C++ template type parameter
471/// (e.g., "typename T") has been parsed. Typename specifies whether
472/// the keyword "typename" was used to declare the type parameter
473/// (otherwise, "class" was used), and KeyLoc is the location of the
474/// "class" or "typename" keyword. ParamName is the name of the
475/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregorefed5c82010-06-16 15:23:05 +0000476/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000477/// If the type parameter has a default argument, it will be added
478/// later via ActOnTypeParameterDefault.
John McCalld226f652010-08-21 09:40:31 +0000479Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
480 SourceLocation EllipsisLoc,
481 SourceLocation KeyLoc,
482 IdentifierInfo *ParamName,
483 SourceLocation ParamNameLoc,
484 unsigned Depth, unsigned Position,
485 SourceLocation EqualLoc,
John McCallb3d87482010-08-24 05:47:05 +0000486 ParsedType DefaultArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000487 assert(S->isTemplateParamScope() &&
488 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000489 bool Invalid = false;
490
491 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000492 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000493 LookupOrdinaryName,
494 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000495 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000496 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000497 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000498 }
499
Douglas Gregorddc29e12009-02-06 22:42:48 +0000500 SourceLocation Loc = ParamNameLoc;
501 if (!ParamName)
502 Loc = KeyLoc;
503
Douglas Gregor72c3f312008-12-05 18:15:24 +0000504 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000505 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
506 Loc, Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000507 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000508 if (Invalid)
509 Param->setInvalidDecl();
510
511 if (ParamName) {
512 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000513 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000514 IdResolver.AddDecl(Param);
515 }
516
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000517 // Handle the default argument, if provided.
518 if (DefaultArg) {
519 TypeSourceInfo *DefaultTInfo;
520 GetTypeFromParser(DefaultArg, &DefaultTInfo);
521
522 assert(DefaultTInfo && "expected source information for type");
523
524 // C++0x [temp.param]p9:
525 // A default template-argument may be specified for any kind of
526 // template-parameter that is not a template parameter pack.
527 if (Ellipsis) {
528 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
John McCalld226f652010-08-21 09:40:31 +0000529 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000530 }
531
532 // Check the template argument itself.
533 if (CheckTemplateArgument(Param, DefaultTInfo)) {
534 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000535 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000536 }
537
538 Param->setDefaultArgument(DefaultTInfo, false);
539 }
540
John McCalld226f652010-08-21 09:40:31 +0000541 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000542}
543
Douglas Gregor2943aed2009-03-03 04:44:36 +0000544/// \brief Check that the type of a non-type template parameter is
545/// well-formed.
546///
547/// \returns the (possibly-promoted) parameter type if valid;
548/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000549QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000550Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora481ec42010-05-23 19:57:01 +0000551 // We don't allow variably-modified types as the type of non-type template
552 // parameters.
553 if (T->isVariablyModifiedType()) {
554 Diag(Loc, diag::err_variably_modified_nontype_template_param)
555 << T;
556 return QualType();
557 }
558
Douglas Gregor2943aed2009-03-03 04:44:36 +0000559 // C++ [temp.param]p4:
560 //
561 // A non-type template-parameter shall have one of the following
562 // (optionally cv-qualified) types:
563 //
564 // -- integral or enumeration type,
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000565 if (T->isIntegralOrEnumerationType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000566 // -- pointer to object or pointer to function,
Eli Friedman13578692010-08-05 02:49:48 +0000567 T->isPointerType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000568 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000569 T->isReferenceType() ||
570 // -- pointer to member.
571 T->isMemberPointerType() ||
572 // If T is a dependent type, we can't do the check now, so we
573 // assume that it is well-formed.
574 T->isDependentType())
575 return T;
576 // C++ [temp.param]p8:
577 //
578 // A non-type template-parameter of type "array of T" or
579 // "function returning T" is adjusted to be of type "pointer to
580 // T" or "pointer to function returning T", respectively.
581 else if (T->isArrayType())
582 // FIXME: Keep the type prior to promotion?
583 return Context.getArrayDecayedType(T);
584 else if (T->isFunctionType())
585 // FIXME: Keep the type prior to promotion?
586 return Context.getPointerType(T);
Douglas Gregor0fddb972010-05-22 16:17:30 +0000587
Douglas Gregor2943aed2009-03-03 04:44:36 +0000588 Diag(Loc, diag::err_template_nontype_parm_bad_type)
589 << T;
590
591 return QualType();
592}
593
John McCalld226f652010-08-21 09:40:31 +0000594Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
595 unsigned Depth,
596 unsigned Position,
597 SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000598 Expr *Default) {
John McCallbf1a0282010-06-04 23:28:52 +0000599 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
600 QualType T = TInfo->getType();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000601
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000602 assert(S->isTemplateParamScope() &&
603 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000604 bool Invalid = false;
605
606 IdentifierInfo *ParamName = D.getIdentifier();
607 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000608 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000609 LookupOrdinaryName,
610 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000611 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000612 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000613 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000614 }
615
Douglas Gregor2943aed2009-03-03 04:44:36 +0000616 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000617 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000618 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000619 Invalid = true;
620 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000621
Douglas Gregor72c3f312008-12-05 18:15:24 +0000622 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000623 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
624 D.getIdentifierLoc(),
John McCalla93c9342009-12-07 02:54:59 +0000625 Depth, Position, ParamName, T, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000626 if (Invalid)
627 Param->setInvalidDecl();
628
629 if (D.getIdentifier()) {
630 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000631 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000632 IdResolver.AddDecl(Param);
633 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000634
635 // Check the well-formedness of the default template argument, if provided.
John McCall9ae2f072010-08-23 23:25:46 +0000636 if (Default) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000637 TemplateArgument Converted;
638 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
639 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000640 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000641 }
642
John McCall9ae2f072010-08-23 23:25:46 +0000643 Param->setDefaultArgument(Default, false);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000644 }
645
John McCalld226f652010-08-21 09:40:31 +0000646 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000647}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000648
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000649/// ActOnTemplateTemplateParameter - Called when a C++ template template
650/// parameter (e.g. T in template <template <typename> class T> class array)
651/// has been parsed. S is the current scope.
John McCalld226f652010-08-21 09:40:31 +0000652Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
653 SourceLocation TmpLoc,
654 TemplateParamsTy *Params,
655 IdentifierInfo *Name,
656 SourceLocation NameLoc,
657 unsigned Depth,
658 unsigned Position,
659 SourceLocation EqualLoc,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000660 const ParsedTemplateArgument &Default) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000661 assert(S->isTemplateParamScope() &&
662 "Template template parameter not in template parameter scope!");
663
664 // Construct the parameter object.
665 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000666 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000667 NameLoc.isInvalid()? TmpLoc : NameLoc,
668 Depth, Position, Name,
Douglas Gregor369ea272010-10-21 17:26:49 +0000669 Params);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000670
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000671 // If the template template parameter has a name, then link the identifier
672 // into the scope and lookup mechanisms.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000673 if (Name) {
John McCalld226f652010-08-21 09:40:31 +0000674 S->AddDecl(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000675 IdResolver.AddDecl(Param);
676 }
677
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000678 if (!Default.isInvalid()) {
679 // Check only that we have a template template argument. We don't want to
680 // try to check well-formedness now, because our template template parameter
681 // might have dependent types in its template parameters, which we wouldn't
682 // be able to match now.
683 //
684 // If none of the template template parameter's template arguments mention
685 // other template parameters, we could actually perform more checking here.
686 // However, it isn't worth doing.
687 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
688 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
689 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
690 << DefaultArg.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +0000691 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000692 }
693
694 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000695 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000696
Douglas Gregor369ea272010-10-21 17:26:49 +0000697 if (Params->size() == 0) {
698 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
699 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
700 Param->setInvalidDecl();
701 }
John McCalld226f652010-08-21 09:40:31 +0000702 return Param;
Douglas Gregord684b002009-02-10 19:49:53 +0000703}
704
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000705/// ActOnTemplateParameterList - Builds a TemplateParameterList that
706/// contains the template parameters in Params/NumParams.
707Sema::TemplateParamsTy *
708Sema::ActOnTemplateParameterList(unsigned Depth,
709 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000710 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000711 SourceLocation LAngleLoc,
John McCalld226f652010-08-21 09:40:31 +0000712 Decl **Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000713 SourceLocation RAngleLoc) {
714 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000715 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000716
Douglas Gregorddc29e12009-02-06 22:42:48 +0000717 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000718 (NamedDecl**)Params, NumParams,
719 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000720}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000721
John McCallb6217662010-03-15 10:12:16 +0000722static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
723 if (SS.isSet())
724 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
725 SS.getRange());
726}
727
John McCallf312b1e2010-08-26 23:41:50 +0000728DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000729Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000730 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000731 IdentifierInfo *Name, SourceLocation NameLoc,
732 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000733 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000734 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000735 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000736 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000737 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000738 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000739
740 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000741 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000742 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000743
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000744 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
745 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000746
747 // There is no such thing as an unnamed class template.
748 if (!Name) {
749 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000750 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000751 }
752
753 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000754 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000755 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000756 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000757 if (SS.isNotEmpty() && !SS.isInvalid()) {
758 SemanticContext = computeDeclContext(SS, true);
759 if (!SemanticContext) {
760 // FIXME: Produce a reasonable diagnostic here
761 return true;
762 }
Mike Stump1eb44332009-09-09 15:08:12 +0000763
John McCall77bb1aa2010-05-01 00:40:08 +0000764 if (RequireCompleteDeclContext(SS, SemanticContext))
765 return true;
766
John McCalla24dc2e2009-11-17 02:14:36 +0000767 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000768 } else {
769 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000770 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000771 }
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Douglas Gregor57265e32010-04-12 16:00:01 +0000773 if (Previous.isAmbiguous())
774 return true;
775
Douglas Gregorddc29e12009-02-06 22:42:48 +0000776 NamedDecl *PrevDecl = 0;
777 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000778 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000779
Douglas Gregorddc29e12009-02-06 22:42:48 +0000780 // If there is a previous declaration with the same name, check
781 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000782 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000783 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000784
785 // We may have found the injected-class-name of a class template,
786 // class template partial specialization, or class template specialization.
787 // In these cases, grab the template that is being defined or specialized.
788 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
789 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
790 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
791 PrevClassTemplate
792 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
793 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
794 PrevClassTemplate
795 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
796 ->getSpecializedTemplate();
797 }
798 }
799
John McCall65c49462009-12-18 11:25:59 +0000800 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000801 // C++ [namespace.memdef]p3:
802 // [...] When looking for a prior declaration of a class or a function
803 // declared as a friend, and when the name of the friend class or
804 // function is neither a qualified name nor a template-id, scopes outside
805 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000806 if (!SS.isSet()) {
807 DeclContext *OutermostContext = CurContext;
808 while (!OutermostContext->isFileContext())
809 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000810
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000811 if (PrevDecl &&
812 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
813 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
814 SemanticContext = PrevDecl->getDeclContext();
815 } else {
816 // Declarations in outer scopes don't matter. However, the outermost
817 // context we computed is the semantic context for our new
818 // declaration.
819 PrevDecl = PrevClassTemplate = 0;
820 SemanticContext = OutermostContext;
821 }
John McCalle129d442009-12-17 23:21:11 +0000822 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000823
John McCalle129d442009-12-17 23:21:11 +0000824 if (CurContext->isDependentContext()) {
825 // If this is a dependent context, we don't want to link the friend
826 // class template to the template in scope, because that would perform
827 // checking of the template parameter lists that can't be performed
828 // until the outer context is instantiated.
829 PrevDecl = PrevClassTemplate = 0;
830 }
831 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
832 PrevDecl = PrevClassTemplate = 0;
Douglas Gregor57265e32010-04-12 16:00:01 +0000833
Douglas Gregorddc29e12009-02-06 22:42:48 +0000834 if (PrevClassTemplate) {
835 // Ensure that the template parameter lists are compatible.
836 if (!TemplateParameterListsAreEqual(TemplateParams,
837 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000838 /*Complain=*/true,
839 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000840 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000841
842 // C++ [temp.class]p4:
843 // In a redeclaration, partial specialization, explicit
844 // specialization or explicit instantiation of a class template,
845 // the class-key shall agree in kind with the original class
846 // template declaration (7.1.5.3).
847 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000848 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000849 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000850 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000851 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000852 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000853 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000854 }
855
Douglas Gregorddc29e12009-02-06 22:42:48 +0000856 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000857 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000858 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000859 Diag(NameLoc, diag::err_redefinition) << Name;
860 Diag(Def->getLocation(), diag::note_previous_definition);
861 // FIXME: Would it make sense to try to "forget" the previous
862 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000863 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000864 }
865 }
866 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
867 // Maybe we will complain about the shadowed template parameter.
868 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
869 // Just pretend that we didn't see the previous declaration.
870 PrevDecl = 0;
871 } else if (PrevDecl) {
872 // C++ [temp]p5:
873 // A class template shall not have the same name as any other
874 // template, class, function, object, enumeration, enumerator,
875 // namespace, or type in the same scope (3.3), except as specified
876 // in (14.5.4).
877 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
878 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000879 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000880 }
881
Douglas Gregord684b002009-02-10 19:49:53 +0000882 // Check the template parameter list of this declaration, possibly
883 // merging in the template parameter list from the previous class
884 // template declaration.
885 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000886 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
887 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000888 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Douglas Gregor57265e32010-04-12 16:00:01 +0000890 if (SS.isSet()) {
891 // If the name of the template was qualified, we must be defining the
892 // template out-of-line.
893 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
894 !(TUK == TUK_Friend && CurContext->isDependentContext()))
895 Diag(NameLoc, diag::err_member_def_does_not_match)
896 << Name << SemanticContext << SS.getRange();
897 }
898
Mike Stump1eb44332009-09-09 15:08:12 +0000899 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000900 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000901 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000902 PrevClassTemplate->getTemplatedDecl() : 0,
903 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000904 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000905
906 ClassTemplateDecl *NewTemplate
907 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
908 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000909 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000910 NewClass->setDescribedClassTemplate(NewTemplate);
911
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000912 // Build the type for the class template declaration now.
Douglas Gregor24bae922010-07-08 18:37:38 +0000913 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCall3cb0ebd2010-03-10 03:28:59 +0000914 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000915 assert(T->isDependentType() && "Class template type is not dependent?");
916 (void)T;
917
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000918 // If we are providing an explicit specialization of a member that is a
919 // class template, make a note of that.
920 if (PrevClassTemplate &&
921 PrevClassTemplate->getInstantiatedFromMemberTemplate())
922 PrevClassTemplate->setMemberSpecialization();
923
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000924 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000925 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000926 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Douglas Gregorddc29e12009-02-06 22:42:48 +0000928 // Set the lexical context of these templates
929 NewClass->setLexicalDeclContext(CurContext);
930 NewTemplate->setLexicalDeclContext(CurContext);
931
John McCall0f434ec2009-07-31 02:45:11 +0000932 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000933 NewClass->startDefinition();
934
935 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000936 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000937
John McCall05b23ea2009-09-14 21:59:20 +0000938 if (TUK != TUK_Friend)
939 PushOnScopeChains(NewTemplate, S);
940 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000941 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000942 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000943 NewClass->setAccess(PrevClassTemplate->getAccess());
944 }
John McCall05b23ea2009-09-14 21:59:20 +0000945
Douglas Gregord85bea22009-09-26 06:47:28 +0000946 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
947 PrevClassTemplate != NULL);
948
John McCall05b23ea2009-09-14 21:59:20 +0000949 // Friend templates are visible in fairly strange ways.
950 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +0000951 DeclContext *DC = SemanticContext->getRedeclContext();
John McCall05b23ea2009-09-14 21:59:20 +0000952 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
953 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
954 PushOnScopeChains(NewTemplate, EnclosingScope,
955 /* AddToContext = */ false);
956 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000957
958 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
959 NewClass->getLocation(),
960 NewTemplate,
961 /*FIXME:*/NewClass->getLocation());
962 Friend->setAccess(AS_public);
963 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000964 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000965
Douglas Gregord684b002009-02-10 19:49:53 +0000966 if (Invalid) {
967 NewTemplate->setInvalidDecl();
968 NewClass->setInvalidDecl();
969 }
John McCalld226f652010-08-21 09:40:31 +0000970 return NewTemplate;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000971}
972
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000973/// \brief Diagnose the presence of a default template argument on a
974/// template parameter, which is ill-formed in certain contexts.
975///
976/// \returns true if the default template argument should be dropped.
977static bool DiagnoseDefaultTemplateArgument(Sema &S,
978 Sema::TemplateParamListContext TPC,
979 SourceLocation ParamLoc,
980 SourceRange DefArgRange) {
981 switch (TPC) {
982 case Sema::TPC_ClassTemplate:
983 return false;
984
985 case Sema::TPC_FunctionTemplate:
986 // C++ [temp.param]p9:
987 // A default template-argument shall not be specified in a
988 // function template declaration or a function template
989 // definition [...]
990 // (This sentence is not in C++0x, per DR226).
991 if (!S.getLangOptions().CPlusPlus0x)
992 S.Diag(ParamLoc,
993 diag::err_template_parameter_default_in_function_template)
994 << DefArgRange;
995 return false;
996
997 case Sema::TPC_ClassTemplateMember:
998 // C++0x [temp.param]p9:
999 // A default template-argument shall not be specified in the
1000 // template-parameter-lists of the definition of a member of a
1001 // class template that appears outside of the member's class.
1002 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1003 << DefArgRange;
1004 return true;
1005
1006 case Sema::TPC_FriendFunctionTemplate:
1007 // C++ [temp.param]p9:
1008 // A default template-argument shall not be specified in a
1009 // friend template declaration.
1010 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1011 << DefArgRange;
1012 return true;
1013
1014 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1015 // for friend function templates if there is only a single
1016 // declaration (and it is a definition). Strange!
1017 }
1018
1019 return false;
1020}
1021
Douglas Gregord684b002009-02-10 19:49:53 +00001022/// \brief Checks the validity of a template parameter list, possibly
1023/// considering the template parameter list from a previous
1024/// declaration.
1025///
1026/// If an "old" template parameter list is provided, it must be
1027/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1028/// template parameter list.
1029///
1030/// \param NewParams Template parameter list for a new template
1031/// declaration. This template parameter list will be updated with any
1032/// default arguments that are carried through from the previous
1033/// template parameter list.
1034///
1035/// \param OldParams If provided, template parameter list from a
1036/// previous declaration of the same template. Default template
1037/// arguments will be merged from the old template parameter list to
1038/// the new template parameter list.
1039///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001040/// \param TPC Describes the context in which we are checking the given
1041/// template parameter list.
1042///
Douglas Gregord684b002009-02-10 19:49:53 +00001043/// \returns true if an error occurred, false otherwise.
1044bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001045 TemplateParameterList *OldParams,
1046 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001047 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Douglas Gregord684b002009-02-10 19:49:53 +00001049 // C++ [temp.param]p10:
1050 // The set of default template-arguments available for use with a
1051 // template declaration or definition is obtained by merging the
1052 // default arguments from the definition (if in scope) and all
1053 // declarations in scope in the same way default function
1054 // arguments are (8.3.6).
1055 bool SawDefaultArgument = false;
1056 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001057
Anders Carlsson49d25572009-06-12 23:20:15 +00001058 bool SawParameterPack = false;
1059 SourceLocation ParameterPackLoc;
1060
Mike Stump1a35fde2009-02-11 23:03:27 +00001061 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001062 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001063 if (OldParams)
1064 OldParam = OldParams->begin();
1065
1066 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1067 NewParamEnd = NewParams->end();
1068 NewParam != NewParamEnd; ++NewParam) {
1069 // Variables used to diagnose redundant default arguments
1070 bool RedundantDefaultArg = false;
1071 SourceLocation OldDefaultLoc;
1072 SourceLocation NewDefaultLoc;
1073
1074 // Variables used to diagnose missing default arguments
1075 bool MissingDefaultArg = false;
1076
Anders Carlsson49d25572009-06-12 23:20:15 +00001077 // C++0x [temp.param]p11:
1078 // If a template parameter of a class template is a template parameter pack,
1079 // it must be the last template parameter.
1080 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001081 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001082 diag::err_template_param_pack_must_be_last_template_parameter);
1083 Invalid = true;
1084 }
1085
Douglas Gregord684b002009-02-10 19:49:53 +00001086 if (TemplateTypeParmDecl *NewTypeParm
1087 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001088 // Check the presence of a default argument here.
1089 if (NewTypeParm->hasDefaultArgument() &&
1090 DiagnoseDefaultTemplateArgument(*this, TPC,
1091 NewTypeParm->getLocation(),
1092 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001093 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001094 NewTypeParm->removeDefaultArgument();
1095
1096 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001097 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001098 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Anders Carlsson49d25572009-06-12 23:20:15 +00001100 if (NewTypeParm->isParameterPack()) {
1101 assert(!NewTypeParm->hasDefaultArgument() &&
1102 "Parameter packs can't have a default argument!");
1103 SawParameterPack = true;
1104 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001105 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001106 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001107 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1108 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1109 SawDefaultArgument = true;
1110 RedundantDefaultArg = true;
1111 PreviousDefaultArgLoc = NewDefaultLoc;
1112 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1113 // Merge the default argument from the old declaration to the
1114 // new declaration.
1115 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001116 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001117 true);
1118 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1119 } else if (NewTypeParm->hasDefaultArgument()) {
1120 SawDefaultArgument = true;
1121 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1122 } else if (SawDefaultArgument)
1123 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001124 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001125 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001126 // Check the presence of a default argument here.
1127 if (NewNonTypeParm->hasDefaultArgument() &&
1128 DiagnoseDefaultTemplateArgument(*this, TPC,
1129 NewNonTypeParm->getLocation(),
1130 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001131 NewNonTypeParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001132 }
1133
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001134 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001135 NonTypeTemplateParmDecl *OldNonTypeParm
1136 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001137 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001138 NewNonTypeParm->hasDefaultArgument()) {
1139 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1140 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1141 SawDefaultArgument = true;
1142 RedundantDefaultArg = true;
1143 PreviousDefaultArgLoc = NewDefaultLoc;
1144 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1145 // Merge the default argument from the old declaration to the
1146 // new declaration.
1147 SawDefaultArgument = true;
1148 // FIXME: We need to create a new kind of "default argument"
1149 // expression that points to a previous template template
1150 // parameter.
1151 NewNonTypeParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001152 OldNonTypeParm->getDefaultArgument(),
1153 /*Inherited=*/ true);
Douglas Gregord684b002009-02-10 19:49:53 +00001154 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1155 } else if (NewNonTypeParm->hasDefaultArgument()) {
1156 SawDefaultArgument = true;
1157 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1158 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001159 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001160 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001161 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001162 TemplateTemplateParmDecl *NewTemplateParm
1163 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001164 if (NewTemplateParm->hasDefaultArgument() &&
1165 DiagnoseDefaultTemplateArgument(*this, TPC,
1166 NewTemplateParm->getLocation(),
1167 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001168 NewTemplateParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001169
1170 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001171 TemplateTemplateParmDecl *OldTemplateParm
1172 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001173 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001174 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001175 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1176 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001177 SawDefaultArgument = true;
1178 RedundantDefaultArg = true;
1179 PreviousDefaultArgLoc = NewDefaultLoc;
1180 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1181 // Merge the default argument from the old declaration to the
1182 // new declaration.
1183 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001184 // FIXME: We need to create a new kind of "default argument" expression
1185 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001186 NewTemplateParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001187 OldTemplateParm->getDefaultArgument(),
1188 /*Inherited=*/ true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001189 PreviousDefaultArgLoc
1190 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001191 } else if (NewTemplateParm->hasDefaultArgument()) {
1192 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001193 PreviousDefaultArgLoc
1194 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001195 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001196 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001197 }
1198
1199 if (RedundantDefaultArg) {
1200 // C++ [temp.param]p12:
1201 // A template-parameter shall not be given default arguments
1202 // by two different declarations in the same scope.
1203 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1204 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1205 Invalid = true;
1206 } else if (MissingDefaultArg) {
1207 // C++ [temp.param]p11:
1208 // If a template-parameter has a default template-argument,
1209 // all subsequent template-parameters shall have a default
1210 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001211 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001212 diag::err_template_param_default_arg_missing);
1213 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1214 Invalid = true;
1215 }
1216
1217 // If we have an old template parameter list that we're merging
1218 // in, move on to the next parameter.
1219 if (OldParams)
1220 ++OldParam;
1221 }
1222
1223 return Invalid;
1224}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001225
John McCall4e2cbb22010-10-20 05:44:58 +00001226namespace {
1227
1228/// A class which looks for a use of a certain level of template
1229/// parameter.
1230struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1231 typedef RecursiveASTVisitor<DependencyChecker> super;
1232
1233 unsigned Depth;
1234 bool Match;
1235
1236 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1237 NamedDecl *ND = Params->getParam(0);
1238 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1239 Depth = PD->getDepth();
1240 } else if (NonTypeTemplateParmDecl *PD =
1241 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1242 Depth = PD->getDepth();
1243 } else {
1244 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1245 }
1246 }
1247
1248 bool Matches(unsigned ParmDepth) {
1249 if (ParmDepth >= Depth) {
1250 Match = true;
1251 return true;
1252 }
1253 return false;
1254 }
1255
1256 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1257 return !Matches(T->getDepth());
1258 }
1259
1260 bool TraverseTemplateName(TemplateName N) {
1261 if (TemplateTemplateParmDecl *PD =
1262 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1263 if (Matches(PD->getDepth())) return false;
1264 return super::TraverseTemplateName(N);
1265 }
1266
1267 bool VisitDeclRefExpr(DeclRefExpr *E) {
1268 if (NonTypeTemplateParmDecl *PD =
1269 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1270 if (PD->getDepth() == Depth) {
1271 Match = true;
1272 return false;
1273 }
1274 }
1275 return super::VisitDeclRefExpr(E);
1276 }
1277};
1278}
1279
1280/// Determines whether a template-id depends on the given parameter
1281/// list.
1282static bool
1283DependsOnTemplateParameters(const TemplateSpecializationType *TemplateId,
1284 TemplateParameterList *Params) {
1285 DependencyChecker Checker(Params);
1286 Checker.TraverseType(QualType(TemplateId, 0));
1287 return Checker.Match;
1288}
1289
Mike Stump1eb44332009-09-09 15:08:12 +00001290/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001291/// specifier, returning the template parameter list that applies to the
1292/// name.
1293///
1294/// \param DeclStartLoc the start of the declaration that has a scope
1295/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001296///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001297/// \param SS the scope specifier that will be matched to the given template
1298/// parameter lists. This scope specifier precedes a qualified name that is
1299/// being declared.
1300///
1301/// \param ParamLists the template parameter lists, from the outermost to the
1302/// innermost template parameter lists.
1303///
1304/// \param NumParamLists the number of template parameter lists in ParamLists.
1305///
John McCall77e8b112010-04-13 20:37:33 +00001306/// \param IsFriend Whether to apply the slightly different rules for
1307/// matching template parameters to scope specifiers in friend
1308/// declarations.
1309///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001310/// \param IsExplicitSpecialization will be set true if the entity being
1311/// declared is an explicit specialization, false otherwise.
1312///
Mike Stump1eb44332009-09-09 15:08:12 +00001313/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001314/// name that is preceded by the scope specifier @p SS. This template
1315/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001316/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001317/// template specialization), or may be NULL (if we were's declaring isn't
1318/// itself a template).
1319TemplateParameterList *
1320Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1321 const CXXScopeSpec &SS,
1322 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001323 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001324 bool IsFriend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001325 bool &IsExplicitSpecialization,
1326 bool &Invalid) {
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001327 IsExplicitSpecialization = false;
1328
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001329 // Find the template-ids that occur within the nested-name-specifier. These
1330 // template-ids will match up with the template parameter lists.
1331 llvm::SmallVector<const TemplateSpecializationType *, 4>
1332 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001333 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1334 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001335 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1336 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001337 const Type *T = NNS->getAsType();
1338 if (!T) break;
1339
1340 // C++0x [temp.expl.spec]p17:
1341 // A member or a member template may be nested within many
1342 // enclosing class templates. In an explicit specialization for
1343 // such a member, the member declaration shall be preceded by a
1344 // template<> for each enclosing class template that is
1345 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001346 //
1347 // Following the existing practice of GNU and EDG, we allow a typedef of a
1348 // template specialization type.
1349 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1350 T = TT->LookThroughTypedefs().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001351
Mike Stump1eb44332009-09-09 15:08:12 +00001352 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001353 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001354 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1355 if (!Template)
1356 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Ted Kremenek6217b802009-07-29 21:53:49 +00001358 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001359 ClassTemplateSpecializationDecl *SpecDecl
1360 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1361 // If the nested name specifier refers to an explicit specialization,
1362 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001363 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1364 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001365 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001366 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001367 }
Mike Stump1eb44332009-09-09 15:08:12 +00001368
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001369 TemplateIdsInSpecifier.push_back(SpecType);
1370 }
1371 }
Mike Stump1eb44332009-09-09 15:08:12 +00001372
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001373 // Reverse the list of template-ids in the scope specifier, so that we can
1374 // more easily match up the template-ids and the template parameter lists.
1375 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001377 SourceLocation FirstTemplateLoc = DeclStartLoc;
1378 if (NumParamLists)
1379 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001381 // Match the template-ids found in the specifier to the template parameter
1382 // lists.
John McCall4e2cbb22010-10-20 05:44:58 +00001383 unsigned ParamIdx = 0, TemplateIdx = 0;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001384 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
John McCall4e2cbb22010-10-20 05:44:58 +00001385 TemplateIdx != NumTemplateIds; ++TemplateIdx) {
1386 const TemplateSpecializationType *TemplateId
1387 = TemplateIdsInSpecifier[TemplateIdx];
Douglas Gregorb88e8882009-07-30 17:40:51 +00001388 bool DependentTemplateId = TemplateId->isDependentType();
John McCall4e2cbb22010-10-20 05:44:58 +00001389
1390 // In friend declarations we can have template-ids which don't
1391 // depend on the corresponding template parameter lists. But
1392 // assume that empty parameter lists are supposed to match this
1393 // template-id.
1394 if (IsFriend && ParamIdx < NumParamLists && ParamLists[ParamIdx]->size()) {
1395 if (!DependentTemplateId ||
1396 !DependsOnTemplateParameters(TemplateId, ParamLists[ParamIdx]))
1397 continue;
1398 }
1399
1400 if (ParamIdx >= NumParamLists) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001401 // We have a template-id without a corresponding template parameter
1402 // list.
John McCall77e8b112010-04-13 20:37:33 +00001403
1404 // ...which is fine if this is a friend declaration.
1405 if (IsFriend) {
1406 IsExplicitSpecialization = true;
1407 break;
1408 }
1409
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001410 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001411 // FIXME: the location information here isn't great.
1412 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001413 diag::err_template_spec_needs_template_parameters)
John McCall4e2cbb22010-10-20 05:44:58 +00001414 << QualType(TemplateId, 0)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001415 << SS.getRange();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001416 Invalid = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001417 } else {
1418 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1419 << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00001420 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001421 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001422 }
1423 return 0;
1424 }
Mike Stump1eb44332009-09-09 15:08:12 +00001425
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001426 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001427 if (DependentTemplateId) {
John McCall31f17ec2010-04-27 00:57:59 +00001428 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00001429
John McCall31f17ec2010-04-27 00:57:59 +00001430 // Are there cases in (e.g.) friends where this won't match?
1431 if (const InjectedClassNameType *Injected
1432 = TemplateId->getAs<InjectedClassNameType>()) {
1433 CXXRecordDecl *Record = Injected->getDecl();
1434 if (ClassTemplatePartialSpecializationDecl *Partial =
1435 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1436 ExpectedTemplateParams = Partial->getTemplateParameters();
1437 else
1438 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1439 ->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001440 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001441
John McCall31f17ec2010-04-27 00:57:59 +00001442 if (ExpectedTemplateParams)
John McCall4e2cbb22010-10-20 05:44:58 +00001443 TemplateParameterListsAreEqual(ParamLists[ParamIdx],
John McCall31f17ec2010-04-27 00:57:59 +00001444 ExpectedTemplateParams,
1445 true, TPL_TemplateMatch);
1446
John McCall4e2cbb22010-10-20 05:44:58 +00001447 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1448 TPC_ClassTemplateMember);
1449 } else if (ParamLists[ParamIdx]->size() > 0)
1450 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001451 diag::err_template_param_list_matches_nontemplate)
1452 << TemplateId
John McCall4e2cbb22010-10-20 05:44:58 +00001453 << ParamLists[ParamIdx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001454 else
1455 IsExplicitSpecialization = true;
John McCall4e2cbb22010-10-20 05:44:58 +00001456
1457 ++ParamIdx;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001458 }
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001460 // If there were at least as many template-ids as there were template
1461 // parameter lists, then there are no template parameter lists remaining for
1462 // the declaration itself.
John McCall4e2cbb22010-10-20 05:44:58 +00001463 if (ParamIdx >= NumParamLists)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001464 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001466 // If there were too many template parameter lists, complain about that now.
John McCall4e2cbb22010-10-20 05:44:58 +00001467 if (ParamIdx != NumParamLists - 1) {
1468 while (ParamIdx < NumParamLists - 1) {
1469 bool isExplicitSpecHeader = ParamLists[ParamIdx]->size() == 0;
1470 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001471 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1472 : diag::err_template_spec_extra_headers)
John McCall4e2cbb22010-10-20 05:44:58 +00001473 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1474 ParamLists[ParamIdx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001475
1476 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1477 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1478 diag::note_explicit_template_spec_does_not_need_header)
1479 << ExplicitSpecializationsInSpecifier.back();
1480 ExplicitSpecializationsInSpecifier.pop_back();
1481 }
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001482
1483 // We have a template parameter list with no corresponding scope, which
1484 // means that the resulting template declaration can't be instantiated
1485 // properly (we'll end up with dependent nodes when we shouldn't).
1486 if (!isExplicitSpecHeader)
1487 Invalid = true;
1488
John McCall4e2cbb22010-10-20 05:44:58 +00001489 ++ParamIdx;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001490 }
1491 }
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001493 // Return the last template parameter list, which corresponds to the
1494 // entity being declared.
1495 return ParamLists[NumParamLists - 1];
1496}
1497
Douglas Gregor7532dc62009-03-30 22:58:21 +00001498QualType Sema::CheckTemplateIdType(TemplateName Name,
1499 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001500 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001501 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001502 if (!Template) {
1503 // The template name does not resolve to a template, so we just
1504 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001505 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001506 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001507
Douglas Gregor40808ce2009-03-09 23:48:35 +00001508 // Check that the template argument list is well-formed for this
1509 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001510 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCalld5532b62009-11-23 01:53:49 +00001511 TemplateArgs.size());
1512 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001513 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001514 return QualType();
1515
Mike Stump1eb44332009-09-09 15:08:12 +00001516 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001517 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001518 "Converted template argument list is too short!");
1519
1520 QualType CanonType;
1521
Douglas Gregorcaddba02009-11-12 18:38:13 +00001522 if (Name.isDependent() ||
1523 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001524 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001525 // This class template specialization is a dependent
1526 // type. Therefore, its canonical type is another class template
1527 // specialization type that contains all of the converted
1528 // arguments in canonical form. This ensures that, e.g., A<T> and
1529 // A<T, T> have identical types when A is declared as:
1530 //
1531 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001532 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001533 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001534 Converted.getFlatArguments(),
1535 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Douglas Gregor1275ae02009-07-28 23:00:59 +00001537 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001538 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001539 // In the future, we need to teach getTemplateSpecializationType to only
1540 // build the canonical type and return that to us.
1541 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001542
1543 // This might work out to be a current instantiation, in which
1544 // case the canonical type needs to be the InjectedClassNameType.
1545 //
1546 // TODO: in theory this could be a simple hashtable lookup; most
1547 // changes to CurContext don't change the set of current
1548 // instantiations.
1549 if (isa<ClassTemplateDecl>(Template)) {
1550 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1551 // If we get out to a namespace, we're done.
1552 if (Ctx->isFileContext()) break;
1553
1554 // If this isn't a record, keep looking.
1555 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1556 if (!Record) continue;
1557
1558 // Look for one of the two cases with InjectedClassNameTypes
1559 // and check whether it's the same template.
1560 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1561 !Record->getDescribedClassTemplate())
1562 continue;
1563
1564 // Fetch the injected class name type and check whether its
1565 // injected type is equal to the type we just built.
1566 QualType ICNT = Context.getTypeDeclType(Record);
1567 QualType Injected = cast<InjectedClassNameType>(ICNT)
1568 ->getInjectedSpecializationType();
1569
1570 if (CanonType != Injected->getCanonicalTypeInternal())
1571 continue;
1572
1573 // If so, the canonical type of this TST is the injected
1574 // class name type of the record we just found.
1575 assert(ICNT.isCanonical());
1576 CanonType = ICNT;
John McCall31f17ec2010-04-27 00:57:59 +00001577 break;
1578 }
1579 }
Mike Stump1eb44332009-09-09 15:08:12 +00001580 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001581 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001582 // Find the class template specialization declaration that
1583 // corresponds to these arguments.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001584 void *InsertPos = 0;
1585 ClassTemplateSpecializationDecl *Decl
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001586 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
1587 Converted.flatSize(), InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001588 if (!Decl) {
1589 // This is the first time we have referenced this class template
1590 // specialization. Create the canonical declaration and add it to
1591 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001592 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00001593 ClassTemplate->getTemplatedDecl()->getTagKind(),
1594 ClassTemplate->getDeclContext(),
1595 ClassTemplate->getLocation(),
1596 ClassTemplate,
1597 Converted, 0);
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001598 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001599 Decl->setLexicalDeclContext(CurContext);
1600 }
1601
1602 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001603 assert(isa<RecordType>(CanonType) &&
1604 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001605 }
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Douglas Gregor40808ce2009-03-09 23:48:35 +00001607 // Build the fully-sugared type for this class template
1608 // specialization, which refers back to the class template
1609 // specialization we created or found.
John McCall71d74bc2010-06-13 09:25:03 +00001610 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001611}
1612
John McCallf312b1e2010-08-26 23:41:50 +00001613TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001614Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001615 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001616 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001617 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001618 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001619
Douglas Gregor40808ce2009-03-09 23:48:35 +00001620 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001621 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001622 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001623
John McCalld5532b62009-11-23 01:53:49 +00001624 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001625 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001626
1627 if (Result.isNull())
1628 return true;
1629
John McCalla93c9342009-12-07 02:54:59 +00001630 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001631 TemplateSpecializationTypeLoc TL
1632 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1633 TL.setTemplateNameLoc(TemplateLoc);
1634 TL.setLAngleLoc(LAngleLoc);
1635 TL.setRAngleLoc(RAngleLoc);
1636 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1637 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1638
John McCallb3d87482010-08-24 05:47:05 +00001639 return CreateParsedType(Result, DI);
John McCall6b2becf2009-09-08 17:47:29 +00001640}
John McCallf1bbbb42009-09-04 01:14:41 +00001641
John McCallf312b1e2010-08-26 23:41:50 +00001642TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1643 TagUseKind TUK,
1644 TypeSpecifierType TagSpec,
1645 SourceLocation TagLoc) {
John McCall6b2becf2009-09-08 17:47:29 +00001646 if (TypeResult.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001647 return ::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001648
John McCall833ca992009-10-29 08:12:44 +00001649 // FIXME: preserve source info, ideally without copying the DI.
John McCalla93c9342009-12-07 02:54:59 +00001650 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001651 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001652
John McCall6b2becf2009-09-08 17:47:29 +00001653 // Verify the tag specifier.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001654 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001655
John McCall6b2becf2009-09-08 17:47:29 +00001656 if (const RecordType *RT = Type->getAs<RecordType>()) {
1657 RecordDecl *D = RT->getDecl();
1658
1659 IdentifierInfo *Id = D->getIdentifier();
1660 assert(Id && "templated class must have an identifier");
1661
1662 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1663 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001664 << Type
Douglas Gregor849b2432010-03-31 17:46:05 +00001665 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001666 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001667 }
1668 }
1669
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001670 ElaboratedTypeKeyword Keyword
1671 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1672 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCall6b2becf2009-09-08 17:47:29 +00001673
John McCallb3d87482010-08-24 05:47:05 +00001674 return ParsedType::make(ElabType);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001675}
1676
John McCall60d7b3a2010-08-24 06:29:42 +00001677ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001678 LookupResult &R,
1679 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001680 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001681 // FIXME: Can we do any checking at this point? I guess we could check the
1682 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001683 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001684 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001685
1686 // These should be filtered out by our callers.
1687 assert(!R.empty() && "empty lookup results when building templateid");
1688 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1689
1690 NestedNameSpecifier *Qualifier = 0;
1691 SourceRange QualifierRange;
1692 if (SS.isSet()) {
1693 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1694 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001695 }
John McCallc373d482010-01-27 01:50:18 +00001696
1697 // We don't want lookup warnings at this point.
1698 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001699
John McCallf7a1a742009-11-24 19:00:30 +00001700 bool Dependent
1701 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1702 &TemplateArgs);
1703 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001704 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001705 Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00001706 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00001707 RequiresADL, TemplateArgs,
1708 R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001709
1710 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001711}
1712
John McCallf7a1a742009-11-24 19:00:30 +00001713// We actually only call this from template instantiation.
John McCall60d7b3a2010-08-24 06:29:42 +00001714ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001715Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001716 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +00001717 const TemplateArgumentListInfo &TemplateArgs) {
1718 DeclContext *DC;
1719 if (!(DC = computeDeclContext(SS, false)) ||
1720 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00001721 RequireCompleteDeclContext(SS, DC))
Abramo Bagnara25777432010-08-11 22:01:17 +00001722 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001724 bool MemberOfUnknownSpecialization;
Abramo Bagnara25777432010-08-11 22:01:17 +00001725 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001726 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1727 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00001728
John McCallf7a1a742009-11-24 19:00:30 +00001729 if (R.isAmbiguous())
1730 return ExprError();
1731
1732 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001733 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1734 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001735 return ExprError();
1736 }
1737
1738 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001739 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1740 << (NestedNameSpecifier*) SS.getScopeRep()
1741 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001742 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1743 return ExprError();
1744 }
1745
1746 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001747}
1748
Douglas Gregorc45c2322009-03-31 00:43:58 +00001749/// \brief Form a dependent template name.
1750///
1751/// This action forms a dependent template name given the template
1752/// name and its (presumably dependent) scope specifier. For
1753/// example, given "MetaFun::template apply", the scope specifier \p
1754/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1755/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001756TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1757 SourceLocation TemplateKWLoc,
1758 CXXScopeSpec &SS,
1759 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +00001760 ParsedType ObjectType,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001761 bool EnteringContext,
1762 TemplateTy &Result) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00001763 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1764 !getLangOptions().CPlusPlus0x)
1765 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1766 << FixItHint::CreateRemoval(TemplateKWLoc);
1767
Douglas Gregor0707bc52010-01-19 16:01:07 +00001768 DeclContext *LookupCtx = 0;
1769 if (SS.isSet())
1770 LookupCtx = computeDeclContext(SS, EnteringContext);
1771 if (!LookupCtx && ObjectType)
John McCallb3d87482010-08-24 05:47:05 +00001772 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor0707bc52010-01-19 16:01:07 +00001773 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001774 // C++0x [temp.names]p5:
1775 // If a name prefixed by the keyword template is not the name of
1776 // a template, the program is ill-formed. [Note: the keyword
1777 // template may not be applied to non-template members of class
1778 // templates. -end note ] [ Note: as is the case with the
1779 // typename prefix, the template prefix is allowed in cases
1780 // where it is not strictly necessary; i.e., when the
1781 // nested-name-specifier or the expression on the left of the ->
1782 // or . is not dependent on a template-parameter, or the use
1783 // does not appear in the scope of a template. -end note]
1784 //
1785 // Note: C++03 was more strict here, because it banned the use of
1786 // the "template" keyword prior to a template-name that was not a
1787 // dependent name. C++ DR468 relaxed this requirement (the
1788 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregor732281d2010-06-14 22:07:54 +00001789 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001790 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001791 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1792 ObjectType, EnteringContext, Result,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001793 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001794 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1795 isa<CXXRecordDecl>(LookupCtx) &&
1796 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord6ab2322010-06-16 23:00:59 +00001797 // This is a dependent template. Handle it below.
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001798 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001799 Diag(Name.getSourceRange().getBegin(),
1800 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001801 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001802 << Name.getSourceRange()
1803 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001804 return TNK_Non_template;
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001805 } else {
1806 // We found something; return it.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001807 return TNK;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001808 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001809 }
1810
Mike Stump1eb44332009-09-09 15:08:12 +00001811 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001812 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001813
1814 switch (Name.getKind()) {
1815 case UnqualifiedId::IK_Identifier:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001816 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1817 Name.Identifier));
1818 return TNK_Dependent_template_name;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001819
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001820 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001821 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001822 Name.OperatorFunctionId.Operator));
Douglas Gregord6ab2322010-06-16 23:00:59 +00001823 return TNK_Dependent_template_name;
Sean Hunte6252d12009-11-28 08:58:14 +00001824
1825 case UnqualifiedId::IK_LiteralOperatorId:
1826 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1827
Douglas Gregor014e88d2009-11-03 23:16:33 +00001828 default:
1829 break;
1830 }
1831
1832 Diag(Name.getSourceRange().getBegin(),
1833 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001834 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001835 << Name.getSourceRange()
1836 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001837 return TNK_Non_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001838}
1839
Mike Stump1eb44332009-09-09 15:08:12 +00001840bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001841 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001842 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001843 const TemplateArgument &Arg = AL.getArgument();
1844
Anders Carlsson436b1562009-06-13 00:33:33 +00001845 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001846 switch(Arg.getKind()) {
1847 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00001848 // C++ [temp.arg.type]p1:
1849 // A template-argument for a template-parameter which is a
1850 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001851 break;
1852 case TemplateArgument::Template: {
1853 // We have a template type parameter but the template argument
1854 // is a template without any arguments.
1855 SourceRange SR = AL.getSourceRange();
1856 TemplateName Name = Arg.getAsTemplate();
1857 Diag(SR.getBegin(), diag::err_template_missing_args)
1858 << Name << SR;
1859 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1860 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00001861
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001862 return true;
1863 }
1864 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00001865 // We have a template type parameter but the template argument
1866 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001867 SourceRange SR = AL.getSourceRange();
1868 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001869 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Anders Carlsson436b1562009-06-13 00:33:33 +00001871 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001872 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001873 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001874
John McCalla93c9342009-12-07 02:54:59 +00001875 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001876 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001877
Anders Carlsson436b1562009-06-13 00:33:33 +00001878 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001879 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001880 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001881 return false;
1882}
1883
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001884/// \brief Substitute template arguments into the default template argument for
1885/// the given template type parameter.
1886///
1887/// \param SemaRef the semantic analysis object for which we are performing
1888/// the substitution.
1889///
1890/// \param Template the template that we are synthesizing template arguments
1891/// for.
1892///
1893/// \param TemplateLoc the location of the template name that started the
1894/// template-id we are checking.
1895///
1896/// \param RAngleLoc the location of the right angle bracket ('>') that
1897/// terminates the template-id.
1898///
1899/// \param Param the template template parameter whose default we are
1900/// substituting into.
1901///
1902/// \param Converted the list of template arguments provided for template
1903/// parameters that precede \p Param in the template parameter list.
1904///
1905/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001906static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001907SubstDefaultTemplateArgument(Sema &SemaRef,
1908 TemplateDecl *Template,
1909 SourceLocation TemplateLoc,
1910 SourceLocation RAngleLoc,
1911 TemplateTypeParmDecl *Param,
1912 TemplateArgumentListBuilder &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001913 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001914
1915 // If the argument type is dependent, instantiate it now based
1916 // on the previously-computed template arguments.
1917 if (ArgType->getType()->isDependentType()) {
1918 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1919 /*TakeArgs=*/false);
1920
1921 MultiLevelTemplateArgumentList AllTemplateArgs
1922 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1923
1924 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1925 Template, Converted.getFlatArguments(),
1926 Converted.flatSize(),
1927 SourceRange(TemplateLoc, RAngleLoc));
1928
1929 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1930 Param->getDefaultArgumentLoc(),
1931 Param->getDeclName());
1932 }
1933
1934 return ArgType;
1935}
1936
1937/// \brief Substitute template arguments into the default template argument for
1938/// the given non-type template parameter.
1939///
1940/// \param SemaRef the semantic analysis object for which we are performing
1941/// the substitution.
1942///
1943/// \param Template the template that we are synthesizing template arguments
1944/// for.
1945///
1946/// \param TemplateLoc the location of the template name that started the
1947/// template-id we are checking.
1948///
1949/// \param RAngleLoc the location of the right angle bracket ('>') that
1950/// terminates the template-id.
1951///
Douglas Gregor788cd062009-11-11 01:00:40 +00001952/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001953/// substituting into.
1954///
1955/// \param Converted the list of template arguments provided for template
1956/// parameters that precede \p Param in the template parameter list.
1957///
1958/// \returns the substituted template argument, or NULL if an error occurred.
John McCall60d7b3a2010-08-24 06:29:42 +00001959static ExprResult
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001960SubstDefaultTemplateArgument(Sema &SemaRef,
1961 TemplateDecl *Template,
1962 SourceLocation TemplateLoc,
1963 SourceLocation RAngleLoc,
1964 NonTypeTemplateParmDecl *Param,
1965 TemplateArgumentListBuilder &Converted) {
1966 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1967 /*TakeArgs=*/false);
1968
1969 MultiLevelTemplateArgumentList AllTemplateArgs
1970 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1971
1972 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1973 Template, Converted.getFlatArguments(),
1974 Converted.flatSize(),
1975 SourceRange(TemplateLoc, RAngleLoc));
1976
1977 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1978}
1979
Douglas Gregor788cd062009-11-11 01:00:40 +00001980/// \brief Substitute template arguments into the default template argument for
1981/// the given template template parameter.
1982///
1983/// \param SemaRef the semantic analysis object for which we are performing
1984/// the substitution.
1985///
1986/// \param Template the template that we are synthesizing template arguments
1987/// for.
1988///
1989/// \param TemplateLoc the location of the template name that started the
1990/// template-id we are checking.
1991///
1992/// \param RAngleLoc the location of the right angle bracket ('>') that
1993/// terminates the template-id.
1994///
1995/// \param Param the template template parameter whose default we are
1996/// substituting into.
1997///
1998/// \param Converted the list of template arguments provided for template
1999/// parameters that precede \p Param in the template parameter list.
2000///
2001/// \returns the substituted template argument, or NULL if an error occurred.
2002static TemplateName
2003SubstDefaultTemplateArgument(Sema &SemaRef,
2004 TemplateDecl *Template,
2005 SourceLocation TemplateLoc,
2006 SourceLocation RAngleLoc,
2007 TemplateTemplateParmDecl *Param,
2008 TemplateArgumentListBuilder &Converted) {
2009 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
2010 /*TakeArgs=*/false);
2011
2012 MultiLevelTemplateArgumentList AllTemplateArgs
2013 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2014
2015 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2016 Template, Converted.getFlatArguments(),
2017 Converted.flatSize(),
2018 SourceRange(TemplateLoc, RAngleLoc));
2019
2020 return SemaRef.SubstTemplateName(
2021 Param->getDefaultArgument().getArgument().getAsTemplate(),
2022 Param->getDefaultArgument().getTemplateNameLoc(),
2023 AllTemplateArgs);
2024}
2025
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002026/// \brief If the given template parameter has a default template
2027/// argument, substitute into that default template argument and
2028/// return the corresponding template argument.
2029TemplateArgumentLoc
2030Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2031 SourceLocation TemplateLoc,
2032 SourceLocation RAngleLoc,
2033 Decl *Param,
2034 TemplateArgumentListBuilder &Converted) {
2035 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
2036 if (!TypeParm->hasDefaultArgument())
2037 return TemplateArgumentLoc();
2038
John McCalla93c9342009-12-07 02:54:59 +00002039 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002040 TemplateLoc,
2041 RAngleLoc,
2042 TypeParm,
2043 Converted);
2044 if (DI)
2045 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2046
2047 return TemplateArgumentLoc();
2048 }
2049
2050 if (NonTypeTemplateParmDecl *NonTypeParm
2051 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2052 if (!NonTypeParm->hasDefaultArgument())
2053 return TemplateArgumentLoc();
2054
John McCall60d7b3a2010-08-24 06:29:42 +00002055 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002056 TemplateLoc,
2057 RAngleLoc,
2058 NonTypeParm,
2059 Converted);
2060 if (Arg.isInvalid())
2061 return TemplateArgumentLoc();
2062
2063 Expr *ArgE = Arg.takeAs<Expr>();
2064 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2065 }
2066
2067 TemplateTemplateParmDecl *TempTempParm
2068 = cast<TemplateTemplateParmDecl>(Param);
2069 if (!TempTempParm->hasDefaultArgument())
2070 return TemplateArgumentLoc();
2071
2072 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2073 TemplateLoc,
2074 RAngleLoc,
2075 TempTempParm,
2076 Converted);
2077 if (TName.isNull())
2078 return TemplateArgumentLoc();
2079
2080 return TemplateArgumentLoc(TemplateArgument(TName),
2081 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2082 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2083}
2084
Douglas Gregore7526412009-11-11 19:31:23 +00002085/// \brief Check that the given template argument corresponds to the given
2086/// template parameter.
2087bool Sema::CheckTemplateArgument(NamedDecl *Param,
2088 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00002089 TemplateDecl *Template,
2090 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002091 SourceLocation RAngleLoc,
Douglas Gregor02024a92010-03-28 02:42:43 +00002092 TemplateArgumentListBuilder &Converted,
2093 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002094 // Check template type parameters.
2095 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002096 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00002097
Douglas Gregord9e15302009-11-11 19:41:09 +00002098 // Check non-type template parameters.
2099 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002100 // Do substitution on the type of the non-type template parameter
2101 // with the template arguments we've seen thus far.
2102 QualType NTTPType = NTTP->getType();
2103 if (NTTPType->isDependentType()) {
2104 // Do substitution on the type of the non-type template parameter.
2105 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2106 NTTP, Converted.getFlatArguments(),
2107 Converted.flatSize(),
2108 SourceRange(TemplateLoc, RAngleLoc));
2109
2110 TemplateArgumentList TemplateArgs(Context, Converted,
2111 /*TakeArgs=*/false);
2112 NTTPType = SubstType(NTTPType,
2113 MultiLevelTemplateArgumentList(TemplateArgs),
2114 NTTP->getLocation(),
2115 NTTP->getDeclName());
2116 // If that worked, check the non-type template parameter type
2117 // for validity.
2118 if (!NTTPType.isNull())
2119 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2120 NTTP->getLocation());
2121 if (NTTPType.isNull())
2122 return true;
2123 }
2124
2125 switch (Arg.getArgument().getKind()) {
2126 case TemplateArgument::Null:
2127 assert(false && "Should never see a NULL template argument here");
2128 return true;
2129
2130 case TemplateArgument::Expression: {
2131 Expr *E = Arg.getArgument().getAsExpr();
2132 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002133 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00002134 return true;
2135
2136 Converted.Append(Result);
2137 break;
2138 }
2139
2140 case TemplateArgument::Declaration:
2141 case TemplateArgument::Integral:
2142 // We've already checked this template argument, so just copy
2143 // it to the list of converted arguments.
2144 Converted.Append(Arg.getArgument());
2145 break;
2146
2147 case TemplateArgument::Template:
2148 // We were given a template template argument. It may not be ill-formed;
2149 // see below.
2150 if (DependentTemplateName *DTN
2151 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2152 // We have a template argument such as \c T::template X, which we
2153 // parsed as a template template argument. However, since we now
2154 // know that we need a non-type template argument, convert this
Abramo Bagnara25777432010-08-11 22:01:17 +00002155 // template name into an expression.
2156
2157 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2158 Arg.getTemplateNameLoc());
2159
John McCallf7a1a742009-11-24 19:00:30 +00002160 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2161 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002162 Arg.getTemplateQualifierRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002163 NameInfo);
Douglas Gregore7526412009-11-11 19:31:23 +00002164
2165 TemplateArgument Result;
2166 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2167 return true;
2168
2169 Converted.Append(Result);
2170 break;
2171 }
2172
2173 // We have a template argument that actually does refer to a class
2174 // template, template alias, or template template parameter, and
2175 // therefore cannot be a non-type template argument.
2176 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2177 << Arg.getSourceRange();
2178
2179 Diag(Param->getLocation(), diag::note_template_param_here);
2180 return true;
2181
2182 case TemplateArgument::Type: {
2183 // We have a non-type template parameter but the template
2184 // argument is a type.
2185
2186 // C++ [temp.arg]p2:
2187 // In a template-argument, an ambiguity between a type-id and
2188 // an expression is resolved to a type-id, regardless of the
2189 // form of the corresponding template-parameter.
2190 //
2191 // We warn specifically about this case, since it can be rather
2192 // confusing for users.
2193 QualType T = Arg.getArgument().getAsType();
2194 SourceRange SR = Arg.getSourceRange();
2195 if (T->isFunctionType())
2196 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2197 else
2198 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2199 Diag(Param->getLocation(), diag::note_template_param_here);
2200 return true;
2201 }
2202
2203 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002204 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002205 break;
2206 }
2207
2208 return false;
2209 }
2210
2211
2212 // Check template template parameters.
2213 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2214
2215 // Substitute into the template parameter list of the template
2216 // template parameter, since previously-supplied template arguments
2217 // may appear within the template template parameter.
2218 {
2219 // Set up a template instantiation context.
2220 LocalInstantiationScope Scope(*this);
2221 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2222 TempParm, Converted.getFlatArguments(),
2223 Converted.flatSize(),
2224 SourceRange(TemplateLoc, RAngleLoc));
2225
2226 TemplateArgumentList TemplateArgs(Context, Converted,
2227 /*TakeArgs=*/false);
2228 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2229 SubstDecl(TempParm, CurContext,
2230 MultiLevelTemplateArgumentList(TemplateArgs)));
2231 if (!TempParm)
2232 return true;
2233
2234 // FIXME: TempParam is leaked.
2235 }
2236
2237 switch (Arg.getArgument().getKind()) {
2238 case TemplateArgument::Null:
2239 assert(false && "Should never see a NULL template argument here");
2240 return true;
2241
2242 case TemplateArgument::Template:
2243 if (CheckTemplateArgument(TempParm, Arg))
2244 return true;
2245
2246 Converted.Append(Arg.getArgument());
2247 break;
2248
2249 case TemplateArgument::Expression:
2250 case TemplateArgument::Type:
2251 // We have a template template parameter but the template
2252 // argument does not refer to a template.
2253 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2254 return true;
2255
2256 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002257 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002258 "Declaration argument with template template parameter");
2259 break;
2260 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002261 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002262 "Integral argument with template template parameter");
2263 break;
2264
2265 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002266 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002267 break;
2268 }
2269
2270 return false;
2271}
2272
Douglas Gregorc15cb382009-02-09 23:23:08 +00002273/// \brief Check that the given template argument list is well-formed
2274/// for specializing the given template.
2275bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2276 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002277 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002278 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002279 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002280 TemplateParameterList *Params = Template->getTemplateParameters();
2281 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002282 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002283 bool Invalid = false;
2284
John McCalld5532b62009-11-23 01:53:49 +00002285 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2286
Mike Stump1eb44332009-09-09 15:08:12 +00002287 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002288 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002289
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002290 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002291 (NumArgs < Params->getMinRequiredArguments() &&
2292 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002293 // FIXME: point at either the first arg beyond what we can handle,
2294 // or the '>', depending on whether we have too many or too few
2295 // arguments.
2296 SourceRange Range;
2297 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002298 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002299 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2300 << (NumArgs > NumParams)
2301 << (isa<ClassTemplateDecl>(Template)? 0 :
2302 isa<FunctionTemplateDecl>(Template)? 1 :
2303 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2304 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002305 Diag(Template->getLocation(), diag::note_template_decl_here)
2306 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002307 Invalid = true;
2308 }
Mike Stump1eb44332009-09-09 15:08:12 +00002309
2310 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002311 // [...] The type and form of each template-argument specified in
2312 // a template-id shall match the type and form specified for the
2313 // corresponding parameter declared by the template in its
2314 // template-parameter-list.
2315 unsigned ArgIdx = 0;
2316 for (TemplateParameterList::iterator Param = Params->begin(),
2317 ParamEnd = Params->end();
2318 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002319 if (ArgIdx > NumArgs && PartialTemplateArgs)
2320 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002321
Douglas Gregord9e15302009-11-11 19:41:09 +00002322 // If we have a template parameter pack, check every remaining template
2323 // argument against that template parameter pack.
2324 if ((*Param)->isTemplateParameterPack()) {
2325 Converted.BeginPack();
2326 for (; ArgIdx < NumArgs; ++ArgIdx) {
2327 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2328 TemplateLoc, RAngleLoc, Converted)) {
2329 Invalid = true;
2330 break;
2331 }
2332 }
2333 Converted.EndPack();
2334 continue;
2335 }
2336
Douglas Gregorf35f8282009-11-11 21:54:23 +00002337 if (ArgIdx < NumArgs) {
2338 // Check the template argument we were given.
2339 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2340 TemplateLoc, RAngleLoc, Converted))
2341 return true;
2342
2343 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002344 }
Douglas Gregore7526412009-11-11 19:31:23 +00002345
Douglas Gregorf35f8282009-11-11 21:54:23 +00002346 // We have a default template argument that we will use.
2347 TemplateArgumentLoc Arg;
2348
2349 // Retrieve the default template argument from the template
2350 // parameter. For each kind of template parameter, we substitute the
2351 // template arguments provided thus far and any "outer" template arguments
2352 // (when the template parameter was part of a nested template) into
2353 // the default argument.
2354 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2355 if (!TTP->hasDefaultArgument()) {
2356 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2357 break;
2358 }
2359
John McCalla93c9342009-12-07 02:54:59 +00002360 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002361 Template,
2362 TemplateLoc,
2363 RAngleLoc,
2364 TTP,
2365 Converted);
2366 if (!ArgType)
2367 return true;
2368
2369 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2370 ArgType);
2371 } else if (NonTypeTemplateParmDecl *NTTP
2372 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2373 if (!NTTP->hasDefaultArgument()) {
2374 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2375 break;
2376 }
2377
John McCall60d7b3a2010-08-24 06:29:42 +00002378 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002379 TemplateLoc,
2380 RAngleLoc,
2381 NTTP,
2382 Converted);
2383 if (E.isInvalid())
2384 return true;
2385
2386 Expr *Ex = E.takeAs<Expr>();
2387 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2388 } else {
2389 TemplateTemplateParmDecl *TempParm
2390 = cast<TemplateTemplateParmDecl>(*Param);
2391
2392 if (!TempParm->hasDefaultArgument()) {
2393 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2394 break;
2395 }
2396
2397 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2398 TemplateLoc,
2399 RAngleLoc,
2400 TempParm,
2401 Converted);
2402 if (Name.isNull())
2403 return true;
2404
2405 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2406 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2407 TempParm->getDefaultArgument().getTemplateNameLoc());
2408 }
2409
2410 // Introduce an instantiation record that describes where we are using
2411 // the default template argument.
2412 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2413 Converted.getFlatArguments(),
2414 Converted.flatSize(),
2415 SourceRange(TemplateLoc, RAngleLoc));
2416
2417 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002418 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002419 RAngleLoc, Converted))
2420 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002421 }
2422
2423 return Invalid;
2424}
2425
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002426namespace {
2427 class UnnamedLocalNoLinkageFinder
2428 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
2429 {
2430 Sema &S;
2431 SourceRange SR;
2432
2433 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
2434
2435 public:
2436 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
2437
2438 bool Visit(QualType T) {
2439 return inherited::Visit(T.getTypePtr());
2440 }
2441
2442#define TYPE(Class, Parent) \
2443 bool Visit##Class##Type(const Class##Type *);
2444#define ABSTRACT_TYPE(Class, Parent) \
2445 bool Visit##Class##Type(const Class##Type *) { return false; }
2446#define NON_CANONICAL_TYPE(Class, Parent) \
2447 bool Visit##Class##Type(const Class##Type *) { return false; }
2448#include "clang/AST/TypeNodes.def"
2449
2450 bool VisitTagDecl(const TagDecl *Tag);
2451 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
2452 };
2453}
2454
2455bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
2456 return false;
2457}
2458
2459bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
2460 return Visit(T->getElementType());
2461}
2462
2463bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
2464 return Visit(T->getPointeeType());
2465}
2466
2467bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
2468 const BlockPointerType* T) {
2469 return Visit(T->getPointeeType());
2470}
2471
2472bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
2473 const LValueReferenceType* T) {
2474 return Visit(T->getPointeeType());
2475}
2476
2477bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
2478 const RValueReferenceType* T) {
2479 return Visit(T->getPointeeType());
2480}
2481
2482bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
2483 const MemberPointerType* T) {
2484 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
2485}
2486
2487bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
2488 const ConstantArrayType* T) {
2489 return Visit(T->getElementType());
2490}
2491
2492bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
2493 const IncompleteArrayType* T) {
2494 return Visit(T->getElementType());
2495}
2496
2497bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
2498 const VariableArrayType* T) {
2499 return Visit(T->getElementType());
2500}
2501
2502bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
2503 const DependentSizedArrayType* T) {
2504 return Visit(T->getElementType());
2505}
2506
2507bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
2508 const DependentSizedExtVectorType* T) {
2509 return Visit(T->getElementType());
2510}
2511
2512bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
2513 return Visit(T->getElementType());
2514}
2515
2516bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
2517 return Visit(T->getElementType());
2518}
2519
2520bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
2521 const FunctionProtoType* T) {
2522 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
2523 AEnd = T->arg_type_end();
2524 A != AEnd; ++A) {
2525 if (Visit(*A))
2526 return true;
2527 }
2528
2529 return Visit(T->getResultType());
2530}
2531
2532bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
2533 const FunctionNoProtoType* T) {
2534 return Visit(T->getResultType());
2535}
2536
2537bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
2538 const UnresolvedUsingType*) {
2539 return false;
2540}
2541
2542bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
2543 return false;
2544}
2545
2546bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
2547 return Visit(T->getUnderlyingType());
2548}
2549
2550bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
2551 return false;
2552}
2553
2554bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
2555 return VisitTagDecl(T->getDecl());
2556}
2557
2558bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
2559 return VisitTagDecl(T->getDecl());
2560}
2561
2562bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
2563 const TemplateTypeParmType*) {
2564 return false;
2565}
2566
2567bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
2568 const TemplateSpecializationType*) {
2569 return false;
2570}
2571
2572bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
2573 const InjectedClassNameType* T) {
2574 return VisitTagDecl(T->getDecl());
2575}
2576
2577bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
2578 const DependentNameType* T) {
2579 return VisitNestedNameSpecifier(T->getQualifier());
2580}
2581
2582bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
2583 const DependentTemplateSpecializationType* T) {
2584 return VisitNestedNameSpecifier(T->getQualifier());
2585}
2586
2587bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
2588 return false;
2589}
2590
2591bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
2592 const ObjCInterfaceType *) {
2593 return false;
2594}
2595
2596bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
2597 const ObjCObjectPointerType *) {
2598 return false;
2599}
2600
2601bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
2602 if (Tag->getDeclContext()->isFunctionOrMethod()) {
2603 S.Diag(SR.getBegin(), diag::ext_template_arg_local_type)
2604 << S.Context.getTypeDeclType(Tag) << SR;
2605 return true;
2606 }
2607
2608 if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl()) {
2609 S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
2610 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
2611 return true;
2612 }
2613
2614 return false;
2615}
2616
2617bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
2618 NestedNameSpecifier *NNS) {
2619 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
2620 return true;
2621
2622 switch (NNS->getKind()) {
2623 case NestedNameSpecifier::Identifier:
2624 case NestedNameSpecifier::Namespace:
2625 case NestedNameSpecifier::Global:
2626 return false;
2627
2628 case NestedNameSpecifier::TypeSpec:
2629 case NestedNameSpecifier::TypeSpecWithTemplate:
2630 return Visit(QualType(NNS->getAsType(), 0));
2631 }
Fariborz Jahanian7b1ec6c2010-10-13 16:19:16 +00002632 return false;
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002633}
2634
2635
Douglas Gregorc15cb382009-02-09 23:23:08 +00002636/// \brief Check a template argument against its corresponding
2637/// template type parameter.
2638///
2639/// This routine implements the semantics of C++ [temp.arg.type]. It
2640/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002641bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002642 TypeSourceInfo *ArgInfo) {
2643 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002644 QualType Arg = ArgInfo->getType();
Douglas Gregor0fddb972010-05-22 16:17:30 +00002645 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth17fb8552010-09-03 21:12:34 +00002646
2647 if (Arg->isVariablyModifiedType()) {
2648 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002649 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00002650 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002651 }
2652
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002653 // C++03 [temp.arg.type]p2:
2654 // A local type, a type with no linkage, an unnamed type or a type
2655 // compounded from any of these types shall not be used as a
2656 // template-argument for a template type-parameter.
2657 //
2658 // C++0x allows these, and even in C++03 we allow them as an extension with
2659 // a warning.
Douglas Gregordb4d4bb2010-10-13 18:05:20 +00002660 if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002661 UnnamedLocalNoLinkageFinder Finder(*this, SR);
2662 (void)Finder.Visit(Context.getCanonicalType(Arg));
2663 }
2664
Douglas Gregorc15cb382009-02-09 23:23:08 +00002665 return false;
2666}
2667
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002668/// \brief Checks whether the given template argument is the address
2669/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002670static bool
2671CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2672 NonTypeTemplateParmDecl *Param,
2673 QualType ParamType,
2674 Expr *ArgIn,
2675 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002676 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002677 Expr *Arg = ArgIn;
2678 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002679
2680 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002681 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002682 Arg = Cast->getSubExpr();
2683
2684 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002685 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002686 // A template-argument for a non-type, non-template
2687 // template-parameter shall be one of: [...]
2688 //
2689 // -- the address of an object or function with external
2690 // linkage, including function templates and function
2691 // template-ids but excluding non-static class members,
2692 // expressed as & id-expression where the & is optional if
2693 // the name refers to a function or array, or if the
2694 // corresponding template-parameter is a reference; or
2695 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002696
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002697 // In C++98/03 mode, give an extension warning on any extra parentheses.
2698 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2699 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002700 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002701 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002702 S.Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002703 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002704 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002705 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002706 }
2707
2708 Arg = Parens->getSubExpr();
2709 }
2710
Douglas Gregorb7a09262010-04-01 18:32:35 +00002711 bool AddressTaken = false;
2712 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002713 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00002714 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002715 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb7a09262010-04-01 18:32:35 +00002716 AddressTaken = true;
2717 AddrOpLoc = UnOp->getOperatorLoc();
2718 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002719 } else
2720 DRE = dyn_cast<DeclRefExpr>(Arg);
2721
Douglas Gregorb7a09262010-04-01 18:32:35 +00002722 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002723 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2724 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002725 S.Diag(Param->getLocation(), diag::note_template_param_here);
2726 return true;
2727 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002728
2729 // Stop checking the precise nature of the argument if it is value dependent,
2730 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002731 if (Arg->isValueDependent()) {
2732 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth038cc392010-01-31 10:01:20 +00002733 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002734 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002735
Douglas Gregorb7a09262010-04-01 18:32:35 +00002736 if (!isa<ValueDecl>(DRE->getDecl())) {
2737 S.Diag(Arg->getSourceRange().getBegin(),
2738 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002739 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002740 S.Diag(Param->getLocation(), diag::note_template_param_here);
2741 return true;
2742 }
2743
2744 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002745
2746 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00002747 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2748 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002749 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002750 S.Diag(Param->getLocation(), diag::note_template_param_here);
2751 return true;
2752 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002753
2754 // Cannot refer to non-static member functions
2755 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00002756 if (!Method->isStatic()) {
2757 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002758 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002759 S.Diag(Param->getLocation(), diag::note_template_param_here);
2760 return true;
2761 }
Mike Stump1eb44332009-09-09 15:08:12 +00002762
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002763 // Functions must have external linkage.
2764 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002765 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002766 S.Diag(Arg->getSourceRange().getBegin(),
2767 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002768 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002769 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002770 << true;
2771 return true;
2772 }
2773
2774 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002775 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002776
Douglas Gregorb7a09262010-04-01 18:32:35 +00002777 // If the template parameter has pointer type, the function decays.
2778 if (ParamType->isPointerType() && !AddressTaken)
2779 ArgType = S.Context.getPointerType(Func->getType());
2780 else if (AddressTaken && ParamType->isReferenceType()) {
2781 // If we originally had an address-of operator, but the
2782 // parameter has reference type, complain and (if things look
2783 // like they will work) drop the address-of operator.
2784 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2785 ParamType.getNonReferenceType())) {
2786 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2787 << ParamType;
2788 S.Diag(Param->getLocation(), diag::note_template_param_here);
2789 return true;
2790 }
2791
2792 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2793 << ParamType
2794 << FixItHint::CreateRemoval(AddrOpLoc);
2795 S.Diag(Param->getLocation(), diag::note_template_param_here);
2796
2797 ArgType = Func->getType();
2798 }
2799 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002800 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002801 S.Diag(Arg->getSourceRange().getBegin(),
2802 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002803 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002804 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002805 << true;
2806 return true;
2807 }
2808
Douglas Gregorb7a09262010-04-01 18:32:35 +00002809 // A value of reference type is not an object.
2810 if (Var->getType()->isReferenceType()) {
2811 S.Diag(Arg->getSourceRange().getBegin(),
2812 diag::err_template_arg_reference_var)
2813 << Var->getType() << Arg->getSourceRange();
2814 S.Diag(Param->getLocation(), diag::note_template_param_here);
2815 return true;
2816 }
2817
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002818 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002819 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002820
2821 // If the template parameter has pointer type, we must have taken
2822 // the address of this object.
2823 if (ParamType->isReferenceType()) {
2824 if (AddressTaken) {
2825 // If we originally had an address-of operator, but the
2826 // parameter has reference type, complain and (if things look
2827 // like they will work) drop the address-of operator.
2828 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2829 ParamType.getNonReferenceType())) {
2830 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2831 << ParamType;
2832 S.Diag(Param->getLocation(), diag::note_template_param_here);
2833 return true;
2834 }
2835
2836 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2837 << ParamType
2838 << FixItHint::CreateRemoval(AddrOpLoc);
2839 S.Diag(Param->getLocation(), diag::note_template_param_here);
2840
2841 ArgType = Var->getType();
2842 }
2843 } else if (!AddressTaken && ParamType->isPointerType()) {
2844 if (Var->getType()->isArrayType()) {
2845 // Array-to-pointer decay.
2846 ArgType = S.Context.getArrayDecayedType(Var->getType());
2847 } else {
2848 // If the template parameter has pointer type but the address of
2849 // this object was not taken, complain and (possibly) recover by
2850 // taking the address of the entity.
2851 ArgType = S.Context.getPointerType(Var->getType());
2852 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2853 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2854 << ParamType;
2855 S.Diag(Param->getLocation(), diag::note_template_param_here);
2856 return true;
2857 }
2858
2859 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2860 << ParamType
2861 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2862
2863 S.Diag(Param->getLocation(), diag::note_template_param_here);
2864 }
2865 }
2866 } else {
2867 // We found something else, but we don't know specifically what it is.
2868 S.Diag(Arg->getSourceRange().getBegin(),
2869 diag::err_template_arg_not_object_or_func)
2870 << Arg->getSourceRange();
2871 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2872 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002873 }
Mike Stump1eb44332009-09-09 15:08:12 +00002874
Douglas Gregorb7a09262010-04-01 18:32:35 +00002875 if (ParamType->isPointerType() &&
2876 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2877 S.IsQualificationConversion(ArgType, ParamType)) {
2878 // For pointer-to-object types, qualification conversions are
2879 // permitted.
2880 } else {
2881 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2882 if (!ParamRef->getPointeeType()->isFunctionType()) {
2883 // C++ [temp.arg.nontype]p5b3:
2884 // For a non-type template-parameter of type reference to
2885 // object, no conversions apply. The type referred to by the
2886 // reference may be more cv-qualified than the (otherwise
2887 // identical) type of the template- argument. The
2888 // template-parameter is bound directly to the
2889 // template-argument, which shall be an lvalue.
2890
2891 // FIXME: Other qualifiers?
2892 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2893 unsigned ArgQuals = ArgType.getCVRQualifiers();
2894
2895 if ((ParamQuals | ArgQuals) != ParamQuals) {
2896 S.Diag(Arg->getSourceRange().getBegin(),
2897 diag::err_template_arg_ref_bind_ignores_quals)
2898 << ParamType << Arg->getType()
2899 << Arg->getSourceRange();
2900 S.Diag(Param->getLocation(), diag::note_template_param_here);
2901 return true;
2902 }
2903 }
2904 }
2905
2906 // At this point, the template argument refers to an object or
2907 // function with external linkage. We now need to check whether the
2908 // argument and parameter types are compatible.
2909 if (!S.Context.hasSameUnqualifiedType(ArgType,
2910 ParamType.getNonReferenceType())) {
2911 // We can't perform this conversion or binding.
2912 if (ParamType->isReferenceType())
2913 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2914 << ParamType << Arg->getType() << Arg->getSourceRange();
2915 else
2916 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2917 << Arg->getType() << ParamType << Arg->getSourceRange();
2918 S.Diag(Param->getLocation(), diag::note_template_param_here);
2919 return true;
2920 }
2921 }
2922
2923 // Create the template argument.
2924 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor77c13e02010-04-24 18:20:53 +00002925 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00002926 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002927}
2928
2929/// \brief Checks whether the given template argument is a pointer to
2930/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002931bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2932 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002933 bool Invalid = false;
2934
2935 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002936 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002937 Arg = Cast->getSubExpr();
2938
2939 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002940 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002941 // A template-argument for a non-type, non-template
2942 // template-parameter shall be one of: [...]
2943 //
2944 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002945 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002946
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002947 // In C++98/03 mode, give an extension warning on any extra parentheses.
2948 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2949 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002950 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002951 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00002952 Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002953 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002954 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002955 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002956 }
2957
2958 Arg = Parens->getSubExpr();
2959 }
2960
Douglas Gregorcaddba02009-11-12 18:38:13 +00002961 // A pointer-to-member constant written &Class::member.
2962 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00002963 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002964 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2965 if (DRE && !DRE->getQualifier())
2966 DRE = 0;
2967 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002968 }
2969 // A constant of pointer-to-member type.
2970 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2971 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2972 if (VD->getType()->isMemberPointerType()) {
2973 if (isa<NonTypeTemplateParmDecl>(VD) ||
2974 (isa<VarDecl>(VD) &&
2975 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2976 if (Arg->isTypeDependent() || Arg->isValueDependent())
2977 Converted = TemplateArgument(Arg->Retain());
2978 else
2979 Converted = TemplateArgument(VD->getCanonicalDecl());
2980 return Invalid;
2981 }
2982 }
2983 }
2984
2985 DRE = 0;
2986 }
2987
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002988 if (!DRE)
2989 return Diag(Arg->getSourceRange().getBegin(),
2990 diag::err_template_arg_not_pointer_to_member_form)
2991 << Arg->getSourceRange();
2992
2993 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2994 assert((isa<FieldDecl>(DRE->getDecl()) ||
2995 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2996 "Only non-static member pointers can make it here");
2997
2998 // Okay: this is the address of a non-static member, and therefore
2999 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00003000 if (Arg->isTypeDependent() || Arg->isValueDependent())
3001 Converted = TemplateArgument(Arg->Retain());
3002 else
3003 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003004 return Invalid;
3005 }
3006
3007 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00003008 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003009 diag::err_template_arg_not_pointer_to_member_form)
3010 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003011 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003012 diag::note_template_arg_refers_here);
3013 return true;
3014}
3015
Douglas Gregorc15cb382009-02-09 23:23:08 +00003016/// \brief Check a template argument against its corresponding
3017/// non-type template parameter.
3018///
Douglas Gregor2943aed2009-03-03 04:44:36 +00003019/// This routine implements the semantics of C++ [temp.arg.nontype].
3020/// It returns true if an error occurred, and false otherwise. \p
3021/// InstantiatedParamType is the type of the non-type template
3022/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003023///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003024/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00003025bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00003026 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00003027 TemplateArgument &Converted,
3028 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00003029 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
3030
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003031 // If either the parameter has a dependent type or the argument is
3032 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00003033 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3034 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003035 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003036 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00003037 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003038
3039 // C++ [temp.arg.nontype]p5:
3040 // The following conversions are performed on each expression used
3041 // as a non-type template-argument. If a non-type
3042 // template-argument cannot be converted to the type of the
3043 // corresponding template-parameter then the program is
3044 // ill-formed.
3045 //
3046 // -- for a non-type template-parameter of integral or
3047 // enumeration type, integral promotions (4.5) and integral
3048 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00003049 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00003050 QualType ArgType = Arg->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003051 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003052 // C++ [temp.arg.nontype]p1:
3053 // A template-argument for a non-type, non-template
3054 // template-parameter shall be one of:
3055 //
3056 // -- an integral constant-expression of integral or enumeration
3057 // type; or
3058 // -- the name of a non-type template-parameter; or
3059 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003060 llvm::APSInt Value;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003061 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003062 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003063 diag::err_template_arg_not_integral_or_enumeral)
3064 << ArgType << Arg->getSourceRange();
3065 Diag(Param->getLocation(), diag::note_template_param_here);
3066 return true;
3067 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003068 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003069 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
3070 << ArgType << Arg->getSourceRange();
3071 return true;
3072 }
3073
Douglas Gregor02024a92010-03-28 02:42:43 +00003074 // From here on out, all we care about are the unqualified forms
3075 // of the parameter and argument types.
3076 ParamType = ParamType.getUnqualifiedType();
3077 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003078
3079 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00003080 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003081 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00003082 } else if (CTAK == CTAK_Deduced) {
3083 // C++ [temp.deduct.type]p17:
3084 // If, in the declaration of a function template with a non-type
3085 // template-parameter, the non-type template- parameter is used
3086 // in an expression in the function parameter-list and, if the
3087 // corresponding template-argument is deduced, the
3088 // template-argument type shall match the type of the
3089 // template-parameter exactly, except that a template-argument
3090 // deduced from an array bound may be of any integral type.
3091 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3092 << ArgType << ParamType;
3093 Diag(Param->getLocation(), diag::note_template_param_here);
3094 return true;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003095 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3096 !ParamType->isEnumeralType()) {
3097 // This is an integral promotion or conversion.
John McCall2de56d12010-08-25 11:45:40 +00003098 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003099 } else {
3100 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003101 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003102 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003103 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003104 Diag(Param->getLocation(), diag::note_template_param_here);
3105 return true;
3106 }
3107
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003108 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00003109 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003110 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003111
3112 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003113 llvm::APSInt OldValue = Value;
3114
3115 // Coerce the template argument's value to the value it will have
3116 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003117 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003118 if (Value.getBitWidth() != AllowedBits)
3119 Value.extOrTrunc(AllowedBits);
3120 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003121
3122 // Complain if an unsigned parameter received a negative value.
3123 if (IntegerType->isUnsignedIntegerType()
3124 && (OldValue.isSigned() && OldValue.isNegative())) {
3125 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3126 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3127 << Arg->getSourceRange();
3128 Diag(Param->getLocation(), diag::note_template_param_here);
3129 }
3130
3131 // Complain if we overflowed the template parameter's type.
3132 unsigned RequiredBits;
3133 if (IntegerType->isUnsignedIntegerType())
3134 RequiredBits = OldValue.getActiveBits();
3135 else if (OldValue.isUnsigned())
3136 RequiredBits = OldValue.getActiveBits() + 1;
3137 else
3138 RequiredBits = OldValue.getMinSignedBits();
3139 if (RequiredBits > AllowedBits) {
3140 Diag(Arg->getSourceRange().getBegin(),
3141 diag::warn_template_arg_too_large)
3142 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3143 << Arg->getSourceRange();
3144 Diag(Param->getLocation(), diag::note_template_param_here);
3145 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003146 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003147
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003148 // Add the value of this argument to the list of converted
3149 // arguments. We use the bitwidth and signedness of the template
3150 // parameter.
3151 if (Arg->isValueDependent()) {
3152 // The argument is value-dependent. Create a new
3153 // TemplateArgument with the converted expression.
3154 Converted = TemplateArgument(Arg);
3155 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003156 }
3157
John McCall833ca992009-10-29 08:12:44 +00003158 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00003159 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003160 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003161 return false;
3162 }
Douglas Gregora35284b2009-02-11 00:19:33 +00003163
John McCall6bb80172010-03-30 21:47:33 +00003164 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3165
Douglas Gregorb7a09262010-04-01 18:32:35 +00003166 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3167 // from a template argument of type std::nullptr_t to a non-type
3168 // template parameter of type pointer to object, pointer to
3169 // function, or pointer-to-member, respectively.
3170 if (ArgType->isNullPtrType() &&
3171 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
3172 Converted = TemplateArgument((NamedDecl *)0);
3173 return false;
3174 }
3175
Douglas Gregorb86b0572009-02-11 01:18:59 +00003176 // Handle pointer-to-function, reference-to-function, and
3177 // pointer-to-member-function all in (roughly) the same way.
3178 if (// -- For a non-type template-parameter of type pointer to
3179 // function, only the function-to-pointer conversion (4.3) is
3180 // applied. If the template-argument represents a set of
3181 // overloaded functions (or a pointer to such), the matching
3182 // function is selected from the set (13.4).
3183 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003184 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003185 // -- For a non-type template-parameter of type reference to
3186 // function, no conversions apply. If the template-argument
3187 // represents a set of overloaded functions, the matching
3188 // function is selected from the set (13.4).
3189 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003190 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003191 // -- For a non-type template-parameter of type pointer to
3192 // member function, no conversions apply. If the
3193 // template-argument represents a set of overloaded member
3194 // functions, the matching member function is selected from
3195 // the set (13.4).
3196 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003197 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00003198 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003199
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003200 if (Arg->getType() == Context.OverloadTy) {
3201 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
3202 true,
3203 FoundResult)) {
3204 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3205 return true;
3206
3207 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3208 ArgType = Arg->getType();
3209 } else
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003210 return true;
Douglas Gregora35284b2009-02-11 00:19:33 +00003211 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003212
Douglas Gregorb7a09262010-04-01 18:32:35 +00003213 if (!ParamType->isMemberPointerType())
3214 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3215 ParamType,
3216 Arg, Converted);
3217
3218 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCall2de56d12010-08-25 11:45:40 +00003219 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb7a09262010-04-01 18:32:35 +00003220 } else if (!Context.hasSameUnqualifiedType(ArgType,
3221 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00003222 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003223 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00003224 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003225 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00003226 Diag(Param->getLocation(), diag::note_template_param_here);
3227 return true;
3228 }
Mike Stump1eb44332009-09-09 15:08:12 +00003229
Douglas Gregorb7a09262010-04-01 18:32:35 +00003230 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregora35284b2009-02-11 00:19:33 +00003231 }
3232
Chris Lattnerfe90de72009-02-20 21:37:53 +00003233 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003234 // -- for a non-type template-parameter of type pointer to
3235 // object, qualification conversions (4.4) and the
3236 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00003237 // C++0x also allows a value of std::nullptr_t.
Eli Friedman13578692010-08-05 02:49:48 +00003238 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003239 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003240
Douglas Gregorb7a09262010-04-01 18:32:35 +00003241 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3242 ParamType,
3243 Arg, Converted);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003244 }
Mike Stump1eb44332009-09-09 15:08:12 +00003245
Ted Kremenek6217b802009-07-29 21:53:49 +00003246 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003247 // -- For a non-type template-parameter of type reference to
3248 // object, no conversions apply. The type referred to by the
3249 // reference may be more cv-qualified than the (otherwise
3250 // identical) type of the template-argument. The
3251 // template-parameter is bound directly to the
3252 // template-argument, which must be an lvalue.
Eli Friedman13578692010-08-05 02:49:48 +00003253 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003254 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003255
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003256 if (Arg->getType() == Context.OverloadTy) {
3257 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
3258 ParamRefType->getPointeeType(),
3259 true,
3260 FoundResult)) {
3261 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3262 return true;
3263
3264 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3265 ArgType = Arg->getType();
3266 } else
Douglas Gregorb7a09262010-04-01 18:32:35 +00003267 return true;
Douglas Gregorb86b0572009-02-11 01:18:59 +00003268 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003269
Douglas Gregorb7a09262010-04-01 18:32:35 +00003270 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3271 ParamType,
3272 Arg, Converted);
Douglas Gregorb86b0572009-02-11 01:18:59 +00003273 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00003274
3275 // -- For a non-type template-parameter of type pointer to data
3276 // member, qualification conversions (4.4) are applied.
3277 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3278
Douglas Gregor8e6563b2009-02-11 18:22:40 +00003279 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00003280 // Types match exactly: nothing more to do here.
3281 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCall2de56d12010-08-25 11:45:40 +00003282 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor658bbb52009-02-11 16:16:59 +00003283 } else {
3284 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003285 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00003286 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003287 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00003288 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00003289 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00003290 }
3291
Douglas Gregorcaddba02009-11-12 18:38:13 +00003292 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00003293}
3294
3295/// \brief Check a template argument against its corresponding
3296/// template template parameter.
3297///
3298/// This routine implements the semantics of C++ [temp.arg.template].
3299/// It returns true if an error occurred, and false otherwise.
3300bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00003301 const TemplateArgumentLoc &Arg) {
3302 TemplateName Name = Arg.getArgument().getAsTemplate();
3303 TemplateDecl *Template = Name.getAsTemplateDecl();
3304 if (!Template) {
3305 // Any dependent template name is fine.
3306 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3307 return false;
3308 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003309
3310 // C++ [temp.arg.template]p1:
3311 // A template-argument for a template template-parameter shall be
3312 // the name of a class template, expressed as id-expression. Only
3313 // primary class templates are considered when matching the
3314 // template template argument with the corresponding parameter;
3315 // partial specializations are not considered even if their
3316 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003317 //
3318 // Note that we also allow template template parameters here, which
3319 // will happen when we are dealing with, e.g., class template
3320 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00003321 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003322 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003323 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00003324 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00003325 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00003326 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003327 << Template;
3328 }
3329
3330 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3331 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00003332 true,
3333 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00003334 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00003335}
3336
Douglas Gregor02024a92010-03-28 02:42:43 +00003337/// \brief Given a non-type template argument that refers to a
3338/// declaration and the type of its corresponding non-type template
3339/// parameter, produce an expression that properly refers to that
3340/// declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00003341ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003342Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3343 QualType ParamType,
3344 SourceLocation Loc) {
3345 assert(Arg.getKind() == TemplateArgument::Declaration &&
3346 "Only declaration template arguments permitted here");
3347 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3348
3349 if (VD->getDeclContext()->isRecord() &&
3350 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3351 // If the value is a class member, we might have a pointer-to-member.
3352 // Determine whether the non-type template template parameter is of
3353 // pointer-to-member type. If so, we need to build an appropriate
3354 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3355 // would refer to the member itself.
3356 if (ParamType->isMemberPointerType()) {
3357 QualType ClassType
3358 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3359 NestedNameSpecifier *Qualifier
John McCall9ae2f072010-08-23 23:25:46 +00003360 = NestedNameSpecifier::Create(Context, 0, false,
3361 ClassType.getTypePtr());
Douglas Gregor02024a92010-03-28 02:42:43 +00003362 CXXScopeSpec SS;
3363 SS.setScopeRep(Qualifier);
John McCall60d7b3a2010-08-24 06:29:42 +00003364 ExprResult RefExpr = BuildDeclRefExpr(VD,
Douglas Gregor02024a92010-03-28 02:42:43 +00003365 VD->getType().getNonReferenceType(),
3366 Loc,
3367 &SS);
3368 if (RefExpr.isInvalid())
3369 return ExprError();
3370
John McCall2de56d12010-08-25 11:45:40 +00003371 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorc0c83002010-04-30 21:46:38 +00003372
3373 // We might need to perform a trailing qualification conversion, since
3374 // the element type on the parameter could be more qualified than the
3375 // element type in the expression we constructed.
3376 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3377 ParamType.getUnqualifiedType())) {
3378 Expr *RefE = RefExpr.takeAs<Expr>();
John McCall2de56d12010-08-25 11:45:40 +00003379 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorc0c83002010-04-30 21:46:38 +00003380 RefExpr = Owned(RefE);
3381 }
3382
Douglas Gregor02024a92010-03-28 02:42:43 +00003383 assert(!RefExpr.isInvalid() &&
3384 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00003385 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00003386 return move(RefExpr);
3387 }
3388 }
3389
3390 QualType T = VD->getType().getNonReferenceType();
3391 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003392 // When the non-type template parameter is a pointer, take the
3393 // address of the declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00003394 ExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003395 if (RefExpr.isInvalid())
3396 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003397
3398 if (T->isFunctionType() || T->isArrayType()) {
3399 // Decay functions and arrays.
3400 Expr *RefE = (Expr *)RefExpr.get();
3401 DefaultFunctionArrayConversion(RefE);
3402 if (RefE != RefExpr.get()) {
3403 RefExpr.release();
3404 RefExpr = Owned(RefE);
3405 }
3406
3407 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00003408 }
3409
Douglas Gregorb7a09262010-04-01 18:32:35 +00003410 // Take the address of everything else
John McCall2de56d12010-08-25 11:45:40 +00003411 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregor02024a92010-03-28 02:42:43 +00003412 }
3413
3414 // If the non-type template parameter has reference type, qualify the
3415 // resulting declaration reference with the extra qualifiers on the
3416 // type that the reference refers to.
3417 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3418 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3419
3420 return BuildDeclRefExpr(VD, T, Loc);
3421}
3422
3423/// \brief Construct a new expression that refers to the given
3424/// integral template argument with the given source-location
3425/// information.
3426///
3427/// This routine takes care of the mapping from an integral template
3428/// argument (which may have any integral type) to the appropriate
3429/// literal value.
John McCall60d7b3a2010-08-24 06:29:42 +00003430ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003431Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3432 SourceLocation Loc) {
3433 assert(Arg.getKind() == TemplateArgument::Integral &&
3434 "Operation is only value for integral template arguments");
3435 QualType T = Arg.getIntegralType();
3436 if (T->isCharType() || T->isWideCharType())
3437 return Owned(new (Context) CharacterLiteral(
3438 Arg.getAsIntegral()->getZExtValue(),
3439 T->isWideCharType(),
3440 T,
3441 Loc));
3442 if (T->isBooleanType())
3443 return Owned(new (Context) CXXBoolLiteralExpr(
3444 Arg.getAsIntegral()->getBoolValue(),
3445 T,
3446 Loc));
3447
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003448 return Owned(IntegerLiteral::Create(Context, *Arg.getAsIntegral(), T, Loc));
Douglas Gregor02024a92010-03-28 02:42:43 +00003449}
3450
3451
Douglas Gregorddc29e12009-02-06 22:42:48 +00003452/// \brief Determine whether the given template parameter lists are
3453/// equivalent.
3454///
Mike Stump1eb44332009-09-09 15:08:12 +00003455/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00003456/// source code as part of a new template declaration.
3457///
3458/// \param Old The old template parameter list, typically found via
3459/// name lookup of the template declared with this template parameter
3460/// list.
3461///
3462/// \param Complain If true, this routine will produce a diagnostic if
3463/// the template parameter lists are not equivalent.
3464///
Douglas Gregorfb898e12009-11-12 16:20:59 +00003465/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00003466///
3467/// \param TemplateArgLoc If this source location is valid, then we
3468/// are actually checking the template parameter list of a template
3469/// argument (New) against the template parameter list of its
3470/// corresponding template template parameter (Old). We produce
3471/// slightly different diagnostics in this scenario.
3472///
Douglas Gregorddc29e12009-02-06 22:42:48 +00003473/// \returns True if the template parameter lists are equal, false
3474/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003475bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00003476Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3477 TemplateParameterList *Old,
3478 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003479 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003480 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003481 if (Old->size() != New->size()) {
3482 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003483 unsigned NextDiag = diag::err_template_param_list_different_arity;
3484 if (TemplateArgLoc.isValid()) {
3485 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3486 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00003487 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003488 Diag(New->getTemplateLoc(), NextDiag)
3489 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00003490 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003491 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00003492 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003493 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003494 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3495 }
3496
3497 return false;
3498 }
3499
3500 for (TemplateParameterList::iterator OldParm = Old->begin(),
3501 OldParmEnd = Old->end(), NewParm = New->begin();
3502 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3503 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003504 if (Complain) {
3505 unsigned NextDiag = diag::err_template_param_different_kind;
3506 if (TemplateArgLoc.isValid()) {
3507 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3508 NextDiag = diag::note_template_param_different_kind;
3509 }
3510 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003511 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003512 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003513 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00003514 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003515 return false;
3516 }
3517
Douglas Gregora417b872010-06-04 08:34:32 +00003518 if (TemplateTypeParmDecl *OldTTP
3519 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3520 // Template type parameters are equivalent if either both are template
3521 // type parameter packs or neither are (since we know we're at the same
3522 // index).
3523 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3524 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3525 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3526 // allow one to match a template parameter pack in the template
3527 // parameter list of a template template parameter to one or more
3528 // template parameters in the template parameter list of the
3529 // corresponding template template argument.
3530 if (Complain) {
3531 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3532 if (TemplateArgLoc.isValid()) {
3533 Diag(TemplateArgLoc,
3534 diag::err_template_arg_template_params_mismatch);
3535 NextDiag = diag::note_template_parameter_pack_non_pack;
3536 }
3537 Diag(NewTTP->getLocation(), NextDiag)
3538 << 0 << NewTTP->isParameterPack();
3539 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3540 << 0 << OldTTP->isParameterPack();
3541 }
3542 return false;
3543 }
Mike Stump1eb44332009-09-09 15:08:12 +00003544 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003545 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3546 // The types of non-type template parameters must agree.
3547 NonTypeTemplateParmDecl *NewNTTP
3548 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00003549
3550 // If we are matching a template template argument to a template
3551 // template parameter and one of the non-type template parameter types
3552 // is dependent, then we must wait until template instantiation time
3553 // to actually compare the arguments.
3554 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3555 (OldNTTP->getType()->isDependentType() ||
3556 NewNTTP->getType()->isDependentType()))
3557 continue;
3558
Douglas Gregorddc29e12009-02-06 22:42:48 +00003559 if (Context.getCanonicalType(OldNTTP->getType()) !=
3560 Context.getCanonicalType(NewNTTP->getType())) {
3561 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003562 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3563 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003564 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003565 diag::err_template_arg_template_params_mismatch);
3566 NextDiag = diag::note_template_nontype_parm_different_type;
3567 }
3568 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003569 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00003570 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00003571 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00003572 diag::note_template_nontype_parm_prev_declaration)
3573 << OldNTTP->getType();
3574 }
3575 return false;
3576 }
3577 } else {
3578 // The template parameter lists of template template
3579 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00003580 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00003581 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00003582 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003583 = cast<TemplateTemplateParmDecl>(*OldParm);
3584 TemplateTemplateParmDecl *NewTTP
3585 = cast<TemplateTemplateParmDecl>(*NewParm);
3586 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3587 OldTTP->getTemplateParameters(),
3588 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003589 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00003590 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003591 return false;
3592 }
3593 }
3594
3595 return true;
3596}
3597
3598/// \brief Check whether a template can be declared within this scope.
3599///
3600/// If the template declaration is valid in this scope, returns
3601/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003602bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003603Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003604 // Find the nearest enclosing declaration scope.
3605 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3606 (S->getFlags() & Scope::TemplateParamScope) != 0)
3607 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003608
Douglas Gregorddc29e12009-02-06 22:42:48 +00003609 // C++ [temp]p2:
3610 // A template-declaration can appear only as a namespace scope or
3611 // class scope declaration.
3612 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003613 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3614 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003615 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003616 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003617
Eli Friedman1503f772009-07-31 01:43:05 +00003618 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003619 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003620
3621 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3622 return false;
3623
Mike Stump1eb44332009-09-09 15:08:12 +00003624 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003625 diag::err_template_outside_namespace_or_class_scope)
3626 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003627}
Douglas Gregorcc636682009-02-17 23:15:12 +00003628
Douglas Gregord5cb8762009-10-07 00:13:32 +00003629/// \brief Determine what kind of template specialization the given declaration
3630/// is.
3631static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3632 if (!D)
3633 return TSK_Undeclared;
3634
Douglas Gregorf6b11852009-10-08 15:14:33 +00003635 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3636 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003637 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3638 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003639 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3640 return Var->getTemplateSpecializationKind();
3641
Douglas Gregord5cb8762009-10-07 00:13:32 +00003642 return TSK_Undeclared;
3643}
3644
Douglas Gregor9302da62009-10-14 23:50:59 +00003645/// \brief Check whether a specialization is well-formed in the current
3646/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003647///
Douglas Gregor9302da62009-10-14 23:50:59 +00003648/// This routine determines whether a template specialization can be declared
3649/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003650///
3651/// \param S the semantic analysis object for which this check is being
3652/// performed.
3653///
3654/// \param Specialized the entity being specialized or instantiated, which
3655/// may be a kind of template (class template, function template, etc.) or
3656/// a member of a class template (member function, static data member,
3657/// member class).
3658///
3659/// \param PrevDecl the previous declaration of this entity, if any.
3660///
3661/// \param Loc the location of the explicit specialization or instantiation of
3662/// this entity.
3663///
3664/// \param IsPartialSpecialization whether this is a partial specialization of
3665/// a class template.
3666///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003667/// \returns true if there was an error that we cannot recover from, false
3668/// otherwise.
3669static bool CheckTemplateSpecializationScope(Sema &S,
3670 NamedDecl *Specialized,
3671 NamedDecl *PrevDecl,
3672 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003673 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003674 // Keep these "kind" numbers in sync with the %select statements in the
3675 // various diagnostics emitted by this routine.
3676 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003677 bool isTemplateSpecialization = false;
3678 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003679 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003680 isTemplateSpecialization = true;
3681 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003682 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003683 isTemplateSpecialization = true;
3684 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003685 EntityKind = 3;
3686 else if (isa<VarDecl>(Specialized))
3687 EntityKind = 4;
3688 else if (isa<RecordDecl>(Specialized))
3689 EntityKind = 5;
3690 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003691 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3692 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003693 return true;
3694 }
3695
Douglas Gregor88b70942009-02-25 22:02:03 +00003696 // C++ [temp.expl.spec]p2:
3697 // An explicit specialization shall be declared in the namespace
3698 // of which the template is a member, or, for member templates, in
3699 // the namespace of which the enclosing class or enclosing class
3700 // template is a member. An explicit specialization of a member
3701 // function, member class or static data member of a class
3702 // template shall be declared in the namespace of which the class
3703 // template is a member. Such a declaration may also be a
3704 // definition. If the declaration is not a definition, the
3705 // specialization may be defined later in the name- space in which
3706 // the explicit specialization was declared, or in a namespace
3707 // that encloses the one in which the explicit specialization was
3708 // declared.
Sebastian Redl7a126a42010-08-31 00:36:30 +00003709 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003710 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003711 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003712 return true;
3713 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003714
Douglas Gregor0a407472009-10-07 17:30:37 +00003715 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3716 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003717 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003718 return true;
3719 }
3720
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003721 // C++ [temp.class.spec]p6:
3722 // A class template partial specialization may be declared or redeclared
3723 // in any namespace scope in which its definition may be defined (14.5.1
3724 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003725 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003726 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003727 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003728 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003729 if ((!PrevDecl ||
3730 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3731 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregor121dc9a2010-09-12 05:08:28 +00003732 // C++ [temp.exp.spec]p2:
3733 // An explicit specialization shall be declared in the namespace of which
3734 // the template is a member, or, for member templates, in the namespace
3735 // of which the enclosing class or enclosing class template is a member.
3736 // An explicit specialization of a member function, member class or
3737 // static data member of a class template shall be declared in the
3738 // namespace of which the class template is a member.
3739 //
3740 // C++0x [temp.expl.spec]p2:
3741 // An explicit specialization shall be declared in a namespace enclosing
3742 // the specialized template.
3743 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
3744 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
Douglas Gregora4d5de52010-09-12 05:24:55 +00003745 bool IsCPlusPlus0xExtension
3746 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00003747 if (isa<TranslationUnitDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00003748 S.Diag(Loc, IsCPlusPlus0xExtension
3749 ? diag::ext_template_spec_decl_out_of_scope_global
3750 : diag::err_template_spec_decl_out_of_scope_global)
3751 << EntityKind << Specialized;
Douglas Gregor9302da62009-10-14 23:50:59 +00003752 else if (isa<NamespaceDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00003753 S.Diag(Loc, IsCPlusPlus0xExtension
3754 ? diag::ext_template_spec_decl_out_of_scope
3755 : diag::err_template_spec_decl_out_of_scope)
3756 << EntityKind << Specialized
3757 << cast<NamedDecl>(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00003758
3759 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3760 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003761 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003762 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003763
3764 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003765 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003766 // Note that HandleDeclarator() performs this check for explicit
3767 // specializations of function templates, static data members, and member
3768 // functions, so we skip the check here for those kinds of entities.
3769 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003770 // Should we refactor that check, so that it occurs later?
3771 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003772 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3773 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003774 if (isa<TranslationUnitDecl>(SpecializedContext))
3775 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3776 << EntityKind << Specialized;
3777 else if (isa<NamespaceDecl>(SpecializedContext))
3778 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3779 << EntityKind << Specialized
3780 << cast<NamedDecl>(SpecializedContext);
3781
Douglas Gregor9302da62009-10-14 23:50:59 +00003782 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003783 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003784
3785 // FIXME: check for specialization-after-instantiation errors and such.
3786
Douglas Gregor88b70942009-02-25 22:02:03 +00003787 return false;
3788}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003789
Douglas Gregore94866f2009-06-12 21:21:02 +00003790/// \brief Check the non-type template arguments of a class template
3791/// partial specialization according to C++ [temp.class.spec]p9.
3792///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003793/// \param TemplateParams the template parameters of the primary class
3794/// template.
3795///
3796/// \param TemplateArg the template arguments of the class template
3797/// partial specialization.
3798///
3799/// \param MirrorsPrimaryTemplate will be set true if the class
3800/// template partial specialization arguments are identical to the
3801/// implicit template arguments of the primary template. This is not
3802/// necessarily an error (C++0x), and it is left to the caller to diagnose
3803/// this condition when it is an error.
3804///
Douglas Gregore94866f2009-06-12 21:21:02 +00003805/// \returns true if there was an error, false otherwise.
3806bool Sema::CheckClassTemplatePartialSpecializationArgs(
3807 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00003808 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003809 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003810 // FIXME: the interface to this function will have to change to
3811 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003812 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003813
Anders Carlssonfb250522009-06-23 01:26:57 +00003814 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00003815
Douglas Gregore94866f2009-06-12 21:21:02 +00003816 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003817 // Determine whether the template argument list of the partial
3818 // specialization is identical to the implicit argument list of
3819 // the primary template. The caller may need to diagnostic this as
3820 // an error per C++ [temp.class.spec]p9b3.
3821 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003822 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003823 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3824 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003825 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003826 MirrorsPrimaryTemplate = false;
3827 } else if (TemplateTemplateParmDecl *TTP
3828 = dyn_cast<TemplateTemplateParmDecl>(
3829 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003830 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003831 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003832 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003833 if (!ArgDecl ||
3834 ArgDecl->getIndex() != TTP->getIndex() ||
3835 ArgDecl->getDepth() != TTP->getDepth())
3836 MirrorsPrimaryTemplate = false;
3837 }
3838 }
3839
Mike Stump1eb44332009-09-09 15:08:12 +00003840 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003841 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003842 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003843 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003844 }
3845
Anders Carlsson6360be72009-06-13 18:20:51 +00003846 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003847 if (!ArgExpr) {
3848 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003849 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003850 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003851
3852 // C++ [temp.class.spec]p8:
3853 // A non-type argument is non-specialized if it is the name of a
3854 // non-type parameter. All other non-type arguments are
3855 // specialized.
3856 //
3857 // Below, we check the two conditions that only apply to
3858 // specialized non-type arguments, so skip any non-specialized
3859 // arguments.
3860 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003861 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003862 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003863 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003864 (Param->getIndex() != NTTP->getIndex() ||
3865 Param->getDepth() != NTTP->getDepth()))
3866 MirrorsPrimaryTemplate = false;
3867
Douglas Gregore94866f2009-06-12 21:21:02 +00003868 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003869 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003870
3871 // C++ [temp.class.spec]p9:
3872 // Within the argument list of a class template partial
3873 // specialization, the following restrictions apply:
3874 // -- A partially specialized non-type argument expression
3875 // shall not involve a template parameter of the partial
3876 // specialization except when the argument expression is a
3877 // simple identifier.
3878 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003879 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003880 diag::err_dependent_non_type_arg_in_partial_spec)
3881 << ArgExpr->getSourceRange();
3882 return true;
3883 }
3884
3885 // -- The type of a template parameter corresponding to a
3886 // specialized non-type argument shall not be dependent on a
3887 // parameter of the specialization.
3888 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003889 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003890 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3891 << Param->getType()
3892 << ArgExpr->getSourceRange();
3893 Diag(Param->getLocation(), diag::note_template_param_here);
3894 return true;
3895 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003896
3897 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003898 }
3899
3900 return false;
3901}
3902
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003903/// \brief Retrieve the previous declaration of the given declaration.
3904static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3905 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3906 return VD->getPreviousDeclaration();
3907 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3908 return FD->getPreviousDeclaration();
3909 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3910 return TD->getPreviousDeclaration();
3911 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3912 return TD->getPreviousDeclaration();
3913 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3914 return FTD->getPreviousDeclaration();
3915 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3916 return CTD->getPreviousDeclaration();
3917 return 0;
3918}
3919
John McCalld226f652010-08-21 09:40:31 +00003920DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003921Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3922 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00003923 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003924 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003925 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00003926 SourceLocation TemplateNameLoc,
3927 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00003928 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00003929 SourceLocation RAngleLoc,
3930 AttributeList *Attr,
3931 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003932 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00003933
Douglas Gregorcc636682009-02-17 23:15:12 +00003934 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00003935 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003936 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00003937 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3938
3939 if (!ClassTemplate) {
3940 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3941 << (Name.getAsTemplateDecl() &&
3942 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3943 return true;
3944 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003945
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003946 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003947 bool isPartialSpecialization = false;
3948
Douglas Gregor88b70942009-02-25 22:02:03 +00003949 // Check the validity of the template headers that introduce this
3950 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003951 // FIXME: We probably shouldn't complain about these headers for
3952 // friend declarations.
Douglas Gregor0167f3c2010-07-14 23:14:12 +00003953 bool Invalid = false;
Douglas Gregor05396e22009-08-25 17:23:04 +00003954 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00003955 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3956 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003957 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00003958 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00003959 isExplicitSpecialization,
3960 Invalid);
3961 if (Invalid)
3962 return true;
3963
Abramo Bagnara9b934882010-06-12 08:15:14 +00003964 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3965 if (TemplateParams)
3966 --NumMatchedTemplateParamLists;
3967
Douglas Gregor05396e22009-08-25 17:23:04 +00003968 if (TemplateParams && TemplateParams->size() > 0) {
3969 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003970
Douglas Gregor05396e22009-08-25 17:23:04 +00003971 // C++ [temp.class.spec]p10:
3972 // The template parameter list of a specialization shall not
3973 // contain default template argument values.
3974 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3975 Decl *Param = TemplateParams->getParam(I);
3976 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3977 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003978 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003979 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00003980 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003981 }
3982 } else if (NonTypeTemplateParmDecl *NTTP
3983 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3984 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003985 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003986 diag::err_default_arg_in_partial_spec)
3987 << DefArg->getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00003988 NTTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003989 }
3990 } else {
3991 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003992 if (TTP->hasDefaultArgument()) {
3993 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003994 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003995 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00003996 TTP->removeDefaultArgument();
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003997 }
3998 }
3999 }
Douglas Gregora735b202009-10-13 14:39:41 +00004000 } else if (TemplateParams) {
4001 if (TUK == TUK_Friend)
4002 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00004003 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00004004 SourceRange(TemplateParams->getTemplateLoc(),
4005 TemplateParams->getRAngleLoc()))
4006 << SourceRange(LAngleLoc, RAngleLoc);
4007 else
4008 isExplicitSpecialization = true;
4009 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00004010 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00004011 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004012 isExplicitSpecialization = true;
4013 }
Douglas Gregor88b70942009-02-25 22:02:03 +00004014
Douglas Gregorcc636682009-02-17 23:15:12 +00004015 // Check that the specialization uses the same tag kind as the
4016 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004017 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4018 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004019 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004020 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004021 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004022 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00004023 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004024 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00004025 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004026 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004027 diag::note_previous_use);
4028 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4029 }
4030
Douglas Gregor40808ce2009-03-09 23:48:35 +00004031 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004032 TemplateArgumentListInfo TemplateArgs;
4033 TemplateArgs.setLAngleLoc(LAngleLoc);
4034 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004035 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00004036
Douglas Gregorcc636682009-02-17 23:15:12 +00004037 // Check that the template argument list is well-formed for this
4038 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00004039 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4040 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00004041 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4042 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004043 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004044
Mike Stump1eb44332009-09-09 15:08:12 +00004045 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00004046 ClassTemplate->getTemplateParameters()->size()) &&
4047 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004048
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004049 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00004050 // corresponds to these arguments.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004051 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004052 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00004053 if (CheckClassTemplatePartialSpecializationArgs(
4054 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00004055 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00004056 return true;
4057
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004058 if (MirrorsPrimaryTemplate) {
4059 // C++ [temp.class.spec]p9b3:
4060 //
Mike Stump1eb44332009-09-09 15:08:12 +00004061 // -- The argument list of the specialization shall not be identical
4062 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004063 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00004064 << (TUK == TUK_Definition)
Douglas Gregor849b2432010-03-31 17:46:05 +00004065 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00004066 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004067 ClassTemplate->getIdentifier(),
4068 TemplateNameLoc,
4069 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00004070 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00004071 AS_none);
4072 }
4073
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004074 // FIXME: Diagnose friend partial specializations
4075
Douglas Gregorde090962010-02-09 00:37:32 +00004076 if (!Name.isDependent() &&
4077 !TemplateSpecializationType::anyDependentTemplateArguments(
4078 TemplateArgs.getArgumentArray(),
4079 TemplateArgs.size())) {
4080 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4081 << ClassTemplate->getDeclName();
4082 isPartialSpecialization = false;
Douglas Gregorde090962010-02-09 00:37:32 +00004083 }
4084 }
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004085
Douglas Gregorcc636682009-02-17 23:15:12 +00004086 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004087 ClassTemplateSpecializationDecl *PrevDecl = 0;
4088
4089 if (isPartialSpecialization)
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004090 // FIXME: Template parameter list matters, too
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004091 PrevDecl
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004092 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
4093 Converted.flatSize(),
4094 InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004095 else
4096 PrevDecl
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004097 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4098 Converted.flatSize(), InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00004099
4100 ClassTemplateSpecializationDecl *Specialization = 0;
4101
Douglas Gregor88b70942009-02-25 22:02:03 +00004102 // Check whether we can declare a class template specialization in
4103 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004104 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00004105 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00004106 TemplateNameLoc,
4107 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004108 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004109
Douglas Gregorb88e8882009-07-30 17:40:51 +00004110 // The canonical type
4111 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004112 if (PrevDecl &&
4113 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00004114 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004115 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004116 // arguments was referenced but not declared, or we're only
4117 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00004118 // declaration node as our own, updating its source location to
4119 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004120 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004121 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00004122 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00004123 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004124 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00004125 // Build the canonical type that describes the converted template
4126 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00004127 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4128 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb88e8882009-07-30 17:40:51 +00004129 Converted.getFlatArguments(),
4130 Converted.flatSize());
4131
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004132 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004133 ClassTemplatePartialSpecializationDecl *PrevPartial
4134 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00004135 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004136 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump1eb44332009-09-09 15:08:12 +00004137 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00004138 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004139 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00004140 TemplateNameLoc,
4141 TemplateParams,
4142 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00004143 Converted,
John McCalld5532b62009-11-23 01:53:49 +00004144 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00004145 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00004146 PrevPartial,
4147 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00004148 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00004149 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00004150 Partial->setTemplateParameterListsInfo(Context,
4151 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00004152 (TemplateParameterList**) TemplateParameterLists.release());
4153 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004154
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004155 if (!PrevPartial)
4156 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004157 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00004158
Douglas Gregored9c0f92009-10-29 00:04:11 +00004159 // If we are providing an explicit specialization of a member class
4160 // template specialization, make a note of that.
4161 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4162 PrevPartial->setMemberSpecialization();
4163
Douglas Gregor031a5882009-06-13 00:26:55 +00004164 // Check that all of the template parameters of the class template
4165 // partial specialization are deducible from the template
4166 // arguments. If not, this class template partial specialization
4167 // will never be used.
4168 llvm::SmallVector<bool, 8> DeducibleParams;
4169 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00004170 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004171 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00004172 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00004173 unsigned NumNonDeducible = 0;
4174 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
4175 if (!DeducibleParams[I])
4176 ++NumNonDeducible;
4177
4178 if (NumNonDeducible) {
4179 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
4180 << (NumNonDeducible > 1)
4181 << SourceRange(TemplateNameLoc, RAngleLoc);
4182 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4183 if (!DeducibleParams[I]) {
4184 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
4185 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00004186 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00004187 diag::note_partial_spec_unused_parameter)
4188 << Param->getDeclName();
4189 else
Mike Stump1eb44332009-09-09 15:08:12 +00004190 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00004191 diag::note_partial_spec_unused_parameter)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00004192 << "<anonymous>";
Douglas Gregor031a5882009-06-13 00:26:55 +00004193 }
4194 }
4195 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004196 } else {
4197 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004198 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004199 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00004200 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00004201 ClassTemplate->getDeclContext(),
4202 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004203 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00004204 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00004205 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004206 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00004207 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00004208 Specialization->setTemplateParameterListsInfo(Context,
4209 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00004210 (TemplateParameterList**) TemplateParameterLists.release());
4211 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004212
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004213 if (!PrevDecl)
4214 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregorb88e8882009-07-30 17:40:51 +00004215
4216 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004217 }
4218
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004219 // C++ [temp.expl.spec]p6:
4220 // If a template, a member template or the member of a class template is
4221 // explicitly specialized then that specialization shall be declared
4222 // before the first use of that specialization that would cause an implicit
4223 // instantiation to take place, in every translation unit in which such a
4224 // use occurs; no diagnostic is required.
4225 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004226 bool Okay = false;
4227 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4228 // Is there any previous explicit specialization declaration?
4229 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4230 Okay = true;
4231 break;
4232 }
4233 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004234
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004235 if (!Okay) {
4236 SourceRange Range(TemplateNameLoc, RAngleLoc);
4237 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4238 << Context.getTypeDeclType(Specialization) << Range;
4239
4240 Diag(PrevDecl->getPointOfInstantiation(),
4241 diag::note_instantiation_required_here)
4242 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004243 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004244 return true;
4245 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004246 }
4247
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004248 // If this is not a friend, note that this is an explicit specialization.
4249 if (TUK != TUK_Friend)
4250 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004251
4252 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004253 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00004254 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004255 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004256 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004257 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00004258 Diag(Def->getLocation(), diag::note_previous_definition);
4259 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00004260 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004261 }
4262 }
4263
Douglas Gregorfc705b82009-02-26 22:19:44 +00004264 // Build the fully-sugared type for this class template
4265 // specialization as the user wrote in the specialization
4266 // itself. This means that we'll pretty-print the type retrieved
4267 // from the specialization's declaration the way that the user
4268 // actually wrote the specialization, rather than formatting the
4269 // name based on the "canonical" representation used to store the
4270 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004271 TypeSourceInfo *WrittenTy
4272 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4273 TemplateArgs, CanonType);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004274 if (TUK != TUK_Friend) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004275 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor7e9b57b2010-07-06 18:33:12 +00004276 if (TemplateParams)
4277 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004278 }
Douglas Gregor40808ce2009-03-09 23:48:35 +00004279 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00004280
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004281 // C++ [temp.expl.spec]p9:
4282 // A template explicit specialization is in the scope of the
4283 // namespace in which the template was defined.
4284 //
4285 // We actually implement this paragraph where we set the semantic
4286 // context (in the creation of the ClassTemplateSpecializationDecl),
4287 // but we also maintain the lexical context where the actual
4288 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00004289 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004290
Douglas Gregorcc636682009-02-17 23:15:12 +00004291 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004292 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00004293 Specialization->startDefinition();
4294
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004295 if (TUK == TUK_Friend) {
4296 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4297 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00004298 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004299 /*FIXME:*/KWLoc);
4300 Friend->setAccess(AS_public);
4301 CurContext->addDecl(Friend);
4302 } else {
4303 // Add the specialization into its lexical context, so that it can
4304 // be seen when iterating through the list of declarations in that
4305 // context. However, specializations are not found by name lookup.
4306 CurContext->addDecl(Specialization);
4307 }
John McCalld226f652010-08-21 09:40:31 +00004308 return Specialization;
Douglas Gregorcc636682009-02-17 23:15:12 +00004309}
Douglas Gregord57959a2009-03-27 23:10:48 +00004310
John McCalld226f652010-08-21 09:40:31 +00004311Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00004312 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004313 Declarator &D) {
Douglas Gregore542c862009-06-23 23:11:28 +00004314 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4315}
4316
John McCalld226f652010-08-21 09:40:31 +00004317Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00004318 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004319 Declarator &D) {
Douglas Gregor52591bf2009-06-24 00:54:41 +00004320 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4321 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4322 "Not a function declarator!");
4323 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00004324
Douglas Gregor52591bf2009-06-24 00:54:41 +00004325 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00004326 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00004327 }
Mike Stump1eb44332009-09-09 15:08:12 +00004328
Douglas Gregor52591bf2009-06-24 00:54:41 +00004329 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004330
John McCalld226f652010-08-21 09:40:31 +00004331 Decl *DP = HandleDeclarator(ParentScope, D,
4332 move(TemplateParameterLists),
4333 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004334 if (FunctionTemplateDecl *FunctionTemplate
John McCalld226f652010-08-21 09:40:31 +00004335 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump1eb44332009-09-09 15:08:12 +00004336 return ActOnStartOfFunctionDef(FnBodyScope,
John McCalld226f652010-08-21 09:40:31 +00004337 FunctionTemplate->getTemplatedDecl());
4338 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4339 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4340 return 0;
Douglas Gregor52591bf2009-06-24 00:54:41 +00004341}
4342
John McCall75042392010-02-11 01:33:53 +00004343/// \brief Strips various properties off an implicit instantiation
4344/// that has just been explicitly specialized.
4345static void StripImplicitInstantiation(NamedDecl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00004346 D->dropAttrs();
John McCall75042392010-02-11 01:33:53 +00004347
4348 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4349 FD->setInlineSpecified(false);
4350 }
4351}
4352
Douglas Gregor454885e2009-10-15 15:54:05 +00004353/// \brief Diagnose cases where we have an explicit template specialization
4354/// before/after an explicit template instantiation, producing diagnostics
4355/// for those cases where they are required and determining whether the
4356/// new specialization/instantiation will have any effect.
4357///
Douglas Gregor454885e2009-10-15 15:54:05 +00004358/// \param NewLoc the location of the new explicit specialization or
4359/// instantiation.
4360///
4361/// \param NewTSK the kind of the new explicit specialization or instantiation.
4362///
4363/// \param PrevDecl the previous declaration of the entity.
4364///
4365/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4366///
4367/// \param PrevPointOfInstantiation if valid, indicates where the previus
4368/// declaration was instantiated (either implicitly or explicitly).
4369///
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004370/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregor454885e2009-10-15 15:54:05 +00004371/// specialization or instantiation has no effect and should be ignored.
4372///
4373/// \returns true if there was an error that should prevent the introduction of
4374/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00004375bool
4376Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4377 TemplateSpecializationKind NewTSK,
4378 NamedDecl *PrevDecl,
4379 TemplateSpecializationKind PrevTSK,
4380 SourceLocation PrevPointOfInstantiation,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004381 bool &HasNoEffect) {
4382 HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00004383
4384 switch (NewTSK) {
4385 case TSK_Undeclared:
4386 case TSK_ImplicitInstantiation:
4387 assert(false && "Don't check implicit instantiations here");
4388 return false;
4389
4390 case TSK_ExplicitSpecialization:
4391 switch (PrevTSK) {
4392 case TSK_Undeclared:
4393 case TSK_ExplicitSpecialization:
4394 // Okay, we're just specializing something that is either already
4395 // explicitly specialized or has merely been mentioned without any
4396 // instantiation.
4397 return false;
4398
4399 case TSK_ImplicitInstantiation:
4400 if (PrevPointOfInstantiation.isInvalid()) {
4401 // The declaration itself has not actually been instantiated, so it is
4402 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00004403 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00004404 return false;
4405 }
4406 // Fall through
4407
4408 case TSK_ExplicitInstantiationDeclaration:
4409 case TSK_ExplicitInstantiationDefinition:
4410 assert((PrevTSK == TSK_ImplicitInstantiation ||
4411 PrevPointOfInstantiation.isValid()) &&
4412 "Explicit instantiation without point of instantiation?");
4413
4414 // C++ [temp.expl.spec]p6:
4415 // If a template, a member template or the member of a class template
4416 // is explicitly specialized then that specialization shall be declared
4417 // before the first use of that specialization that would cause an
4418 // implicit instantiation to take place, in every translation unit in
4419 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004420 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4421 // Is there any previous explicit specialization declaration?
4422 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4423 return false;
4424 }
4425
Douglas Gregor0d035142009-10-27 18:42:08 +00004426 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00004427 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004428 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00004429 << (PrevTSK != TSK_ImplicitInstantiation);
4430
4431 return true;
4432 }
4433 break;
4434
4435 case TSK_ExplicitInstantiationDeclaration:
4436 switch (PrevTSK) {
4437 case TSK_ExplicitInstantiationDeclaration:
4438 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004439 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004440 return false;
4441
4442 case TSK_Undeclared:
4443 case TSK_ImplicitInstantiation:
4444 // We're explicitly instantiating something that may have already been
4445 // implicitly instantiated; that's fine.
4446 return false;
4447
4448 case TSK_ExplicitSpecialization:
4449 // C++0x [temp.explicit]p4:
4450 // For a given set of template parameters, if an explicit instantiation
4451 // of a template appears after a declaration of an explicit
4452 // specialization for that template, the explicit instantiation has no
4453 // effect.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004454 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004455 return false;
4456
4457 case TSK_ExplicitInstantiationDefinition:
4458 // C++0x [temp.explicit]p10:
4459 // If an entity is the subject of both an explicit instantiation
4460 // declaration and an explicit instantiation definition in the same
4461 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00004462 Diag(NewLoc,
4463 diag::err_explicit_instantiation_declaration_after_definition);
4464 Diag(PrevPointOfInstantiation,
4465 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00004466 assert(PrevPointOfInstantiation.isValid() &&
4467 "Explicit instantiation without point of instantiation?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004468 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004469 return false;
4470 }
4471 break;
4472
4473 case TSK_ExplicitInstantiationDefinition:
4474 switch (PrevTSK) {
4475 case TSK_Undeclared:
4476 case TSK_ImplicitInstantiation:
4477 // We're explicitly instantiating something that may have already been
4478 // implicitly instantiated; that's fine.
4479 return false;
4480
4481 case TSK_ExplicitSpecialization:
4482 // C++ DR 259, C++0x [temp.explicit]p4:
4483 // For a given set of template parameters, if an explicit
4484 // instantiation of a template appears after a declaration of
4485 // an explicit specialization for that template, the explicit
4486 // instantiation has no effect.
4487 //
4488 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00004489 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00004490 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00004491 if (!getLangOptions().CPlusPlus0x) {
4492 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00004493 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004494 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00004495 diag::note_previous_template_specialization);
4496 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004497 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004498 return false;
4499
4500 case TSK_ExplicitInstantiationDeclaration:
4501 // We're explicity instantiating a definition for something for which we
4502 // were previously asked to suppress instantiations. That's fine.
4503 return false;
4504
4505 case TSK_ExplicitInstantiationDefinition:
4506 // C++0x [temp.spec]p5:
4507 // For a given template and a given set of template-arguments,
4508 // - an explicit instantiation definition shall appear at most once
4509 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00004510 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00004511 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004512 Diag(PrevPointOfInstantiation,
4513 diag::note_previous_explicit_instantiation);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004514 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004515 return false;
4516 }
4517 break;
4518 }
4519
4520 assert(false && "Missing specialization/instantiation case?");
4521
4522 return false;
4523}
4524
John McCallaf2094e2010-04-08 09:05:18 +00004525/// \brief Perform semantic analysis for the given dependent function
4526/// template specialization. The only possible way to get a dependent
4527/// function template specialization is with a friend declaration,
4528/// like so:
4529///
4530/// template <class T> void foo(T);
4531/// template <class T> class A {
4532/// friend void foo<>(T);
4533/// };
4534///
4535/// There really isn't any useful analysis we can do here, so we
4536/// just store the information.
4537bool
4538Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4539 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4540 LookupResult &Previous) {
4541 // Remove anything from Previous that isn't a function template in
4542 // the correct context.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004543 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallaf2094e2010-04-08 09:05:18 +00004544 LookupResult::Filter F = Previous.makeFilter();
4545 while (F.hasNext()) {
4546 NamedDecl *D = F.next()->getUnderlyingDecl();
4547 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl7a126a42010-08-31 00:36:30 +00004548 !FDLookupContext->InEnclosingNamespaceSetOf(
4549 D->getDeclContext()->getRedeclContext()))
John McCallaf2094e2010-04-08 09:05:18 +00004550 F.erase();
4551 }
4552 F.done();
4553
4554 // Should this be diagnosed here?
4555 if (Previous.empty()) return true;
4556
4557 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4558 ExplicitTemplateArgs);
4559 return false;
4560}
4561
Abramo Bagnarae03db982010-05-20 15:32:11 +00004562/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004563/// specialization.
4564///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004565/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004566/// explicit function template specialization. On successful completion,
4567/// the function declaration \p FD will become a function template
4568/// specialization.
4569///
4570/// \param FD the function declaration, which will be updated to become a
4571/// function template specialization.
4572///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004573/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4574/// if any. Note that this may be valid info even when 0 arguments are
4575/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4576/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004577///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004578/// \param PrevDecl the set of declarations that may be specialized by
4579/// this function specialization.
4580bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004581Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004582 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004583 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004584 // The set of function template specializations that could match this
4585 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004586 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004587
Sebastian Redl7a126a42010-08-31 00:36:30 +00004588 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall68263142009-11-18 22:49:29 +00004589 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4590 I != E; ++I) {
4591 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4592 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004593 // Only consider templates found within the same semantic lookup scope as
4594 // FD.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004595 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4596 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004597 continue;
4598
4599 // C++ [temp.expl.spec]p11:
4600 // A trailing template-argument can be left unspecified in the
4601 // template-id naming an explicit function template specialization
4602 // provided it can be deduced from the function argument type.
4603 // Perform template argument deduction to determine whether we may be
4604 // specializing this template.
4605 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004606 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004607 FunctionDecl *Specialization = 0;
4608 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004609 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004610 FD->getType(),
4611 Specialization,
4612 Info)) {
4613 // FIXME: Template argument deduction failed; record why it failed, so
4614 // that we can provide nifty diagnostics.
4615 (void)TDK;
4616 continue;
4617 }
4618
4619 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004620 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004621 }
4622 }
4623
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004624 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004625 UnresolvedSetIterator Result
4626 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4627 TPOC_Other, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004628 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004629 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004630 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004631 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004632 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004633 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004634 return true;
John McCallc373d482010-01-27 01:50:18 +00004635
4636 // Ignore access information; it doesn't figure into redeclaration checking.
4637 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorc42b6522010-04-09 21:02:29 +00004638 Specialization->setLocation(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004639
4640 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004641 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004642
4643 // If this is a friend declaration, then we're not really declaring
4644 // an explicit specialization.
4645 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004646
Douglas Gregord5cb8762009-10-07 00:13:32 +00004647 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004648 if (!isFriend &&
4649 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004650 Specialization->getPrimaryTemplate(),
4651 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004652 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004653 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004654
4655 // C++ [temp.expl.spec]p6:
4656 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004657 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004658 // before the first use of that specialization that would cause an implicit
4659 // instantiation to take place, in every translation unit in which such a
4660 // use occurs; no diagnostic is required.
4661 FunctionTemplateSpecializationInfo *SpecInfo
4662 = Specialization->getTemplateSpecializationInfo();
4663 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004664
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004665 bool HasNoEffect = false;
John McCall7ad650f2010-03-24 07:46:06 +00004666 if (!isFriend &&
4667 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004668 TSK_ExplicitSpecialization,
4669 Specialization,
4670 SpecInfo->getTemplateSpecializationKind(),
4671 SpecInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004672 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004673 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004674
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004675 // Mark the prior declaration as an explicit specialization, so that later
4676 // clients know that this is an explicit specialization.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004677 if (!isFriend) {
John McCall7ad650f2010-03-24 07:46:06 +00004678 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004679 MarkUnusedFileScopedDecl(Specialization);
4680 }
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004681
4682 // Turn the given function declaration into a function template
4683 // specialization, with the template arguments from the previous
4684 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00004685 // Take copies of (semantic and syntactic) template argument lists.
4686 const TemplateArgumentList* TemplArgs = new (Context)
4687 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4688 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4689 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregor838db382010-02-11 01:19:42 +00004690 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00004691 TemplArgs, /*InsertPos=*/0,
4692 SpecInfo->getTemplateSpecializationKind(),
4693 TemplArgsAsWritten);
4694
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004695 // The "previous declaration" for this function template specialization is
4696 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004697 Previous.clear();
4698 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004699 return false;
4700}
4701
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004702/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004703/// specialization.
4704///
4705/// This routine performs all of the semantic analysis required for an
4706/// explicit member function specialization. On successful completion,
4707/// the function declaration \p FD will become a member function
4708/// specialization.
4709///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004710/// \param Member the member declaration, which will be updated to become a
4711/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004712///
John McCall68263142009-11-18 22:49:29 +00004713/// \param Previous the set of declarations, one of which may be specialized
4714/// by this function specialization; the set will be modified to contain the
4715/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004716bool
John McCall68263142009-11-18 22:49:29 +00004717Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004718 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00004719
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004720 // Try to find the member we are instantiating.
4721 NamedDecl *Instantiation = 0;
4722 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004723 MemberSpecializationInfo *MSInfo = 0;
4724
John McCall68263142009-11-18 22:49:29 +00004725 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004726 // Nowhere to look anyway.
4727 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004728 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4729 I != E; ++I) {
4730 NamedDecl *D = (*I)->getUnderlyingDecl();
4731 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004732 if (Context.hasSameType(Function->getType(), Method->getType())) {
4733 Instantiation = Method;
4734 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004735 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004736 break;
4737 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004738 }
4739 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004740 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004741 VarDecl *PrevVar;
4742 if (Previous.isSingleResult() &&
4743 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004744 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004745 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004746 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004747 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004748 }
4749 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004750 CXXRecordDecl *PrevRecord;
4751 if (Previous.isSingleResult() &&
4752 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4753 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004754 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004755 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004756 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004757 }
4758
4759 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004760 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004761 // specializations are always out-of-line, the caller will complain about
4762 // this mismatch later.
4763 return false;
4764 }
John McCall77e8b112010-04-13 20:37:33 +00004765
4766 // If this is a friend, just bail out here before we start turning
4767 // things into explicit specializations.
4768 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4769 // Preserve instantiation information.
4770 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4771 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4772 cast<CXXMethodDecl>(InstantiatedFrom),
4773 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4774 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4775 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4776 cast<CXXRecordDecl>(InstantiatedFrom),
4777 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4778 }
4779
4780 Previous.clear();
4781 Previous.addDecl(Instantiation);
4782 return false;
4783 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004784
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004785 // Make sure that this is a specialization of a member.
4786 if (!InstantiatedFrom) {
4787 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4788 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004789 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4790 return true;
4791 }
4792
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004793 // C++ [temp.expl.spec]p6:
4794 // If a template, a member template or the member of a class template is
4795 // explicitly specialized then that spe- cialization shall be declared
4796 // before the first use of that specialization that would cause an implicit
4797 // instantiation to take place, in every translation unit in which such a
4798 // use occurs; no diagnostic is required.
4799 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004800
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004801 bool HasNoEffect = false;
John McCall75042392010-02-11 01:33:53 +00004802 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4803 TSK_ExplicitSpecialization,
4804 Instantiation,
4805 MSInfo->getTemplateSpecializationKind(),
4806 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004807 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004808 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004809
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004810 // Check the scope of this explicit specialization.
4811 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004812 InstantiatedFrom,
4813 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004814 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004815 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004816
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004817 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004818 // the original declaration to note that it is an explicit specialization
4819 // (if it was previously an implicit instantiation). This latter step
4820 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004821 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004822 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4823 if (InstantiationFunction->getTemplateSpecializationKind() ==
4824 TSK_ImplicitInstantiation) {
4825 InstantiationFunction->setTemplateSpecializationKind(
4826 TSK_ExplicitSpecialization);
4827 InstantiationFunction->setLocation(Member->getLocation());
4828 }
4829
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004830 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4831 cast<CXXMethodDecl>(InstantiatedFrom),
4832 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004833 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004834 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004835 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4836 if (InstantiationVar->getTemplateSpecializationKind() ==
4837 TSK_ImplicitInstantiation) {
4838 InstantiationVar->setTemplateSpecializationKind(
4839 TSK_ExplicitSpecialization);
4840 InstantiationVar->setLocation(Member->getLocation());
4841 }
4842
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004843 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4844 cast<VarDecl>(InstantiatedFrom),
4845 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004846 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004847 } else {
4848 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004849 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4850 if (InstantiationClass->getTemplateSpecializationKind() ==
4851 TSK_ImplicitInstantiation) {
4852 InstantiationClass->setTemplateSpecializationKind(
4853 TSK_ExplicitSpecialization);
4854 InstantiationClass->setLocation(Member->getLocation());
4855 }
4856
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004857 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004858 cast<CXXRecordDecl>(InstantiatedFrom),
4859 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004860 }
4861
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004862 // Save the caller the trouble of having to figure out which declaration
4863 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004864 Previous.clear();
4865 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004866 return false;
4867}
4868
Douglas Gregor558c0322009-10-14 23:41:34 +00004869/// \brief Check the scope of an explicit instantiation.
Douglas Gregor669eed82010-07-13 00:10:04 +00004870///
4871/// \returns true if a serious error occurs, false otherwise.
4872static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregor558c0322009-10-14 23:41:34 +00004873 SourceLocation InstLoc,
4874 bool WasQualifiedName) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00004875 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
4876 DeclContext *CurContext = S.CurContext->getRedeclContext();
Douglas Gregor558c0322009-10-14 23:41:34 +00004877
Douglas Gregor669eed82010-07-13 00:10:04 +00004878 if (CurContext->isRecord()) {
4879 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4880 << D;
4881 return true;
4882 }
4883
Douglas Gregor558c0322009-10-14 23:41:34 +00004884 // C++0x [temp.explicit]p2:
4885 // An explicit instantiation shall appear in an enclosing namespace of its
4886 // template.
4887 //
4888 // This is DR275, which we do not retroactively apply to C++98/03.
4889 if (S.getLangOptions().CPlusPlus0x &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004890 !CurContext->Encloses(OrigContext)) {
4891 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
Douglas Gregor2166beb2010-05-11 17:39:34 +00004892 S.Diag(InstLoc,
4893 S.getLangOptions().CPlusPlus0x?
4894 diag::err_explicit_instantiation_out_of_scope
4895 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004896 << D << NS;
4897 else
Douglas Gregor2166beb2010-05-11 17:39:34 +00004898 S.Diag(InstLoc,
4899 S.getLangOptions().CPlusPlus0x?
4900 diag::err_explicit_instantiation_must_be_global
4901 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004902 << D;
4903 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00004904 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00004905 }
Sebastian Redl7a126a42010-08-31 00:36:30 +00004906
Douglas Gregor558c0322009-10-14 23:41:34 +00004907 // C++0x [temp.explicit]p2:
4908 // If the name declared in the explicit instantiation is an unqualified
4909 // name, the explicit instantiation shall appear in the namespace where
4910 // its template is declared or, if that namespace is inline (7.3.1), any
4911 // namespace from its enclosing namespace set.
4912 if (WasQualifiedName)
Douglas Gregor669eed82010-07-13 00:10:04 +00004913 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00004914
4915 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
Douglas Gregor669eed82010-07-13 00:10:04 +00004916 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00004917
Douglas Gregor2166beb2010-05-11 17:39:34 +00004918 S.Diag(InstLoc,
4919 S.getLangOptions().CPlusPlus0x?
4920 diag::err_explicit_instantiation_unqualified_wrong_namespace
4921 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Sebastian Redl7a126a42010-08-31 00:36:30 +00004922 << D << OrigContext;
Douglas Gregor558c0322009-10-14 23:41:34 +00004923 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00004924 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00004925}
4926
4927/// \brief Determine whether the given scope specifier has a template-id in it.
4928static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4929 if (!SS.isSet())
4930 return false;
4931
4932 // C++0x [temp.explicit]p2:
4933 // If the explicit instantiation is for a member function, a member class
4934 // or a static data member of a class template specialization, the name of
4935 // the class template specialization in the qualified-id for the member
4936 // name shall be a simple-template-id.
4937 //
4938 // C++98 has the same restriction, just worded differently.
4939 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4940 NNS; NNS = NNS->getPrefix())
4941 if (Type *T = NNS->getAsType())
4942 if (isa<TemplateSpecializationType>(T))
4943 return true;
4944
4945 return false;
4946}
4947
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004948// Explicit instantiation of a class template specialization
John McCallf312b1e2010-08-26 23:41:50 +00004949DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004950Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004951 SourceLocation ExternLoc,
4952 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004953 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004954 SourceLocation KWLoc,
4955 const CXXScopeSpec &SS,
4956 TemplateTy TemplateD,
4957 SourceLocation TemplateNameLoc,
4958 SourceLocation LAngleLoc,
4959 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004960 SourceLocation RAngleLoc,
4961 AttributeList *Attr) {
4962 // Find the class template we're specializing
4963 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004964 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004965 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4966
4967 // Check that the specialization uses the same tag kind as the
4968 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004969 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4970 assert(Kind != TTK_Enum &&
4971 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004972 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004973 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004974 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004975 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004976 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004977 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004978 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004979 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004980 diag::note_previous_use);
4981 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4982 }
4983
Douglas Gregor558c0322009-10-14 23:41:34 +00004984 // C++0x [temp.explicit]p2:
4985 // There are two forms of explicit instantiation: an explicit instantiation
4986 // definition and an explicit instantiation declaration. An explicit
4987 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00004988 TemplateSpecializationKind TSK
4989 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4990 : TSK_ExplicitInstantiationDeclaration;
4991
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004992 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004993 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004994 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004995
4996 // Check that the template argument list is well-formed for this
4997 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00004998 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4999 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00005000 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5001 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005002 return true;
5003
Mike Stump1eb44332009-09-09 15:08:12 +00005004 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005005 ClassTemplate->getTemplateParameters()->size()) &&
5006 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00005007
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005008 // Find the class template specialization declaration that
5009 // corresponds to these arguments.
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005010 void *InsertPos = 0;
5011 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005012 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
5013 Converted.flatSize(), InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005014
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005015 TemplateSpecializationKind PrevDecl_TSK
5016 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
5017
Douglas Gregord5cb8762009-10-07 00:13:32 +00005018 // C++0x [temp.explicit]p2:
5019 // [...] An explicit instantiation shall appear in an enclosing
5020 // namespace of its template. [...]
5021 //
5022 // This is C++ DR 275.
Douglas Gregor669eed82010-07-13 00:10:04 +00005023 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
5024 SS.isSet()))
5025 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00005026
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005027 ClassTemplateSpecializationDecl *Specialization = 0;
5028
Douglas Gregord78f5982009-11-25 06:01:46 +00005029 bool ReusedDecl = false;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005030 bool HasNoEffect = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005031 if (PrevDecl) {
Douglas Gregor0d035142009-10-27 18:42:08 +00005032 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005033 PrevDecl, PrevDecl_TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005034 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005035 HasNoEffect))
John McCalld226f652010-08-21 09:40:31 +00005036 return PrevDecl;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005037
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005038 // Even though HasNoEffect == true means that this explicit instantiation
5039 // has no effect on semantics, we go on to put its syntax in the AST.
5040
5041 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
5042 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor52604ab2009-09-11 21:19:12 +00005043 // Since the only prior class template specialization with these
5044 // arguments was referenced but not declared, reuse that
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005045 // declaration node as our own, updating the source location
5046 // for the template name to reflect our new declaration.
5047 // (Other source locations will be updated later.)
Douglas Gregor52604ab2009-09-11 21:19:12 +00005048 Specialization = PrevDecl;
5049 Specialization->setLocation(TemplateNameLoc);
5050 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00005051 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00005052 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005053 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005054
Douglas Gregor52604ab2009-09-11 21:19:12 +00005055 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005056 // Create a new class template specialization declaration node for
5057 // this explicit specialization.
5058 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00005059 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005060 ClassTemplate->getDeclContext(),
5061 TemplateNameLoc,
5062 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00005063 Converted, PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00005064 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005065
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005066 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005067 // Insert the new specialization.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005068 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005069 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005070 }
5071
5072 // Build the fully-sugared type for this explicit instantiation as
5073 // the user wrote in the explicit instantiation itself. This means
5074 // that we'll pretty-print the type retrieved from the
5075 // specialization's declaration the way that the user actually wrote
5076 // the explicit instantiation, rather than formatting the name based
5077 // on the "canonical" representation used to store the template
5078 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00005079 TypeSourceInfo *WrittenTy
5080 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5081 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005082 Context.getTypeDeclType(Specialization));
5083 Specialization->setTypeAsWritten(WrittenTy);
5084 TemplateArgsIn.release();
5085
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005086 // Set source locations for keywords.
5087 Specialization->setExternLoc(ExternLoc);
5088 Specialization->setTemplateKeywordLoc(TemplateLoc);
5089
5090 // Add the explicit instantiation into its lexical context. However,
5091 // since explicit instantiations are never found by name lookup, we
5092 // just put it into the declaration context directly.
5093 Specialization->setLexicalDeclContext(CurContext);
5094 CurContext->addDecl(Specialization);
5095
5096 // Syntax is now OK, so return if it has no other effect on semantics.
5097 if (HasNoEffect) {
5098 // Set the template specialization kind.
5099 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005100 return Specialization;
Douglas Gregord78f5982009-11-25 06:01:46 +00005101 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005102
5103 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005104 // A definition of a class template or class member template
5105 // shall be in scope at the point of the explicit instantiation of
5106 // the class template or class member template.
5107 //
5108 // This check comes when we actually try to perform the
5109 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005110 ClassTemplateSpecializationDecl *Def
5111 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005112 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005113 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005114 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005115 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005116 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005117 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5118 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005119
Douglas Gregor0d035142009-10-27 18:42:08 +00005120 // Instantiate the members of this class template specialization.
5121 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005122 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005123 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00005124 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5125
5126 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5127 // TSK_ExplicitInstantiationDefinition
5128 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5129 TSK == TSK_ExplicitInstantiationDefinition)
5130 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005131
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005132 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005133 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005134
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005135 // Set the template specialization kind.
5136 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005137 return Specialization;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005138}
5139
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005140// Explicit instantiation of a member class of a class template.
John McCalld226f652010-08-21 09:40:31 +00005141DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00005142Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00005143 SourceLocation ExternLoc,
5144 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005145 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005146 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005147 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005148 IdentifierInfo *Name,
5149 SourceLocation NameLoc,
5150 AttributeList *Attr) {
5151
Douglas Gregor402abb52009-05-28 23:31:59 +00005152 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00005153 bool IsDependent = false;
John McCallf312b1e2010-08-26 23:41:50 +00005154 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCalld226f652010-08-21 09:40:31 +00005155 KWLoc, SS, Name, NameLoc, Attr, AS_none,
5156 MultiTemplateParamsArg(*this, 0, 0),
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005157 Owned, IsDependent, false,
5158 TypeResult());
John McCallc4e70192009-09-11 04:59:25 +00005159 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
5160
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005161 if (!TagD)
5162 return true;
5163
John McCalld226f652010-08-21 09:40:31 +00005164 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005165 if (Tag->isEnum()) {
5166 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
5167 << Context.getTypeDeclType(Tag);
5168 return true;
5169 }
5170
Douglas Gregord0c87372009-05-27 17:30:49 +00005171 if (Tag->isInvalidDecl())
5172 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00005173
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005174 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
5175 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
5176 if (!Pattern) {
5177 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
5178 << Context.getTypeDeclType(Record);
5179 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
5180 return true;
5181 }
5182
Douglas Gregor558c0322009-10-14 23:41:34 +00005183 // C++0x [temp.explicit]p2:
5184 // If the explicit instantiation is for a class or member class, the
5185 // elaborated-type-specifier in the declaration shall include a
5186 // simple-template-id.
5187 //
5188 // C++98 has the same restriction, just worded differently.
5189 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregora2dd8282010-06-16 16:26:47 +00005190 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005191 << Record << SS.getRange();
5192
5193 // C++0x [temp.explicit]p2:
5194 // There are two forms of explicit instantiation: an explicit instantiation
5195 // definition and an explicit instantiation declaration. An explicit
5196 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00005197 TemplateSpecializationKind TSK
5198 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5199 : TSK_ExplicitInstantiationDeclaration;
5200
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005201 // C++0x [temp.explicit]p2:
5202 // [...] An explicit instantiation shall appear in an enclosing
5203 // namespace of its template. [...]
5204 //
5205 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00005206 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00005207
5208 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00005209 CXXRecordDecl *PrevDecl
5210 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00005211 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00005212 PrevDecl = Record;
5213 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00005214 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005215 bool HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00005216 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00005217 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00005218 PrevDecl,
5219 MSInfo->getTemplateSpecializationKind(),
5220 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005221 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005222 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005223 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00005224 return TagD;
5225 }
5226
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005227 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00005228 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005229 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005230 // C++ [temp.explicit]p3:
5231 // A definition of a member class of a class template shall be in scope
5232 // at the point of an explicit instantiation of the member class.
5233 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00005234 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005235 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00005236 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
5237 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005238 Diag(Pattern->getLocation(), diag::note_forward_declaration)
5239 << Pattern;
5240 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00005241 } else {
5242 if (InstantiateClass(NameLoc, Record, Def,
5243 getTemplateInstantiationArgs(Record),
5244 TSK))
5245 return true;
5246
Douglas Gregor952b0172010-02-11 01:04:33 +00005247 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00005248 if (!RecordDef)
5249 return true;
5250 }
5251 }
5252
5253 // Instantiate all of the members of the class.
5254 InstantiateClassMembers(NameLoc, RecordDef,
5255 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005256
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005257 if (TSK == TSK_ExplicitInstantiationDefinition)
5258 MarkVTableUsed(NameLoc, RecordDef, true);
5259
Mike Stump390b4cc2009-05-16 07:39:55 +00005260 // FIXME: We don't have any representation for explicit instantiations of
5261 // member classes. Such a representation is not needed for compilation, but it
5262 // should be available for clients that want to see all of the declarations in
5263 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005264 return TagD;
5265}
5266
John McCallf312b1e2010-08-26 23:41:50 +00005267DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
5268 SourceLocation ExternLoc,
5269 SourceLocation TemplateLoc,
5270 Declarator &D) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005271 // Explicit instantiations always require a name.
Abramo Bagnara25777432010-08-11 22:01:17 +00005272 // TODO: check if/when DNInfo should replace Name.
5273 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5274 DeclarationName Name = NameInfo.getName();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005275 if (!Name) {
5276 if (!D.isInvalidType())
5277 Diag(D.getDeclSpec().getSourceRange().getBegin(),
5278 diag::err_explicit_instantiation_requires_name)
5279 << D.getDeclSpec().getSourceRange()
5280 << D.getSourceRange();
5281
5282 return true;
5283 }
5284
5285 // The scope passed in may not be a decl scope. Zip up the scope tree until
5286 // we find one that is.
5287 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5288 (S->getFlags() & Scope::TemplateParamScope) != 0)
5289 S = S->getParent();
5290
5291 // Determine the type of the declaration.
John McCallbf1a0282010-06-04 23:28:52 +00005292 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5293 QualType R = T->getType();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005294 if (R.isNull())
5295 return true;
5296
5297 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5298 // Cannot explicitly instantiate a typedef.
5299 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5300 << Name;
5301 return true;
5302 }
5303
Douglas Gregor663b5a02009-10-14 20:14:33 +00005304 // C++0x [temp.explicit]p1:
5305 // [...] An explicit instantiation of a function template shall not use the
5306 // inline or constexpr specifiers.
5307 // Presumably, this also applies to member functions of class templates as
5308 // well.
5309 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5310 Diag(D.getDeclSpec().getInlineSpecLoc(),
5311 diag::err_explicit_instantiation_inline)
Douglas Gregor849b2432010-03-31 17:46:05 +00005312 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00005313
5314 // FIXME: check for constexpr specifier.
5315
Douglas Gregor558c0322009-10-14 23:41:34 +00005316 // C++0x [temp.explicit]p2:
5317 // There are two forms of explicit instantiation: an explicit instantiation
5318 // definition and an explicit instantiation declaration. An explicit
5319 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00005320 TemplateSpecializationKind TSK
5321 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5322 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00005323
Abramo Bagnara25777432010-08-11 22:01:17 +00005324 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005325 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005326
5327 if (!R->isFunctionType()) {
5328 // C++ [temp.explicit]p1:
5329 // A [...] static data member of a class template can be explicitly
5330 // instantiated from the member definition associated with its class
5331 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00005332 if (Previous.isAmbiguous())
5333 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005334
John McCall1bcee0a2009-12-02 08:25:40 +00005335 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005336 if (!Prev || !Prev->isStaticDataMember()) {
5337 // We expect to see a data data member here.
5338 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5339 << Name;
5340 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5341 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00005342 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005343 return true;
5344 }
5345
5346 if (!Prev->getInstantiatedFromStaticDataMember()) {
5347 // FIXME: Check for explicit specialization?
5348 Diag(D.getIdentifierLoc(),
5349 diag::err_explicit_instantiation_data_member_not_instantiated)
5350 << Prev;
5351 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5352 // FIXME: Can we provide a note showing where this was declared?
5353 return true;
5354 }
5355
Douglas Gregor558c0322009-10-14 23:41:34 +00005356 // C++0x [temp.explicit]p2:
5357 // If the explicit instantiation is for a member function, a member class
5358 // or a static data member of a class template specialization, the name of
5359 // the class template specialization in the qualified-id for the member
5360 // name shall be a simple-template-id.
5361 //
5362 // C++98 has the same restriction, just worded differently.
5363 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5364 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005365 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005366 << Prev << D.getCXXScopeSpec().getRange();
5367
5368 // Check the scope of this explicit instantiation.
5369 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5370
Douglas Gregor454885e2009-10-15 15:54:05 +00005371 // Verify that it is okay to explicitly instantiate here.
5372 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5373 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005374 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005375 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00005376 MSInfo->getTemplateSpecializationKind(),
5377 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005378 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005379 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005380 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005381 return (Decl*) 0;
Douglas Gregor454885e2009-10-15 15:54:05 +00005382
Douglas Gregord5a423b2009-09-25 18:43:00 +00005383 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005384 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005385 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005386 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005387
5388 // FIXME: Create an ExplicitInstantiation node?
John McCalld226f652010-08-21 09:40:31 +00005389 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005390 }
5391
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005392 // If the declarator is a template-id, translate the parser's template
5393 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00005394 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00005395 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005396 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5397 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00005398 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5399 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00005400 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5401 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00005402 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00005403 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00005404 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00005405 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00005406 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005407
Douglas Gregord5a423b2009-09-25 18:43:00 +00005408 // C++ [temp.explicit]p1:
5409 // A [...] function [...] can be explicitly instantiated from its template.
5410 // A member function [...] of a class template can be explicitly
5411 // instantiated from the member definition associated with its class
5412 // template.
John McCallc373d482010-01-27 01:50:18 +00005413 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005414 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5415 P != PEnd; ++P) {
5416 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00005417 if (!HasExplicitTemplateArgs) {
5418 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5419 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5420 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00005421
John McCallc373d482010-01-27 01:50:18 +00005422 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00005423 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5424 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00005425 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00005426 }
5427 }
5428
5429 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5430 if (!FunTmpl)
5431 continue;
5432
John McCall5769d612010-02-08 23:07:23 +00005433 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005434 FunctionDecl *Specialization = 0;
5435 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00005436 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00005437 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00005438 R, Specialization, Info)) {
5439 // FIXME: Keep track of almost-matches?
5440 (void)TDK;
5441 continue;
5442 }
5443
John McCallc373d482010-01-27 01:50:18 +00005444 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005445 }
5446
5447 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005448 UnresolvedSetIterator Result
5449 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregord5a423b2009-09-25 18:43:00 +00005450 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005451 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5452 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5453 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00005454
John McCallc373d482010-01-27 01:50:18 +00005455 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00005456 return true;
John McCallc373d482010-01-27 01:50:18 +00005457
5458 // Ignore access control bits, we don't need them for redeclaration checking.
5459 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005460
Douglas Gregor0a897e32009-10-15 17:21:20 +00005461 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005462 Diag(D.getIdentifierLoc(),
5463 diag::err_explicit_instantiation_member_function_not_instantiated)
5464 << Specialization
5465 << (Specialization->getTemplateSpecializationKind() ==
5466 TSK_ExplicitSpecialization);
5467 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5468 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005469 }
Douglas Gregor558c0322009-10-14 23:41:34 +00005470
Douglas Gregor0a897e32009-10-15 17:21:20 +00005471 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00005472 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5473 PrevDecl = Specialization;
5474
Douglas Gregor0a897e32009-10-15 17:21:20 +00005475 if (PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005476 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005477 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00005478 PrevDecl,
5479 PrevDecl->getTemplateSpecializationKind(),
5480 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005481 HasNoEffect))
Douglas Gregor0a897e32009-10-15 17:21:20 +00005482 return true;
5483
5484 // FIXME: We may still want to build some representation of this
5485 // explicit specialization.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005486 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005487 return (Decl*) 0;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005488 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00005489
5490 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00005491
5492 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005493 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor0a897e32009-10-15 17:21:20 +00005494
Douglas Gregor558c0322009-10-14 23:41:34 +00005495 // C++0x [temp.explicit]p2:
5496 // If the explicit instantiation is for a member function, a member class
5497 // or a static data member of a class template specialization, the name of
5498 // the class template specialization in the qualified-id for the member
5499 // name shall be a simple-template-id.
5500 //
5501 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005502 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005503 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00005504 D.getCXXScopeSpec().isSet() &&
5505 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5506 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005507 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005508 << Specialization << D.getCXXScopeSpec().getRange();
5509
5510 CheckExplicitInstantiationScope(*this,
5511 FunTmpl? (NamedDecl *)FunTmpl
5512 : Specialization->getInstantiatedFromMemberFunction(),
5513 D.getIdentifierLoc(),
5514 D.getCXXScopeSpec().isSet());
5515
Douglas Gregord5a423b2009-09-25 18:43:00 +00005516 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCalld226f652010-08-21 09:40:31 +00005517 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005518}
5519
John McCallf312b1e2010-08-26 23:41:50 +00005520TypeResult
John McCallc4e70192009-09-11 04:59:25 +00005521Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5522 const CXXScopeSpec &SS, IdentifierInfo *Name,
5523 SourceLocation TagLoc, SourceLocation NameLoc) {
5524 // This has to hold, because SS is expected to be defined.
5525 assert(Name && "Expected a name in a dependent tag");
5526
5527 NestedNameSpecifier *NNS
5528 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5529 if (!NNS)
5530 return true;
5531
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005532 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005533
Douglas Gregor48c89f42010-04-24 16:38:41 +00005534 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5535 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005536 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00005537 return true;
5538 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005539
5540 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallb3d87482010-08-24 05:47:05 +00005541 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCallc4e70192009-09-11 04:59:25 +00005542}
5543
John McCallf312b1e2010-08-26 23:41:50 +00005544TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005545Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5546 const CXXScopeSpec &SS, const IdentifierInfo &II,
5547 SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005548 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00005549 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5550 if (!NNS)
5551 return true;
5552
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005553 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5554 !getLangOptions().CPlusPlus0x)
5555 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5556 << FixItHint::CreateRemoval(TypenameLoc);
5557
Douglas Gregor107de902010-04-24 15:35:55 +00005558 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005559 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00005560 if (T.isNull())
5561 return true;
John McCall63b43852010-04-29 23:50:39 +00005562
5563 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5564 if (isa<DependentNameType>(T)) {
5565 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005566 TL.setKeywordLoc(TypenameLoc);
5567 TL.setQualifierRange(SS.getRange());
5568 TL.setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005569 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005570 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005571 TL.setKeywordLoc(TypenameLoc);
5572 TL.setQualifierRange(SS.getRange());
5573 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005574 }
5575
John McCallb3d87482010-08-24 05:47:05 +00005576 return CreateParsedType(T, TSI);
Douglas Gregord57959a2009-03-27 23:10:48 +00005577}
5578
John McCallf312b1e2010-08-26 23:41:50 +00005579TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005580Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5581 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallb3d87482010-08-24 05:47:05 +00005582 ParsedType Ty) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005583 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5584 !getLangOptions().CPlusPlus0x)
5585 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5586 << FixItHint::CreateRemoval(TypenameLoc);
5587
John McCall4e449832010-05-28 23:32:21 +00005588 TypeSourceInfo *InnerTSI = 0;
5589 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCall4e449832010-05-28 23:32:21 +00005590
5591 assert(isa<TemplateSpecializationType>(T) &&
5592 "Expected a template specialization type");
Douglas Gregor17343172009-04-01 00:28:59 +00005593
Douglas Gregor6946baf2009-09-02 13:05:45 +00005594 if (computeDeclContext(SS, false)) {
5595 // If we can compute a declaration context, then the "typename"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005596 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor6946baf2009-09-02 13:05:45 +00005597 // track of the nested-name-specifier.
John McCall4e449832010-05-28 23:32:21 +00005598
5599 // Push the inner type, preserving its source locations if possible.
5600 TypeLocBuilder Builder;
5601 if (InnerTSI)
5602 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5603 else
5604 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5605
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005606 /* Note: NNS already embedded in template specialization type T. */
5607 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCall4e449832010-05-28 23:32:21 +00005608 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5609 TL.setKeywordLoc(TypenameLoc);
5610 TL.setQualifierRange(SS.getRange());
5611
5612 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallb3d87482010-08-24 05:47:05 +00005613 return CreateParsedType(T, TSI);
Douglas Gregor6946baf2009-09-02 13:05:45 +00005614 }
Mike Stump1eb44332009-09-09 15:08:12 +00005615
John McCall33500952010-06-11 00:33:02 +00005616 // TODO: it's really silly that we make a template specialization
5617 // type earlier only to drop it again here.
5618 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5619 DependentTemplateName *DTN =
5620 TST->getTemplateName().getAsDependentTemplateName();
5621 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005622 assert(DTN->getQualifier()
5623 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5624 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5625 DTN->getQualifier(),
John McCall33500952010-06-11 00:33:02 +00005626 DTN->getIdentifier(),
5627 TST->getNumArgs(),
5628 TST->getArgs());
John McCall63b43852010-04-29 23:50:39 +00005629 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCall33500952010-06-11 00:33:02 +00005630 DependentTemplateSpecializationTypeLoc TL =
5631 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5632 if (InnerTSI) {
5633 TemplateSpecializationTypeLoc TSTL =
5634 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5635 TL.setLAngleLoc(TSTL.getLAngleLoc());
5636 TL.setRAngleLoc(TSTL.getRAngleLoc());
5637 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5638 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5639 } else {
5640 TL.initializeLocal(SourceLocation());
5641 }
John McCall4e449832010-05-28 23:32:21 +00005642 TL.setKeywordLoc(TypenameLoc);
5643 TL.setQualifierRange(SS.getRange());
John McCallb3d87482010-08-24 05:47:05 +00005644 return CreateParsedType(T, TSI);
Douglas Gregor17343172009-04-01 00:28:59 +00005645}
5646
Douglas Gregord57959a2009-03-27 23:10:48 +00005647/// \brief Build the type that describes a C++ typename specifier,
5648/// e.g., "typename T::type".
5649QualType
Douglas Gregor107de902010-04-24 15:35:55 +00005650Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5651 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005652 SourceLocation KeywordLoc, SourceRange NNSRange,
5653 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00005654 CXXScopeSpec SS;
5655 SS.setScopeRep(NNS);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005656 SS.setRange(NNSRange);
Douglas Gregord57959a2009-03-27 23:10:48 +00005657
John McCall77bb1aa2010-05-01 00:40:08 +00005658 DeclContext *Ctx = computeDeclContext(SS);
5659 if (!Ctx) {
5660 // If the nested-name-specifier is dependent and couldn't be
5661 // resolved to a type, build a typename type.
5662 assert(NNS->isDependent());
5663 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00005664 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005665
John McCall77bb1aa2010-05-01 00:40:08 +00005666 // If the nested-name-specifier refers to the current instantiation,
5667 // the "typename" keyword itself is superfluous. In C++03, the
5668 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5669 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregor732281d2010-06-14 22:07:54 +00005670 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00005671
John McCall77bb1aa2010-05-01 00:40:08 +00005672 if (RequireCompleteDeclContext(SS, Ctx))
5673 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00005674
5675 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005676 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005677 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005678 unsigned DiagID = 0;
5679 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005680 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005681 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005682 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005683 break;
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005684
5685 case LookupResult::NotFoundInCurrentInstantiation:
5686 // Okay, it's a member of an unknown instantiation.
Douglas Gregor107de902010-04-24 15:35:55 +00005687 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00005688
5689 case LookupResult::Found:
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005690 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005691 // We found a type. Build an ElaboratedType, since the
5692 // typename-specifier was just sugar.
5693 return Context.getElaboratedType(ETK_Typename, NNS,
5694 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00005695 }
5696
5697 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00005698 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00005699 break;
5700
John McCall7ba107a2009-11-18 02:36:19 +00005701 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005702 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00005703 return QualType();
5704
Douglas Gregord57959a2009-03-27 23:10:48 +00005705 case LookupResult::FoundOverloaded:
5706 DiagID = diag::err_typename_nested_not_type;
5707 Referenced = *Result.begin();
5708 break;
5709
John McCall6e247262009-10-10 05:48:19 +00005710 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00005711 return QualType();
5712 }
5713
5714 // If we get here, it's because name lookup did not find a
5715 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005716 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5717 IILoc);
5718 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00005719 if (Referenced)
5720 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5721 << Name;
5722 return QualType();
5723}
Douglas Gregor4a959d82009-08-06 16:20:37 +00005724
5725namespace {
5726 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00005727 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00005728 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00005729 SourceLocation Loc;
5730 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00005731
Douglas Gregor4a959d82009-08-06 16:20:37 +00005732 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00005733 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5734
Mike Stump1eb44332009-09-09 15:08:12 +00005735 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005736 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005737 DeclarationName Entity)
5738 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00005739 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00005740
5741 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00005742 /// transformed.
5743 ///
5744 /// For the purposes of type reconstruction, a type has already been
5745 /// transformed if it is NULL or if it is not dependent.
5746 bool AlreadyTransformed(QualType T) {
5747 return T.isNull() || !T->isDependentType();
5748 }
Mike Stump1eb44332009-09-09 15:08:12 +00005749
5750 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00005751 /// rebuilt.
5752 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00005753
Douglas Gregor4a959d82009-08-06 16:20:37 +00005754 /// \brief Returns the name of the entity whose type is being rebuilt.
5755 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00005756
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005757 /// \brief Sets the "base" location and entity when that
5758 /// information is known based on another transformation.
5759 void setBase(SourceLocation Loc, DeclarationName Entity) {
5760 this->Loc = Loc;
5761 this->Entity = Entity;
5762 }
Douglas Gregor4a959d82009-08-06 16:20:37 +00005763 };
5764}
5765
Douglas Gregor4a959d82009-08-06 16:20:37 +00005766/// \brief Rebuilds a type within the context of the current instantiation.
5767///
Mike Stump1eb44332009-09-09 15:08:12 +00005768/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00005769/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00005770/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00005771/// partial specialization thereof). This routine will rebuild that type now
5772/// that we have entered the declarator's scope, which may produce different
5773/// canonical types, e.g.,
5774///
5775/// \code
5776/// template<typename T>
5777/// struct X {
5778/// typedef T* pointer;
5779/// pointer data();
5780/// };
5781///
5782/// template<typename T>
5783/// typename X<T>::pointer X<T>::data() { ... }
5784/// \endcode
5785///
Douglas Gregor4714c122010-03-31 17:34:00 +00005786/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005787/// since we do not know that we can look into X<T> when we parsed the type.
5788/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005789/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00005790/// as the canonical type of T*, allowing the return types of the out-of-line
5791/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00005792TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5793 SourceLocation Loc,
5794 DeclarationName Name) {
5795 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00005796 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00005797
Douglas Gregor4a959d82009-08-06 16:20:37 +00005798 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5799 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00005800}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005801
John McCall60d7b3a2010-08-24 06:29:42 +00005802ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallb3d87482010-08-24 05:47:05 +00005803 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5804 DeclarationName());
5805 return Rebuilder.TransformExpr(E);
5806}
5807
John McCall63b43852010-04-29 23:50:39 +00005808bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5809 if (SS.isInvalid()) return true;
John McCall31f17ec2010-04-27 00:57:59 +00005810
5811 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5812 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5813 DeclarationName());
5814 NestedNameSpecifier *Rebuilt =
5815 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall63b43852010-04-29 23:50:39 +00005816 if (!Rebuilt) return true;
5817
5818 SS.setScopeRep(Rebuilt);
5819 return false;
John McCall31f17ec2010-04-27 00:57:59 +00005820}
5821
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005822/// \brief Produces a formatted string that describes the binding of
5823/// template parameters to template arguments.
5824std::string
5825Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5826 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005827 // FIXME: For variadic templates, we'll need to get the structured list.
5828 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5829 Args.flat_size());
5830}
5831
5832std::string
5833Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5834 const TemplateArgument *Args,
5835 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005836 std::string Result;
5837
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005838 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005839 return Result;
5840
5841 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005842 if (I >= NumArgs)
5843 break;
5844
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005845 if (I == 0)
5846 Result += "[with ";
5847 else
5848 Result += ", ";
5849
5850 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5851 Result += Id->getName();
5852 } else {
5853 Result += '$';
5854 Result += llvm::utostr(I);
5855 }
5856
5857 Result += " = ";
5858
5859 switch (Args[I].getKind()) {
5860 case TemplateArgument::Null:
5861 Result += "<no value>";
5862 break;
5863
5864 case TemplateArgument::Type: {
5865 std::string TypeStr;
5866 Args[I].getAsType().getAsStringInternal(TypeStr,
5867 Context.PrintingPolicy);
5868 Result += TypeStr;
5869 break;
5870 }
5871
5872 case TemplateArgument::Declaration: {
5873 bool Unnamed = true;
5874 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5875 if (ND->getDeclName()) {
5876 Unnamed = false;
5877 Result += ND->getNameAsString();
5878 }
5879 }
5880
5881 if (Unnamed) {
5882 Result += "<anonymous>";
5883 }
5884 break;
5885 }
5886
Douglas Gregor788cd062009-11-11 01:00:40 +00005887 case TemplateArgument::Template: {
5888 std::string Str;
5889 llvm::raw_string_ostream OS(Str);
5890 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5891 Result += OS.str();
5892 break;
5893 }
5894
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005895 case TemplateArgument::Integral: {
5896 Result += Args[I].getAsIntegral()->toString(10);
5897 break;
5898 }
5899
5900 case TemplateArgument::Expression: {
Douglas Gregor77e2c672010-04-29 04:55:13 +00005901 // FIXME: This is non-optimal, since we're regurgitating the
5902 // expression we were given.
5903 std::string Str;
5904 {
5905 llvm::raw_string_ostream OS(Str);
5906 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5907 Context.PrintingPolicy);
5908 }
5909 Result += Str;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005910 break;
5911 }
5912
5913 case TemplateArgument::Pack:
5914 // FIXME: Format template argument packs
5915 Result += "<template argument pack>";
5916 break;
5917 }
5918 }
5919
5920 Result += ']';
5921 return Result;
5922}